diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/.github/workflows/run-unit-tests.yaml b/.github/workflows/run-unit-tests.yaml new file mode 100644 index 0000000..927560e --- /dev/null +++ b/.github/workflows/run-unit-tests.yaml @@ -0,0 +1,46 @@ +name: Java CI + +on: [push] + +permissions: + contents: read + checks: write + id-token: write + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + + - name: Install Xvfb + run: | + sudo apt-get update + sudo apt-get install -y xvfb + continue-on-error: true + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + # build everything (includes running unit tests) + - name: Execute Gradle build + run: xvfb-run -a ./gradlew build + + # report the results + - name: Publish Test Report + uses: mikepenz/action-junit-report@v3 + if: success() || failure() # always run even if the previous step fails + with: + report_paths: '**/build/test-results/test/TEST-*.xml' + detailed_summary: true # display detailed summary of the report + include_passed: true # include passed tests in the results table diff --git a/.gitignore b/.gitignore index c5f16a4..7754426 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ # Created by https://www.toptal.com/developers/gitignore/api/java # Edit at https://www.toptal.com/developers/gitignore?templates=java +# VSCode +.vscode + ### Java ### # Compiled class file *.class @@ -29,4 +32,7 @@ replay_pid* # End of https://www.toptal.com/developers/gitignore/api/java *.wav -*.properties \ No newline at end of file +*.properties +!.vscode/launch.json +!gradle/wrapper/gradle-wrapper.jar +!gradle/wrapper/gradle-wrapper.properties \ No newline at end of file diff --git a/.gradle/7.4.2/checksums/checksums.lock b/.gradle/7.4.2/checksums/checksums.lock new file mode 100644 index 0000000..fe68481 Binary files /dev/null and b/.gradle/7.4.2/checksums/checksums.lock differ diff --git a/.gradle/7.4.2/checksums/md5-checksums.bin b/.gradle/7.4.2/checksums/md5-checksums.bin new file mode 100644 index 0000000..28c1435 Binary files /dev/null and b/.gradle/7.4.2/checksums/md5-checksums.bin differ diff --git a/.gradle/7.4.2/checksums/sha1-checksums.bin b/.gradle/7.4.2/checksums/sha1-checksums.bin new file mode 100644 index 0000000..4d4441d Binary files /dev/null and b/.gradle/7.4.2/checksums/sha1-checksums.bin differ diff --git a/.gradle/7.4.2/dependencies-accessors/dependencies-accessors.lock b/.gradle/7.4.2/dependencies-accessors/dependencies-accessors.lock new file mode 100644 index 0000000..9f8e386 Binary files /dev/null and b/.gradle/7.4.2/dependencies-accessors/dependencies-accessors.lock differ diff --git a/.gradle/7.4.2/fileChanges/last-build.bin b/.gradle/7.4.2/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/.gradle/7.4.2/fileChanges/last-build.bin differ diff --git a/.gradle/7.4.2/fileHashes/fileHashes.lock b/.gradle/7.4.2/fileHashes/fileHashes.lock new file mode 100644 index 0000000..b2fa140 Binary files /dev/null and b/.gradle/7.4.2/fileHashes/fileHashes.lock differ diff --git a/.gradle/8.0.2/checksums/checksums.lock b/.gradle/8.0.2/checksums/checksums.lock new file mode 100644 index 0000000..84f082e Binary files /dev/null and b/.gradle/8.0.2/checksums/checksums.lock differ diff --git a/.gradle/8.0.2/checksums/md5-checksums.bin b/.gradle/8.0.2/checksums/md5-checksums.bin new file mode 100644 index 0000000..d750d36 Binary files /dev/null and b/.gradle/8.0.2/checksums/md5-checksums.bin differ diff --git a/.gradle/8.0.2/checksums/sha1-checksums.bin b/.gradle/8.0.2/checksums/sha1-checksums.bin new file mode 100644 index 0000000..f3e9f14 Binary files /dev/null and b/.gradle/8.0.2/checksums/sha1-checksums.bin differ diff --git a/.gradle/8.0.2/dependencies-accessors/dependencies-accessors.lock b/.gradle/8.0.2/dependencies-accessors/dependencies-accessors.lock new file mode 100644 index 0000000..67251c5 Binary files /dev/null and b/.gradle/8.0.2/dependencies-accessors/dependencies-accessors.lock differ diff --git a/.gradle/8.0.2/executionHistory/executionHistory.bin b/.gradle/8.0.2/executionHistory/executionHistory.bin new file mode 100644 index 0000000..5daca43 Binary files /dev/null and b/.gradle/8.0.2/executionHistory/executionHistory.bin differ diff --git a/.gradle/8.0.2/executionHistory/executionHistory.lock b/.gradle/8.0.2/executionHistory/executionHistory.lock new file mode 100644 index 0000000..e9ddad0 Binary files /dev/null and b/.gradle/8.0.2/executionHistory/executionHistory.lock differ diff --git a/.gradle/8.0.2/fileChanges/last-build.bin b/.gradle/8.0.2/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/.gradle/8.0.2/fileChanges/last-build.bin differ diff --git a/.gradle/8.0.2/fileHashes/fileHashes.bin b/.gradle/8.0.2/fileHashes/fileHashes.bin new file mode 100644 index 0000000..9053215 Binary files /dev/null and b/.gradle/8.0.2/fileHashes/fileHashes.bin differ diff --git a/.gradle/8.0.2/fileHashes/fileHashes.lock b/.gradle/8.0.2/fileHashes/fileHashes.lock new file mode 100644 index 0000000..c779b18 Binary files /dev/null and b/.gradle/8.0.2/fileHashes/fileHashes.lock differ diff --git a/.gradle/8.0.2/fileHashes/resourceHashesCache.bin b/.gradle/8.0.2/fileHashes/resourceHashesCache.bin new file mode 100644 index 0000000..003a407 Binary files /dev/null and b/.gradle/8.0.2/fileHashes/resourceHashesCache.bin differ diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 0000000..a23d7b1 Binary files /dev/null and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin new file mode 100644 index 0000000..f00c87a Binary files /dev/null and b/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/.gradle/file-system.probe b/.gradle/file-system.probe new file mode 100644 index 0000000..101905a Binary files /dev/null and b/.gradle/file-system.probe differ diff --git a/.vscode/launch.json b/.vscode/launch.json index b5cde0a..c603acd 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -15,7 +15,7 @@ "name": "App", "request": "launch", "mainClass": "View.java", - "vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" + //"vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" }, { "type": "java", @@ -23,7 +23,7 @@ "request": "launch", "mainClass": "multithreading.AudioRecorder", "projectName": "cse110-lab5_d0dfa5ee", - "vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" + //"vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" }, { "type": "java", @@ -31,7 +31,7 @@ "request": "launch", "mainClass": "multithreading.ThreadingNoThread", "projectName": "cse110-lab5_d0dfa5ee", - "vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" + //"vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" }, { "type": "java", @@ -39,7 +39,7 @@ "request": "launch", "mainClass": "multithreading.ThreadingWithThread", "projectName": "cse110-lab5_d0dfa5ee", - "vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" + //"vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml" }, { "type": "java", diff --git a/.vscode/settings.json b/.vscode/settings.json index c995aa5..fc8081a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,7 @@ { - "java.debug.settings.onBuildFailureProceed": true + "java.compile.nullAnalysis.mode": "automatic", + "java.project.referencedLibraries": [ + "lib/**/*.jar" + ], + "java.configuration.updateBuildConfiguration": "interactive" } \ No newline at end of file diff --git a/README.md b/README.md index d21211b..550ca91 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# Lab5-Test -CSE110FA23 Lab 5 - Creating your own HTTP Server and Multithreading +# CSE 110 Project Team 39 Culinary Companion Crew +PantryPals - the application that provides you with recipes that YOU have currently in your possession! \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..3907115 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,43 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This generated file contains a sample Java application project to get you started. + * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle + * User Manual available at https://docs.gradle.org/8.0.2/userguide/building_java_projects.html + */ + +plugins { + // Apply the application plugin to add support for building a CLI application in Java. + id 'application' + id 'org.openjfx.javafxplugin' version '0.0.9' +} + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + // Use JUnit Jupiter for testing. + testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1' + + // This dependency is used by the application. + implementation 'com.google.guava:guava:31.1-jre' + + implementation 'org.json:json:20180813' +} + +application { + // Define the main class for the application. + mainClass = 'src.App' +} + +tasks.named('test') { + // Use JUnit Platform for unit tests. + useJUnitPlatform() +} + +javafx { + version = "21" + modules = [ 'javafx.controls' ] +} diff --git a/app/build/tmp/compileJava/compileTransaction/stash-dir/App.class.uniqueId3 b/app/build/tmp/compileJava/compileTransaction/stash-dir/App.class.uniqueId3 new file mode 100644 index 0000000..f673865 Binary files /dev/null and b/app/build/tmp/compileJava/compileTransaction/stash-dir/App.class.uniqueId3 differ diff --git a/app/build/tmp/compileJava/compileTransaction/stash-dir/AudioRecorder$1.class.uniqueId4 b/app/build/tmp/compileJava/compileTransaction/stash-dir/AudioRecorder$1.class.uniqueId4 new file mode 100644 index 0000000..1ebdd1e Binary files /dev/null and b/app/build/tmp/compileJava/compileTransaction/stash-dir/AudioRecorder$1.class.uniqueId4 differ diff --git a/app/build/tmp/compileJava/compileTransaction/stash-dir/AudioRecorder.class.uniqueId0 b/app/build/tmp/compileJava/compileTransaction/stash-dir/AudioRecorder.class.uniqueId0 new file mode 100644 index 0000000..fc272ba Binary files /dev/null and b/app/build/tmp/compileJava/compileTransaction/stash-dir/AudioRecorder.class.uniqueId0 differ diff --git a/app/build/tmp/compileJava/compileTransaction/stash-dir/Controller.class.uniqueId1 b/app/build/tmp/compileJava/compileTransaction/stash-dir/Controller.class.uniqueId1 new file mode 100644 index 0000000..8ccf111 Binary files /dev/null and b/app/build/tmp/compileJava/compileTransaction/stash-dir/Controller.class.uniqueId1 differ diff --git a/app/build/tmp/compileJava/compileTransaction/stash-dir/Model.class.uniqueId2 b/app/build/tmp/compileJava/compileTransaction/stash-dir/Model.class.uniqueId2 new file mode 100644 index 0000000..bafbbb9 Binary files /dev/null and b/app/build/tmp/compileJava/compileTransaction/stash-dir/Model.class.uniqueId2 differ diff --git a/app/build/tmp/compileJava/compileTransaction/stash-dir/View.class.uniqueId5 b/app/build/tmp/compileJava/compileTransaction/stash-dir/View.class.uniqueId5 new file mode 100644 index 0000000..2a4478d Binary files /dev/null and b/app/build/tmp/compileJava/compileTransaction/stash-dir/View.class.uniqueId5 differ diff --git a/app/build/tmp/compileJava/previous-compilation-data.bin b/app/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000..8c8e2ca Binary files /dev/null and b/app/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/app/build/tmp/compileTestJava/compileTransaction/stash-dir/VoiceRetrievalTest.class.uniqueId0 b/app/build/tmp/compileTestJava/compileTransaction/stash-dir/VoiceRetrievalTest.class.uniqueId0 new file mode 100644 index 0000000..5726b18 Binary files /dev/null and b/app/build/tmp/compileTestJava/compileTransaction/stash-dir/VoiceRetrievalTest.class.uniqueId0 differ diff --git a/app/build/tmp/compileTestJava/previous-compilation-data.bin b/app/build/tmp/compileTestJava/previous-compilation-data.bin new file mode 100644 index 0000000..ab9df8f Binary files /dev/null and b/app/build/tmp/compileTestJava/previous-compilation-data.bin differ diff --git a/src/ContactManagerReference.java b/app/src/ContactManagerReference.java similarity index 99% rename from src/ContactManagerReference.java rename to app/src/ContactManagerReference.java index f106b79..fb42269 100644 --- a/src/ContactManagerReference.java +++ b/app/src/ContactManagerReference.java @@ -1,4 +1,3 @@ - // layout import javafx.animation.PauseTransition; import javafx.application.Application; diff --git a/src/client/App.java b/app/src/main/java/code/App.java similarity index 67% rename from src/client/App.java rename to app/src/main/java/code/App.java index 51fd381..10ca984 100644 --- a/src/client/App.java +++ b/app/src/main/java/code/App.java @@ -1,8 +1,8 @@ -package client; +package code; -import client.Controllers.Controller; -import client.Model.Model; -import client.View.View; +import code.client.Controllers.Controller; +import code.client.Model.Model; +import code.client.View.View; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; @@ -15,14 +15,14 @@ public static void main(String[] args) { @Override public void start(Stage primaryStage) { - + View view = new View(); Model model = new Model(); Controller controller = new Controller(view, model); - Scene scene = new Scene(view.getGrid(), 400, 200); + Scene scene = new Scene(view.getGrid(), 1200, 600); primaryStage.setScene(scene); - primaryStage.setTitle("MyServerUI"); + primaryStage.setTitle("PantryPal"); primaryStage.show(); } diff --git a/src/multithreading/AudioRecorder.java b/app/src/main/java/code/client/Controllers/AudioRecorder.java similarity index 53% rename from src/multithreading/AudioRecorder.java rename to app/src/main/java/code/client/Controllers/AudioRecorder.java index 6098b1f..c59b65c 100644 --- a/src/multithreading/AudioRecorder.java +++ b/app/src/main/java/code/client/Controllers/AudioRecorder.java @@ -1,64 +1,18 @@ -package multithreading; +package code.client.Controllers; -import javafx.application.Application; -import javafx.stage.Stage; -import javafx.scene.Scene; -import javafx.scene.control.Button; import javafx.scene.control.Label; -import javafx.scene.layout.FlowPane; -import javafx.geometry.Insets; import java.io.*; import javax.sound.sampled.*; -class AppFrame extends FlowPane { - private Button startButton; - private Button stopButton; +public class AudioRecorder { private AudioFormat audioFormat; private TargetDataLine targetDataLine; private Label recordingLabel; + private boolean recordingState; - // Set a default style for buttons and fields - background color, font size, - // italics - String defaultButtonStyle = "-fx-border-color: #000000; -fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px;"; - String defaultLabelStyle = "-fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px; -fx-text-fill: red; visibility: hidden"; - - AppFrame() { - // Set properties for the flowpane - this.setPrefSize(370, 120); - this.setPadding(new Insets(5, 0, 5, 5)); - this.setVgap(10); - this.setHgap(10); - this.setPrefWrapLength(170); - - // Add the buttons and text fields - startButton = new Button("Start"); - startButton.setStyle(defaultButtonStyle); - - stopButton = new Button("Stop"); - stopButton.setStyle(defaultButtonStyle); - - recordingLabel = new Label("Recording..."); - recordingLabel.setStyle(defaultLabelStyle); - - this.getChildren().addAll(startButton, stopButton, recordingLabel); - - // Get the audio format - audioFormat = getAudioFormat(); - - // Add the listeners to the buttons - addListeners(); - } - - public void addListeners() { - // Start Button - startButton.setOnAction(e -> { - startRecording(); - }); - - // Stop Button - stopButton.setOnAction(e -> { - stopRecording(); - }); + public AudioRecorder(Label recordingLabel) { + this.audioFormat = getAudioFormat(); + this.recordingLabel = recordingLabel; } private AudioFormat getAudioFormat() { @@ -86,7 +40,7 @@ private AudioFormat getAudioFormat() { bigEndian); } - private void startRecording() { + public void startRecording() { Thread t = new Thread( new Runnable() { @Override @@ -121,31 +75,19 @@ public void run() { t.start(); } - private void stopRecording() { + public void stopRecording() { targetDataLine.stop(); targetDataLine.close(); } -} - -public class AudioRecorder extends Application { - - @Override - public void start(Stage primaryStage) throws Exception { - // Setting the Layout of the Window (Flow Pane) - AppFrame root = new AppFrame(); - - // Set the title of the app - primaryStage.setTitle("Audio Recorder"); - // Create scene of mentioned size with the border pane - primaryStage.setScene(new Scene(root, 370, 120)); - // Make window non-resizable - primaryStage.setResizable(false); - // Show the app - primaryStage.show(); - } - - public static void main(String[] args) { - launch(args); + public boolean toggleRecording() { + if(recordingState) { + stopRecording(); + recordingState = false; + return false; + } + startRecording(); + recordingState = true; + return true; } } diff --git a/app/src/main/java/code/client/Controllers/Controller.java b/app/src/main/java/code/client/Controllers/Controller.java new file mode 100644 index 0000000..3a2c49e --- /dev/null +++ b/app/src/main/java/code/client/Controllers/Controller.java @@ -0,0 +1,61 @@ +package code.client.Controllers; + +import code.client.Controllers.AudioRecorder; +import code.client.Model.Model; +import code.client.View.View; +import javafx.event.ActionEvent; + +/* + * Modify t + */ +public class Controller { + private View view; + private Model model; + private AudioRecorder audioRecorder; + + public Controller(View view, Model model) { + this.view = view; + this.model = model; + this.audioRecorder = new AudioRecorder(view.getRecordingLabel()); + + // recording buttons + this.view.setStartButtonAction(this::handleStartButton); + this.view.setStopButtonAction(this::handleStopButton); + } + + private void handleStartButton(ActionEvent event) { + audioRecorder.startRecording(); + } + + private void handleStopButton(ActionEvent event) { + // Makes calls to View + audioRecorder.stopRecording(); + } + /* + * private void handlePostButton(ActionEvent event) { + * String language = view.getLanguage(); + * String year = view.getYear(); + * String response = model.performRequest("POST", language, year, null); + * view.showAlert("Response", response); + * } + * + * private void handleGetButton(ActionEvent event) { + * String query = view.getQuery(); + * String response = model.performRequest("GET", null, null, query); + * view.showAlert("Response", response); + * } + * + * private void handlePutButton(ActionEvent event) { + * String language = view.getLanguage(); + * String year = view.getYear(); + * String response = model.performRequest("PUT", language, year, null); + * view.showAlert("Response", response); + * } + * + * private void handleDeleteButton(ActionEvent event) { + * String query = view.getQuery(); + * String response = model.performRequest("DELETE", null, null, query); + * view.showAlert("Response", response); + * } + */ +} \ No newline at end of file diff --git a/app/src/main/java/code/client/Model/Model.java b/app/src/main/java/code/client/Model/Model.java new file mode 100644 index 0000000..cd8e47a --- /dev/null +++ b/app/src/main/java/code/client/Model/Model.java @@ -0,0 +1,52 @@ +package code.client.Model; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URI; + + +public class Model { + private static final String API_ENDPOINT = "https://api.openai.com/v1/audio/transcriptions"; + private static final String TOKEN = "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"; + private static final String MODEL = "whisper-1"; + + public String performWhisperRequest() { + // Implement your HTTP request logic here and return the response + try { + + WhisperHandler whisper = new WhisperHandler(API_ENDPOINT, TOKEN, MODEL); + String response = whisper.processAudio(); + return response; + + /* + * String urlString = "http://localhost:8100/"; + * if (query != null) { + * urlString += "?=" + query; + * } + * URL url = new URI(urlString).toURL(); + * HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + * conn.setRequestMethod(method); + * conn.setDoOutput(true); + * + * if (method.equals("POST") || method.equals("PUT")) { + * OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); + * out.write(language + "," + year); + * out.flush(); + * out.close(); + * } + * + * BufferedReader in = new BufferedReader(new + * InputStreamReader(conn.getInputStream())); + * String response = in.readLine(); + * in.close(); + * return response; + */ + } catch (Exception ex) { + ex.printStackTrace(); + return "Error: " + ex.getMessage(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/client/Model/Recipe.java b/app/src/main/java/code/client/Model/Recipe.java new file mode 100644 index 0000000..9ba46e1 --- /dev/null +++ b/app/src/main/java/code/client/Model/Recipe.java @@ -0,0 +1,41 @@ +package code.client.Model; + +import javafx.scene.control.TextField; +import javafx.scene.text.Font; +import javafx.scene.text.FontPosture; +import javafx.scene.text.FontWeight; + +public class Recipe { + private TextField name; + + private TextField recipeDetails; + + Recipe() { + Font biggerFont = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 22); + Font smallerFont = Font.font("georgia", FontWeight.SEMI_BOLD, FontPosture.REGULAR, 18); + + name = new TextField(); + name.setPromptText("Recipe Name"); + name.setFont(biggerFont); + + recipeDetails = new TextField(); + recipeDetails.setFont(smallerFont); + + } + + public String getRecipeName() { + return this.name.getText(); + } + + public String getRecipeDetails() { + return this.recipeDetails.getText(); + } + + public void setRecipeName(String name) { + this.name.setText(name); + } + + public void setRecipeDetails(String details) { + this.recipeDetails.setText(details); + } +} diff --git a/app/src/main/java/code/client/Model/WhisperHandler.java b/app/src/main/java/code/client/Model/WhisperHandler.java new file mode 100644 index 0000000..bbdbcb6 --- /dev/null +++ b/app/src/main/java/code/client/Model/WhisperHandler.java @@ -0,0 +1,152 @@ +package code.client.Model; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import org.json.JSONObject; +import org.json.JSONException; + +public class WhisperHandler { + private String API_ENDPOINT; + private String TOKEN; + private String MODEL; + + public WhisperHandler(String API_ENDPOINT, String TOKEN, String MODEL) { + this.API_ENDPOINT = API_ENDPOINT; + this.TOKEN = TOKEN; + this.MODEL = MODEL; + } + + // https://stackoverflow.com/questions/25334139/how-to-mock-a-url-connection + public String processAudio() throws IOException, URISyntaxException { + // Create file object from file path + File file = new File("recording.wav"); + HttpURLConnection connection = sendHttpRequest(file); + + // Get response code + int responseCode = connection.getResponseCode(); + String response; + + // Check response code and handle response accordingly + if (responseCode == HttpURLConnection.HTTP_OK) { + response = handleSuccessResponse(connection); + } else { + response = handleErrorResponse(connection); + } + + // Disconnect connection + connection.disconnect(); + + return response; + } + + private HttpURLConnection sendHttpRequest(File file) throws IOException, URISyntaxException { + URL url = new URI(API_ENDPOINT).toURL(); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + + // Set up request headers + String boundary = "Boundary-" + System.currentTimeMillis(); + connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); + connection.setRequestProperty("Authorization", "Bearer " + TOKEN); + + // Set up output stream to write request body + OutputStream outputStream = connection.getOutputStream(); + + // Write model parameter to request body + writeParameterToOutputStream(outputStream, "model", MODEL, boundary); + + // Write file parameter to request body + writeFileToOutputStream(outputStream, file, boundary); + + // Write closing boundary to request body + outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes()); + + // Flush and close output stream + outputStream.flush(); + outputStream.close(); + + return connection; + } + + // Helper method to write a parameter to the output stream in multipart form + // data format + private static void writeParameterToOutputStream( + OutputStream outputStream, + String parameterName, + String parameterValue, + String boundary) throws IOException { + outputStream.write(("--" + boundary + "\r\n").getBytes()); + outputStream.write( + ("Content-Disposition: form-data; name=\"" + parameterName + "\"\r\n\r\n").getBytes()); + outputStream.write((parameterValue + "\r\n").getBytes()); + } + + // Helper method to write a file to the output stream in multipart form data + // format + private static void writeFileToOutputStream( + OutputStream outputStream, + File file, + String boundary) throws IOException { + outputStream.write(("--" + boundary + "\r\n").getBytes()); + outputStream.write( + ("Content-Disposition: form-data; name=\"file\"; filename=\"" + + file.getName() + + "\"\r\n").getBytes()); + outputStream.write(("Content-Type: audio/mpeg\r\n\r\n").getBytes()); + + FileInputStream fileInputStream = new FileInputStream(file); + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = fileInputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + fileInputStream.close(); + } + + // Helper method to handle a successful response + private static String handleSuccessResponse(HttpURLConnection connection) + throws IOException, JSONException { + BufferedReader in = new BufferedReader( + new InputStreamReader(connection.getInputStream())); + String inputLine; + StringBuilder response = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + + JSONObject responseJson = new JSONObject(response.toString()); + + String generatedText = responseJson.getString("text"); + System.out.println("Transcription Result: " + generatedText); + return generatedText; + + } + + // Helper method to handle an error response + private static String handleErrorResponse(HttpURLConnection connection) + throws IOException, JSONException { + BufferedReader errorReader = new BufferedReader( + new InputStreamReader(connection.getErrorStream())); + String errorLine; + StringBuilder errorResponse = new StringBuilder(); + while ((errorLine = errorReader.readLine()) != null) { + errorResponse.append(errorLine); + } + errorReader.close(); + String errorResult = errorResponse.toString(); + System.out.println("Error Result: " + errorResult); + return errorResult; + } + +} + diff --git a/src/client/View/Main.java b/app/src/main/java/code/client/View/Main.java similarity index 99% rename from src/client/View/Main.java rename to app/src/main/java/code/client/View/Main.java index f582eab..13c931f 100644 --- a/src/client/View/Main.java +++ b/app/src/main/java/code/client/View/Main.java @@ -1,5 +1,5 @@ -package client.View; +package code.client.View; import javafx.scene.layout.StackPane; diff --git a/src/client/View/NewRecipe.java b/app/src/main/java/code/client/View/NewRecipeUI.java similarity index 97% rename from src/client/View/NewRecipe.java rename to app/src/main/java/code/client/View/NewRecipeUI.java index 0e14ddb..0066027 100644 --- a/src/client/View/NewRecipe.java +++ b/app/src/main/java/code/client/View/NewRecipeUI.java @@ -1,4 +1,4 @@ -package client.View; +package code.client.View; import javafx.geometry.Pos; import javafx.application.Application; @@ -10,7 +10,7 @@ import javafx.scene.layout.*; import javafx.scene.text.*; -public class NewRecipe extends Application { +public class NewRecipeUI extends Application { @Override public void start(Stage primaryStage) { diff --git a/app/src/main/java/code/client/View/View.java b/app/src/main/java/code/client/View/View.java new file mode 100644 index 0000000..2d479f9 --- /dev/null +++ b/app/src/main/java/code/client/View/View.java @@ -0,0 +1,78 @@ +package code.client.View; + +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.geometry.Insets; +import javafx.scene.control.*; +import javafx.scene.layout.GridPane; +import javax.swing.Action; + +/* + * Stores all the buttons and GUI + */ +public class View { + private Button startRecButton, stopRecButton; + private Label recordingLabel, transcriptLabel; + private GridPane grid; + + public View() { + grid = new GridPane(); + grid.setPadding(new Insets(20, 20, 20, 20)); + grid.setHgap(10); + grid.setVgap(10); + + String defaultButtonStyle = "-fx-border-color: #000000; -fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px;"; + String defaultLabelStyle = "-fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px; -fx-text-fill: red; visibility: hidden"; + /* + * Audio recording + */ + startRecButton = new Button("Start"); + startRecButton.setStyle(defaultButtonStyle); + + stopRecButton = new Button("Stop"); + stopRecButton.setStyle(defaultButtonStyle); + + recordingLabel = new Label("Recording..."); + recordingLabel.setStyle(defaultLabelStyle); + + grid.add(startRecButton, 0, 3); // start recording + grid.add(stopRecButton, 1, 3); // stop + grid.add(recordingLabel, 0, 4); + + transcriptLabel = new Label(""); + grid.add(transcriptLabel, 0, 5); + + } + + public GridPane getGrid() { + return grid; + } + + public Label getRecordingLabel() { + return recordingLabel; + } + + public Label getTranscriptLabel() { + return transcriptLabel; + } + + public void setTranscriptLabel(String transcript) { + transcriptLabel.setText(transcript); + } + + public void setStartButtonAction(EventHandler eventHandler) { + startRecButton.setOnAction(eventHandler); + } + + public void setStopButtonAction(EventHandler eventHandler) { + stopRecButton.setOnAction(eventHandler); + } + + public void showAlert(String title, String content) { + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle(title); + alert.setHeaderText(null); + alert.setContentText(content); + alert.showAndWait(); + } +} \ No newline at end of file diff --git a/src/client/View/microphone.png b/app/src/main/java/code/client/View/microphone.png similarity index 100% rename from src/client/View/microphone.png rename to app/src/main/java/code/client/View/microphone.png diff --git a/src/server/MyHandler.java b/app/src/main/java/code/server/MyHandler.java similarity index 98% rename from src/server/MyHandler.java rename to app/src/main/java/code/server/MyHandler.java index dea62d5..7c0cfb8 100644 --- a/src/server/MyHandler.java +++ b/app/src/main/java/code/server/MyHandler.java @@ -1,4 +1,4 @@ -package server; +package code.server; import com.sun.net.httpserver.*; import java.io.*; diff --git a/src/server/MyServer.java b/app/src/main/java/code/server/MyServer.java similarity index 98% rename from src/server/MyServer.java rename to app/src/main/java/code/server/MyServer.java index a0d8c7b..f071b26 100644 --- a/src/server/MyServer.java +++ b/app/src/main/java/code/server/MyServer.java @@ -1,4 +1,4 @@ -package server; +package code.server; import com.sun.net.httpserver.*; import java.io.IOException; diff --git a/src/server/RequestHandler.java b/app/src/main/java/code/server/RequestHandler.java similarity index 99% rename from src/server/RequestHandler.java rename to app/src/main/java/code/server/RequestHandler.java index 5638d31..3fc2aa1 100644 --- a/src/server/RequestHandler.java +++ b/app/src/main/java/code/server/RequestHandler.java @@ -1,4 +1,4 @@ -package server; +package code.server; import com.sun.net.httpserver.*; import java.io.*; diff --git a/app/src/main/java/code/server/WhisperReference.java b/app/src/main/java/code/server/WhisperReference.java new file mode 100644 index 0000000..701d6a9 --- /dev/null +++ b/app/src/main/java/code/server/WhisperReference.java @@ -0,0 +1,141 @@ +package code.server; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import org.json.JSONObject; +import org.json.JSONException; + +public class WhisperReference { + private static final String API_ENDPOINT = "https://api.openai.com/v1/audio/transcriptions"; + private static final String TOKEN = "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"; + private static final String MODEL = "whisper-1"; + // private static final String FILE_PATH = + // "C:\\Users\\saman\\OneDrive\\Documents\\GitHub\\cse110-lab4\\src\\cse110.mp3"; + + public static void main(String[] args) throws IOException, URISyntaxException { + // Create file object from file path + String FILE_PATH = args[0]; + File file = new File(FILE_PATH); + + // Set up HTTP connection + URL url = new URI(API_ENDPOINT).toURL(); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + + // Set up request headers + String boundary = "Boundary-" + System.currentTimeMillis(); + connection.setRequestProperty( + "Content-Type", + "multipart/form-data; boundary=" + boundary); + connection.setRequestProperty("Authorization", "Bearer " + TOKEN); + + // Set up output stream to write request body + OutputStream outputStream = connection.getOutputStream(); + + // Write model parameter to request body + writeParameterToOutputStream(outputStream, "model", MODEL, boundary); + + // Write file parameter to request body + writeFileToOutputStream(outputStream, file, boundary); + + // Write closing boundary to request body + outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes()); + + // Flush and close output stream + outputStream.flush(); + outputStream.close(); + + // Get response code + int responseCode = connection.getResponseCode(); + + // Check response code and handle response accordingly + if (responseCode == HttpURLConnection.HTTP_OK) { + handleSuccessResponse(connection); + } else { + handleErrorResponse(connection); + } + + // Disconnect connection + connection.disconnect(); + } + + // Helper method to write a parameter to the output stream in multipart form + // data format + private static void writeParameterToOutputStream( + OutputStream outputStream, + String parameterName, + String parameterValue, + String boundary) throws IOException { + outputStream.write(("--" + boundary + "\r\n").getBytes()); + outputStream.write( + ("Content-Disposition: form-data; name=\"" + parameterName + "\"\r\n\r\n").getBytes()); + outputStream.write((parameterValue + "\r\n").getBytes()); + } + + // Helper method to write a file to the output stream in multipart form data + // format + private static void writeFileToOutputStream( + OutputStream outputStream, + File file, + String boundary) throws IOException { + outputStream.write(("--" + boundary + "\r\n").getBytes()); + outputStream.write( + ("Content-Disposition: form-data; name=\"file\"; filename=\"" + + file.getName() + + "\"\r\n").getBytes()); + outputStream.write(("Content-Type: audio/mpeg\r\n\r\n").getBytes()); + + FileInputStream fileInputStream = new FileInputStream(file); + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = fileInputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + fileInputStream.close(); + } + + // Helper method to handle a successful response + private static void handleSuccessResponse(HttpURLConnection connection) + throws IOException, JSONException { + BufferedReader in = new BufferedReader( + new InputStreamReader(connection.getInputStream())); + String inputLine; + StringBuilder response = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + + JSONObject responseJson = new JSONObject(response.toString()); + + String generatedText = responseJson.getString("text"); + + // Print the transcription result + System.out.println("Transcription Result: " + generatedText); + } + + // Helper method to handle an error response + private static void handleErrorResponse(HttpURLConnection connection) + throws IOException, JSONException { + BufferedReader errorReader = new BufferedReader( + new InputStreamReader(connection.getErrorStream())); + String errorLine; + StringBuilder errorResponse = new StringBuilder(); + while ((errorLine = errorReader.readLine()) != null) { + errorResponse.append(errorLine); + } + errorReader.close(); + String errorResult = errorResponse.toString(); + System.out.println("Error Result: " + errorResult); + } + +} diff --git a/app/src/test/java/code/VoiceRetrievalTest.java b/app/src/test/java/code/VoiceRetrievalTest.java new file mode 100644 index 0000000..96daa4f --- /dev/null +++ b/app/src/test/java/code/VoiceRetrievalTest.java @@ -0,0 +1,52 @@ +package code; + +import javafx.scene.control.Label; + +import java.io.*; +import org.junit.jupiter.api.Test; + +import code.client.Controllers.AudioRecorder; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import javafx.application.Platform; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +public class VoiceRetrievalTest { + private AudioRecorder audioRecorder; + private Label recordingLabel; + + @BeforeAll + static void initJfxRuntime() { + Platform.startup(() -> {}); + } + + @BeforeEach + void setUp() { + recordingLabel = new Label("Recording"); + audioRecorder = new AudioRecorder(recordingLabel); + } + + + void testAudioSave() throws InterruptedException { + audioRecorder.startRecording(); + Thread.sleep(1000); + audioRecorder.stopRecording(); + File file = new File("recording.wav"); + assertTrue(file.exists()); + } + + + void testLabelChanges() throws InterruptedException { + audioRecorder.startRecording(); + assertTrue(recordingLabel.isVisible()); + Thread.sleep(1000); + + audioRecorder.stopRecording(); + assertFalse(recordingLabel.isVisible()); + } + +} diff --git a/bin/client/App.class b/bin/client/App.class deleted file mode 100644 index 7cbb1e1..0000000 Binary files a/bin/client/App.class and /dev/null differ diff --git a/bin/client/Controller.class b/bin/client/Controller.class deleted file mode 100644 index b99ecf0..0000000 Binary files a/bin/client/Controller.class and /dev/null differ diff --git a/bin/client/Model.class b/bin/client/Model.class deleted file mode 100644 index 9f00061..0000000 Binary files a/bin/client/Model.class and /dev/null differ diff --git a/bin/client/View.class b/bin/client/View.class deleted file mode 100644 index 44e61e1..0000000 Binary files a/bin/client/View.class and /dev/null differ diff --git a/bin/server/MyHandler.class b/bin/server/MyHandler.class deleted file mode 100644 index 38de6d9..0000000 Binary files a/bin/server/MyHandler.class and /dev/null differ diff --git a/bin/server/MyServer.class b/bin/server/MyServer.class deleted file mode 100644 index 83268d6..0000000 Binary files a/bin/server/MyServer.class and /dev/null differ diff --git a/bin/server/RequestHandler.class b/bin/server/RequestHandler.class deleted file mode 100644 index 1d88768..0000000 Binary files a/bin/server/RequestHandler.class and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..ccebba7 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bdc9a83 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..79a61d4 --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..6221db2 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,11 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/8.0.2/userguide/multi_project_builds.html + */ + +rootProject.name = 'cse110-project-team-39' +include('app') diff --git a/src/client/Controllers/Controller.java b/src/client/Controllers/Controller.java deleted file mode 100644 index 810ab51..0000000 --- a/src/client/Controllers/Controller.java +++ /dev/null @@ -1,49 +0,0 @@ -package client.Controllers; - -import client.Model.Model; -import client.View.View; -import javafx.event.ActionEvent; - -/* - * - */ -public class Controller { - private View view; - private Model model; - - public Controller(View view, Model model) { - this.view = view; - this.model = model; - - this.view.setPostButtonAction(this::handlePostButton); - this.view.setGetButtonAction(this::handleGetButton); - this.view.setPutButtonAction(this::handlePutButton); - this.view.setDeleteButtonAction(this::handleDeleteButton); - } - - private void handlePostButton(ActionEvent event) { - String language = view.getLanguage(); - String year = view.getYear(); - String response = model.performRequest("POST", language, year, null); - view.showAlert("Response", response); - } - - private void handleGetButton(ActionEvent event) { - String query = view.getQuery(); - String response = model.performRequest("GET", null, null, query); - view.showAlert("Response", response); - } - - private void handlePutButton(ActionEvent event) { - String language = view.getLanguage(); - String year = view.getYear(); - String response = model.performRequest("PUT", language, year, null); - view.showAlert("Response", response); - } - - private void handleDeleteButton(ActionEvent event) { - String query = view.getQuery(); - String response = model.performRequest("DELETE", null, null, query); - view.showAlert("Response", response); - } -} \ No newline at end of file diff --git a/src/client/Model/Model.java b/src/client/Model/Model.java deleted file mode 100644 index 9deb931..0000000 --- a/src/client/Model/Model.java +++ /dev/null @@ -1,41 +0,0 @@ -package client.Model; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URI; - - -public class Model { - public String performRequest(String method, String language, String year, String query) { - // Implement your HTTP request logic here and return the response - - try { - String urlString = "http://localhost:8100/"; - if (query != null) { - urlString += "?=" + query; - } - URL url = new URI(urlString).toURL(); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod(method); - conn.setDoOutput(true); - - if (method.equals("POST") || method.equals("PUT")) { - OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); - out.write(language + "," + year); - out.flush(); - out.close(); - } - - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String response = in.readLine(); - in.close(); - return response; - } catch (Exception ex) { - ex.printStackTrace(); - return "Error: " + ex.getMessage(); - } - } -} \ No newline at end of file diff --git a/src/client/View/View.java b/src/client/View/View.java deleted file mode 100644 index 99382dd..0000000 --- a/src/client/View/View.java +++ /dev/null @@ -1,89 +0,0 @@ -package client.View; - -import javafx.event.ActionEvent; -import javafx.event.EventHandler; -import javafx.geometry.Insets; -import javafx.scene.control.*; -import javafx.scene.layout.GridPane; - -/* - * Stores all the buttons and GUI - */ -public class View { - private TextField languageField, yearField, queryField; - private Button postButton, getButton, putButton, deleteButton; - private GridPane grid; - - public View() { - grid = new GridPane(); - grid.setPadding(new Insets(20, 20, 20, 20)); - grid.setHgap(10); - grid.setVgap(10); - - Label languageLabel = new Label("Language:"); - languageField = new TextField(); - grid.add(languageLabel, 0, 0); - grid.add(languageField, 1, 0); - - Label yearLabel = new Label("Year:"); - yearField = new TextField(); - grid.add(yearLabel, 0, 1); - grid.add(yearField, 1, 1); - - Label queryLabel = new Label("Query:"); - queryField = new TextField(); - grid.add(queryLabel, 0, 2); - grid.add(queryField, 1, 2); - - postButton = new Button("Post"); - getButton = new Button("Get"); - putButton = new Button("Put"); - deleteButton = new Button("Delete"); - - grid.add(postButton, 0, 3); - grid.add(getButton, 1, 3); - grid.add(putButton, 0, 4); - grid.add(deleteButton, 1, 4); - - } - - public String getLanguage() { - return languageField.getText(); - } - - public String getYear() { - return yearField.getText(); - } - - public String getQuery() { - return queryField.getText(); - } - - public GridPane getGrid() { - return grid; - } - - public void setPostButtonAction(EventHandler eventHandler) { - postButton.setOnAction(eventHandler); - } - - public void setGetButtonAction(EventHandler eventHandler) { - getButton.setOnAction(eventHandler); - } - - public void setPutButtonAction(EventHandler eventHandler) { - putButton.setOnAction(eventHandler); - } - - public void setDeleteButtonAction(EventHandler eventHandler) { - deleteButton.setOnAction(eventHandler); - } - - public void showAlert(String title, String content) { - Alert alert = new Alert(Alert.AlertType.INFORMATION); - alert.setTitle(title); - alert.setHeaderText(null); - alert.setContentText(content); - alert.showAndWait(); - } -} \ No newline at end of file diff --git a/src/multithreading/ThreadingNoThread.java b/src/multithreading/ThreadingNoThread.java deleted file mode 100644 index dc1c15d..0000000 --- a/src/multithreading/ThreadingNoThread.java +++ /dev/null @@ -1,101 +0,0 @@ -package multithreading; - -import javafx.application.Application; -import javafx.stage.Stage; -import javafx.scene.Scene; -import javafx.scene.control.Button; -import javafx.scene.control.TextField; -import javafx.scene.paint.Color; -import javafx.scene.layout.Background; -import javafx.scene.layout.BackgroundFill; -import javafx.scene.layout.CornerRadii; -import javafx.scene.layout.FlowPane; -import javafx.geometry.Insets; - -class AppFrameNoThread extends FlowPane { - private Button colorButton; - private Button calcButton; - private TextField colorField; - private TextField calcField; - - // Set a default style for buttons and fields - background color, font size, - // italics - String defaultButtonStyle = "-fx-border-color: #000000; -fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px;"; - String defaultFieldStyle = "-fx-border-color: #000000; -fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px; -fx-alignment: CENTER;"; - - AppFrameNoThread() { - // Set properties for the flowpane - this.setPrefSize(370, 120); - this.setPadding(new Insets(5, 0, 5, 5)); - this.setVgap(10); - this.setHgap(10); - this.setPrefWrapLength(170); - - // Add the buttons and text fields - colorButton = new Button("Color"); - colorButton.setStyle(defaultButtonStyle); - - colorField = new TextField(); - colorField.setStyle(defaultFieldStyle); - - calcButton = new Button("Calculate"); - calcButton.setStyle(defaultButtonStyle); - - calcField = new TextField(); - calcField.setStyle(defaultFieldStyle); - - this.getChildren().addAll(colorButton, colorField, calcButton, calcField); - - // Add the listeners to the buttons - addListeners(); - } - - public void addListeners() { - // Color Button - colorButton.setOnAction(e -> { - if (colorField.getBackground().getFills().get(0).getFill() == Color.GREEN) { - colorField.setBackground(new Background(new BackgroundFill(Color.ORANGE, CornerRadii.EMPTY, Insets.EMPTY))); - } else { - colorField.setBackground(new Background(new BackgroundFill(Color.GREEN, CornerRadii.EMPTY, Insets.EMPTY))); - } - }); - - // Calculate Button - calcButton.setOnAction(e -> { - calculate(); - }); - } - - private void calculate() { - try { - calcField.setText("Please Wait..."); - Thread.sleep(5 * 1000); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - calcField.setText("Computation complete!"); - } -} - -public class ThreadingNoThread extends Application { - - @Override - public void start(Stage primaryStage) throws Exception { - - // Setting the Layout of the Window (Flow Pane) - AppFrameNoThread root = new AppFrameNoThread(); - - // Set the title of the app - primaryStage.setTitle("Threading No Thread"); - // Create scene of mentioned size with the border pane - primaryStage.setScene(new Scene(root, 370, 120)); - // Make window non-resizable - primaryStage.setResizable(false); - // Show the app - primaryStage.show(); - } - - public static void main(String[] args) { - launch(args); - } -} diff --git a/src/multithreading/ThreadingWithThread.java b/src/multithreading/ThreadingWithThread.java deleted file mode 100644 index e296cba..0000000 --- a/src/multithreading/ThreadingWithThread.java +++ /dev/null @@ -1,108 +0,0 @@ -package multithreading; - -import javafx.application.Application; -import javafx.stage.Stage; -import javafx.scene.Scene; -import javafx.scene.control.Button; -import javafx.scene.control.TextField; -import javafx.scene.paint.Color; -import javafx.scene.layout.Background; -import javafx.scene.layout.BackgroundFill; -import javafx.scene.layout.CornerRadii; -import javafx.scene.layout.FlowPane; -import javafx.geometry.Insets; - -class AppFrameThread extends FlowPane { - private Button colorButton; - private Button calcButton; - private TextField colorField; - private TextField calcField; - Thread t; - - // Set a default style for buttons and fields - background color, font size, - // italics - String defaultButtonStyle = "-fx-border-color: #000000; -fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px;"; - String defaultFieldStyle = "-fx-border-color: #000000; -fx-font: 13 arial; -fx-pref-width: 175px; -fx-pref-height: 50px; -fx-alignment: CENTER;"; - - AppFrameThread() { - // Set properties for the flowpane - this.setPrefSize(370, 120); - this.setPadding(new Insets(5, 0, 5, 5)); - this.setVgap(10); - this.setHgap(10); - this.setPrefWrapLength(170); - - // Add the buttons and text fields - colorButton = new Button("Color"); - colorButton.setStyle(defaultButtonStyle); - - colorField = new TextField(); - colorField.setStyle(defaultFieldStyle); - - calcButton = new Button("Calculate"); - calcButton.setStyle(defaultButtonStyle); - - calcField = new TextField(); - calcField.setStyle(defaultFieldStyle); - - this.getChildren().addAll(colorButton, colorField, calcButton, calcField); - - // Add the listeners to the buttons - addListeners(); - } - - public void addListeners() { - // Color Button - colorButton.setOnAction(e -> { - if (colorField.getBackground().getFills().get(0).getFill() == Color.GREEN) { - colorField.setBackground(new Background(new BackgroundFill(Color.ORANGE, CornerRadii.EMPTY, Insets.EMPTY))); - } else { - colorField.setBackground(new Background(new BackgroundFill(Color.GREEN, CornerRadii.EMPTY, Insets.EMPTY))); - } - }); - - // Calculate Button - calcButton.setOnAction(e -> { - calculate(); - }); - } - - private void calculate() { - Thread t = new Thread( - new Runnable() { - @Override - public void run() { - try { - calcField.setText("Please Wait..."); - Thread.sleep(5 * 1000); - } catch (InterruptedException e1) { - } - calcField.setText("Computation complete!"); - } - }); - t.start(); - } -} - -public class ThreadingWithThread extends Application { - - @Override - public void start(Stage primaryStage) throws Exception { - - // Setting the Layout of the Window (Flow Pane) - AppFrameThread root = new AppFrameThread(); - - // Set the title of the app - primaryStage.setTitle("Threading With Thread"); - // Create scene of mentioned size with the border pane - primaryStage.setScene(new Scene(root, 370, 120)); - // Make window non-resizable - primaryStage.setResizable(false); - // Show the app - primaryStage.show(); - } - - public static void main(String[] args) { - launch(args); - } -}