diff --git a/.gitignore b/.gitignore index 2414ce5..c16f915 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -*.class -*~ -*.swp +.gradle +build/ +.idea diff --git a/Charts.pdf b/Charts.pdf deleted file mode 100644 index 1614fdf..0000000 Binary files a/Charts.pdf and /dev/null differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..6f5fb1b --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# Simple-Java-Client-Server + +This is forked from [c-lark/Simple-Java-Client-Server](https://github.com/c-lark/Simple-Java-Client-Server). + + +## Compiling + +``` +``` + + +## Running Server + +``` +``` + + + diff --git a/README.txt b/README.txt deleted file mode 100644 index 93fe03f..0000000 --- a/README.txt +++ /dev/null @@ -1,35 +0,0 @@ -AUTHORS: Ikonija Bogojevic, Miguel Perez, Sandra Weber - -DESCRIPTION - -This is a simple client and server written in Java using the socket API. Both the client and server are multithreaded. The client can use multiple threads to simulate multiple simultanous connections to the server, which will create a new thread for every incoming connection. - - - -Client --------- - -COMPILATION -$ javac Client.java - -USAGE -$ java Client hostname - -where hostname is the name of the machine the server is running on. If it is the same machine as the client, use localhost. - -The client program offers the user a choice of UNIX commands to run on the server. After the user chooses a command, the client creates a thread which connects to the server and sends it the user's choice. The client will print the answer that it receives from the server (unless the client is in benchmark mode). - -The client program can also open multiple simultaneous connections to the server. To do this, choose option 7, Benchmark, from the main menu. It will then prompt for which command to benchmark and how many connections to open. It will calculate and display an average response time for all connections. - - - -Server --------- - -COMPILATION -$ javac Server.java - -USAGE -$ java Server - -This will make the server listen on port 15432 for incoming connections from client(s). The server listens for incoming connections in its main loop, and creates a new thread to handle every incoming connection. These threads run UNIX commands on the server machine and send their output to the client(s). diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..c808fd9 --- /dev/null +++ b/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'java' +} + +group 'com.example.hyokeun.asr' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() + jcenter() +} + +jar { + manifest { + attributes 'Main-Class': 'com.example.hyokeun.asr.SpeechToTextService' + } +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.12' + + compile 'org.apache.commons:commons-lang3:3.6' + compile 'com.google.guava:guava:23.0' + compile 'org.projectlombok:lombok:1.16.18' + compile 'com.fasterxml.jackson.core:jackson-databind:2.9.6' + compile 'com.google.code.gson:gson:2.8.1' + compile 'org.webjars:stomp-websocket:2.3.3' + compile 'com.googlecode.json-simple:json-simple:1.1.1' + + +} diff --git a/client/Client.java b/client/Client.java deleted file mode 100644 index 83b803d..0000000 --- a/client/Client.java +++ /dev/null @@ -1,149 +0,0 @@ -import java.util.*; -import java.io.*; -import java.util.concurrent.atomic.AtomicLong; -/** - * @author Ikonija Bogojevic - * @author Sandra Weber - * @author Miguel Perez - * - * This is the main Client class, which spawns ClientThreads which connect to the server. This class - * includes methods for obtaining the user's commands and validating them. - */ -public class Client { - private static String hostName; - - // create a variable to initialize new threads with - private static Thread thrd = null; - - // the threads are kept track of with a linked list - private static LinkedList list = new LinkedList(); - - // AtomicLong is a class that is synchronized, and can be used across - // multiple threads. Here it is used for benchmarking, to store the sum - // of the command completion times for all threads - private static AtomicLong totalTime = new AtomicLong(0); - - // this AtomicLong is used to keep track of the current # of running threads - private static AtomicLong runningThreads = new AtomicLong(0); - private static boolean printOutput = true; - - public static void main(String[] args) { - int menuSelection = 0; - int numProcesses = 1; - // if no hostname is provided, quit - if (args.length == 0) { - System.out.println("User did not enter a host name. Client program exiting."); - System.exit(1); - } - - // until the user selects 8, the Exit option, keep looping and - // offering the menu again after running the queries to the server - else while (menuSelection != 8) { - // display the menu and get the user's choice - menuSelection = mainMenu(); - - // if 8, exit program - if (menuSelection == 8) { - System.out.println("Quitting."); - System.exit(0); - } - - // if 7, ask which command should be run in the benchmark mode - // and how many connections to create - if (menuSelection == 7) { - printOutput = false; - menuSelection = benchmarkMenu(); - numProcesses = numProcessesMenu(); - } - // create threads. since numProcesses is initialized to 1 and gets reset - // at the end of this loop, if the user has not selected to benchmark - // a command, this loop will only create one process - totalTime.set(0); - runningThreads.set(numProcesses); - for (int i = 0; i < numProcesses; i++) { - // make a new thread, tell it the hostname to connect to - // and the command to run. It is also passed the totalTime object, - // so it can record how much time its command took to complete - thrd = new Thread(new ClientThread(args[0], menuSelection, totalTime, printOutput, runningThreads)); - thrd.start(); // start the thread - list.add(thrd); // add the thread to the end of the linked list - - } - - // wait for all of the threads to complete before going to the top - // of the loop again. This ensures that all threads complete before the - // menu is shown again - for (int i = 0; i < numProcesses; i++) { - try { - // wait for the thread to finish - list.get(i).join(); - } catch (InterruptedException e) { - // if the join interrupts the thread, print an error - e.printStackTrace(); - } - } - // while runningThreads is not 0, there are still clients waiting for the server - // to send a response, so keep looping (waiting) until they are finished - while (runningThreads.get() != 0) {} - - System.out.println("Average response time: " + (totalTime.get() / numProcesses) + " ms\n"); - numProcesses = 1; - printOutput = true; - } - - } - //---------------------------------------------------------------------------- - /** - * Function to prompt the user for a command to run - * @return command number 1-8 - */ - public static int mainMenu() { - int menuSelection = 0; - // loop (and prompt again) until the user's input is an integer between 1 and 8 - while ((menuSelection <= 0) || (menuSelection > 8)) { - System.out.println("The menu provides the following choices to the user: "); - System.out.println("1. Host current Date and Time \n2. Host uptime\n" - + "3. Host memory use \n4. Host Netstat \n5. Host current users " - + "\n6. Host running processes \n7. Benchmark (measure mean response time)\n8. Quit "); - System.out.print("Please provide number corresponding to the action you want to be performed: "); - Scanner sc = new Scanner(System.in); - if (sc.hasNextInt()) menuSelection = sc.nextInt(); - } - return menuSelection; - } - - /** - * Function to prompt the user for a benchmark command to run - * @return command number 1-6 - */ - public static int benchmarkMenu() { - int menuSelection = 0; - // loop (and prompt again) until the user's input is an integer between 1 and 6 - while ((menuSelection <= 0) || (menuSelection > 6)) { - System.out.println("Which command would you like to benchmark? "); - System.out.println("1. Host current Date and Time \n2. Host uptime\n" - + "3. Host memory use \n4. Host Netstat \n5. Host current users " - + "\n6. Host running processes"); - System.out.print("Please provide number corresponding to the action you want to be performed: "); - Scanner sc = new Scanner(System.in); - if (sc.hasNextInt()) menuSelection = sc.nextInt(); - } - return menuSelection; - } - - /** - * Function to prompt the user for how many connections to make (for measuring the mean response time) - * @return number 1-100 - */ - public static int numProcessesMenu() { - int menuSelection = 0; - // loop (and prompt again) until the user's input is an integer between 1 and 100 - while ((menuSelection <= 0) || (menuSelection > 100)) { - System.out.print("How many connections to the server would you like to open? [1-100]: "); - Scanner sc = new Scanner(System.in); - if (sc.hasNextInt()) menuSelection = sc.nextInt(); - } - return menuSelection; - } - -} diff --git a/client/ClientThread.java b/client/ClientThread.java deleted file mode 100644 index 1fd17e9..0000000 --- a/client/ClientThread.java +++ /dev/null @@ -1,110 +0,0 @@ -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.Socket; -import java.net.UnknownHostException; -import java.net.ConnectException; -import java.util.concurrent.atomic.AtomicLong; - - -public class ClientThread extends Thread { - // every clientThread is passed which command to send to the server - int menuSelection; - // every clientThread is passed the hostname of the server to connect to - String hostName; - Socket socket = null; - - // totalTime is used to keep the sum of response times for all threads. after all threads - // have completed it is divided by the total number of threads to get an - // average response time - AtomicLong totalTime; - - // runningThreads is the total number of running threads. it is set to numThreads (the number - // of threads that are started) before any threads are started by the Client class. Every time - // a ClientThread finishes it will decrement runningThreads by one, so runningThreads == 0 when - // all threads have finished - AtomicLong runningThreads; - - // each class is passed false for printOutput if the number of threads started is > 1. When running more - // than one client thread the clientThreads should not print output, input order to not clutter the screen - boolean printOutput; - - // startTime and endTime are used to keep track of the current time when the thread conects to the - // server and when the thread gets a response from the server. The difference between the two - // (endTime - startTime) is the response time - long startTime; - long endTime; - - ClientThread(String hostName, int menuSelection, AtomicLong totalTime, boolean printOutput, AtomicLong runningThreads) { - this.menuSelection = menuSelection; - this.hostName = hostName; - this.totalTime = totalTime; - this.printOutput = printOutput; - this.runningThreads = runningThreads; - } - - public void run() { - PrintWriter out = null; - BufferedReader input = null; - try { - //creates a new Socket object and names it socket. - //Establishes the socket connection between the client & server - //name of the machine & the port number to which we want to connect - socket = new Socket(hostName, 15432); - if (printOutput) { - System.out.print("Establishing connection."); - } - //opens a PrintWriter on the socket input autoflush mode - out = new PrintWriter(socket.getOutputStream(), true); - - //opens a BufferedReader on the socket - input = new BufferedReader(new InputStreamReader(socket.getInputStream())); - if (printOutput) System.out.println("\nRequesting output for the '" + menuSelection + "' command from " + hostName); - - // get the current time (before sending the request to the server) - startTime = System.currentTimeMillis(); - - // send the command to the server - out.println(Integer.toString(menuSelection)); - if (printOutput) System.out.println("Sent output"); - - // read the output from the server - String outputString; - while (((outputString = input.readLine()) != null) && (!outputString.equals("END_MESSAGE"))) { - if (printOutput) System.out.println(outputString); - } - - // get the current time (after connecting to the server) - endTime = System.currentTimeMillis(); - // endTime - startTime = the time it took to get the response from the sever - totalTime.addAndGet(endTime - startTime); - - } - catch (UnknownHostException e) { - System.err.println("Unknown host: " + hostName); - System.exit(1); - } - catch (ConnectException e) { - System.err.println("Connection refused by host: " + hostName); - System.exit(1); - } - catch (IOException e) { - e.printStackTrace(); - } - // finally, close the socket and decrement runningThreads - finally { - if (printOutput) System.out.println("closing"); - try { - socket.close(); - runningThreads.decrementAndGet(); - System.out.flush(); - } - catch (IOException e ) { - System.out.println("Couldn't close socket"); - } - } - - } - -} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f3d88b1 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..ba94df8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..2fe81a7 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or 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 UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# 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 "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..24467a1 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,100 @@ +@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=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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%" == "0" goto init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/server/CommandExecutor.java b/server/CommandExecutor.java deleted file mode 100644 index 4d19b34..0000000 --- a/server/CommandExecutor.java +++ /dev/null @@ -1,90 +0,0 @@ -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -/* - * Class containing methods for taking the command string (a string with a digit 1-6) - * received from the server and converting that into its respective Linux shell command, - * then executing it and returning the results. - */ -public class CommandExecutor { - - /** - * Runs the shell command after first using parseCommand() to determine which - * command to run. - * - * @param commandString A string containing a single digit, 1-6; - * @return A string containing the results of the shell command. - */ - static String run(String commandString) { - String result = ""; - String line; - try { - // start the shell command running as a child processes - Process child = Runtime.getRuntime().exec(parseCommand(commandString)); - - // open a BufferedReader to read the output of the child process - BufferedReader output = new BufferedReader(new InputStreamReader(child.getInputStream())); - // while the child process is still outputting, add the output to the result string - while ((line = output.readLine()) != null) { - result = result.concat(line); - result = result.concat("\n"); - } - - result = result.concat("\n"); - // add "END_MESSAGE" to the result string. When the client sees END_MESSAGE it - // will know that the server is done sending - result = result.concat("END_MESSAGE"); - output.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - - return result; - } - - /** - * Converts the digit string into its respective shell command. - * - * @param inputString A string containing a single digit, 1-6; - * @return A string containing the shell command to run - */ - static String parseCommand(String inputString) { - int inputInt = Integer.parseInt(inputString); - String commandString = ""; - switch (inputInt) { - // Date - case 1: - commandString = "date"; - break; - - // Uptime - case 2: - commandString = "uptime"; - break; - - // Memory use - case 3: - commandString = "free"; - break; - - // netstat - case 4: - commandString = "netstat"; - break; - - // current users - case 5: - commandString = "who"; - break; - - // running processes - case 6: - commandString = "ps -e"; - break; - } - - return commandString; - } -} diff --git a/server/ServerThread.java b/server/ServerThread.java deleted file mode 100644 index 6100b0c..0000000 --- a/server/ServerThread.java +++ /dev/null @@ -1,58 +0,0 @@ -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.Socket; -import java.util.concurrent.atomic.AtomicInteger; - -/* - * Individual ServerThread listens for the client to tell it what command to run, then - * runs that command and sends the output of that command to the client - * - */ -public class ServerThread extends Thread { - Socket client = null; - PrintWriter output; - BufferedReader input; - - public ServerThread(Socket client) { - this.client = client; - } - - public void run() { - System.out.print("Accepted connection. "); - - try { - // open a new PrintWriter and BufferedReader on the socket - output = new PrintWriter(client.getOutputStream(), true); - input = new BufferedReader(new InputStreamReader(client.getInputStream())); - System.out.print("Reader and writer created. "); - - String inString; - // read the command from the client - while ((inString = input.readLine()) == null); - System.out.println("Read command " + inString); - - // run the command using CommandExecutor and get its output - String outString = CommandExecutor.run(inString); - System.out.println("Server sending result to client"); - // send the result of the command to the client - output.println(outString); - } - catch (IOException e) { - e.printStackTrace(); - } - finally { - // close the connection to the client - try { - client.close(); - } - catch (IOException e) { - e.printStackTrace(); - } - System.out.println("Output closed."); - } - - } -} - diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b5cb389 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'text-to-speech' + diff --git a/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/ErrorMessageDto.java b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/ErrorMessageDto.java new file mode 100644 index 0000000..f60cc8b --- /dev/null +++ b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/ErrorMessageDto.java @@ -0,0 +1,13 @@ +package com.example.hyokeun.asr.SpeechToText.Dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ErrorMessageDto { + private int code; + private String reason; +} diff --git a/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/ResultMessageDto.java b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/ResultMessageDto.java new file mode 100644 index 0000000..eeab4cb --- /dev/null +++ b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/ResultMessageDto.java @@ -0,0 +1,13 @@ +package com.example.hyokeun.asr.SpeechToText.Dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ResultMessageDto { + private int type; + private String retText; +} diff --git a/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextControlMessageDto.java b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextControlMessageDto.java new file mode 100644 index 0000000..7ab0901 --- /dev/null +++ b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextControlMessageDto.java @@ -0,0 +1,28 @@ +package com.example.hyokeun.asr.SpeechToText.Dto; + +import com.google.gson.annotations.SerializedName; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +public class SpeechToTextControlMessageDto { + + private boolean wakeup; + @SerializedName("wakeup-plm-path") + private String wakeupPlmPath; + @SerializedName("plm-path") + private String plmPath; + @SerializedName("plm-weight") + private double plmWeight; + @SerializedName("enroll-path") + private String enrollPath; + @SerializedName("norm-para-path") + private String normParaPath; + private boolean ns; + @SerializedName("data-path") + private String dataPath; + private String GPSXY; +} diff --git a/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextResponseDto.java b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextResponseDto.java new file mode 100644 index 0000000..e526ed5 --- /dev/null +++ b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextResponseDto.java @@ -0,0 +1,45 @@ +package com.example.hyokeun.asr.SpeechToText.Dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; + + + +import java.util.List; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonAutoDetect(fieldVisibility = Visibility.ANY) +public class SpeechToTextResponseDto { + + private double audio; + private boolean cancel; + private boolean memory_failure; + private long n_sample; + private List nbest; + private ErrorMessageDto error; + + public void setAudio(double audio) { + this.audio = audio; + } + public void setCancel(boolean cancel) { + this.cancel = cancel; + } + public void setMemoryFailure(boolean memory_failure) { + this.memory_failure = memory_failure; + } + public void setNSample(long n_sample) { + this.n_sample = n_sample; + } + public void setNbest(List nbest) { + this.nbest = nbest; + } + public void setError(ErrorMessageDto error) { + this.error = error; + } + +} diff --git a/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextReturnedWordsDto.java b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextReturnedWordsDto.java new file mode 100644 index 0000000..582d782 --- /dev/null +++ b/src/main/java/com/example/hyokeun/asr/SpeechToText/Dto/SpeechToTextReturnedWordsDto.java @@ -0,0 +1,41 @@ +package com.example.hyokeun.asr.SpeechToText.Dto; + +import com.google.gson.annotations.SerializedName; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonAutoDetect(fieldVisibility = Visibility.ANY) +public class SpeechToTextReturnedWordsDto { + private int confidence; + private String extHypothesis; + private String hypothesis; + private List word; + @SerializedName("final") + private boolean final_; + + public void setConfidence(int confidence) { + this.confidence = confidence; + } + public void setExtHypothesis(String extHypothesis) { + this.extHypothesis = extHypothesis; + } + public void setHypothesis(String hypothesis) { + this.hypothesis = hypothesis; + } + public void setWord(List word) { + this.word = word; + } + public void setFinal(boolean final_) { + this.final_ = final_; + } +} diff --git a/src/main/java/com/example/hyokeun/asr/SpeechToText/ServerThread.java b/src/main/java/com/example/hyokeun/asr/SpeechToText/ServerThread.java new file mode 100644 index 0000000..9aea45a --- /dev/null +++ b/src/main/java/com/example/hyokeun/asr/SpeechToText/ServerThread.java @@ -0,0 +1,253 @@ +package com.example.hyokeun.asr.SpeechToText; + +import com.example.hyokeun.asr.SpeechToText.Dto.SpeechToTextControlMessageDto; +import com.example.hyokeun.asr.SpeechToText.Dto.SpeechToTextResponseDto; +import com.example.hyokeun.asr.SpeechToText.Dto.SpeechToTextReturnedWordsDto; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.Socket; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; + +import com.google.gson.JsonParser; + +import java.util.Date; + +//import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; + + + +/* + * Individual ServerThread listens for the client to tell it what command to run, then + * runs that command and sends the output of that command to the client + * + */ +public class ServerThread extends Thread { + private final static long CONTEXT_MESSAGE_HEADER = 0x0000FFFFL; + + Socket client = null; + + private InputStream m_sock_in = null; + private OutputStream m_sock_out = null; + + PrintWriter output; + BufferedReader input; + private SpeechToTextControlMessageDto controlMsgDto = null; + private long len = 0; + + public ServerThread(Socket client) throws IOException { + this.client = client; + this.controlMsgDto = new SpeechToTextControlMessageDto(); + } + + + // little endian + private byte[] intToByteArray(int value) { + byte[] byteArray = new byte[4]; + byteArray[3] = (byte) (value >> 24); + byteArray[2] = (byte) (value >> 16); + byteArray[1] = (byte) (value >> 8); + byteArray[0] = (byte) (value); + return byteArray; + } + + private int byteArrayToInt(byte bytes[]) { + if(bytes != null && bytes.length >= 4){ + return ((((int) bytes[3] & 0xff) << 24) | + (((int) bytes[2] & 0xff) << 16) | + (((int) bytes[1] & 0xff) << 8) | + (((int) bytes[0] & 0xff))); + } else { + return 0; + } + } + + private byte[] recvBytes(int len) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buffer; + int total_length = 0; + while (len != total_length && !client.isClosed()) { + + buffer = new byte[len]; + int temp_length = -1; + try { + if(!client.isInputShutdown()) { + temp_length = m_sock_in.read(buffer); + } + } catch (IOException e) { + e.printStackTrace(); + break; + } + if(temp_length==-1){ + break; + } + if (temp_length > 0) { + total_length += temp_length; + baos.write(buffer, 0, temp_length); + } + } + return baos.toByteArray(); + } + + // recv a 32-bit int + private int recvInt32() throws IOException { + byte[] b32 = this.recvBytes(4); + int i32 = byteArrayToInt(b32); + return i32; + } + + private void sendBytes(byte[] buf, int len, boolean flush) throws IOException { + if(!client.isClosed()) { + m_sock_out.write(buf, 0, len); + if (flush) { + m_sock_out.flush(); + } + } + } + + private void sendInt32(int n, boolean flush) throws IOException { + this.sendBytes(intToByteArray(n), 4, flush); + } + + public int recvLength() throws IOException { + int len = (int)((long)(this.recvInt32()) & CONTEXT_MESSAGE_HEADER); + return len; + } + + public void recvControlMsg() throws IOException { + int len = this.recvLength(); + JsonParser parser = new JsonParser(); + byte[] clientData = this.recvBytes(len); + String decoded = new String(clientData, "UTF-8"); + System.out.println(decoded); + // TODO: Fill into this.controlMsgDto + } + + private void recvAudioData() throws IOException { + int totalLength = 0; + int len = this.recvLength(); + while (len > 0) { + totalLength += len; + byte[] clientData = this.recvBytes(len); + len = this.recvLength(); + } + System.out.println("Total Audio data length: " + totalLength); + } + + public void sendSttResult() { + SpeechToTextResponseDto dtos = new SpeechToTextResponseDto(); + + Date date = new Date(); + long time = date.getTime(); + //String returnStr = "Hello " + time; + + dtos.setCancel(false); + dtos.setMemoryFailure(false); + dtos.setNSample(1); + + ArrayList pitches = new ArrayList(); + ArrayList words = new ArrayList(); + words.add("Hello"); + words.add("World"); + words.add(" " + time); + SpeechToTextReturnedWordsDto rwd = new SpeechToTextReturnedWordsDto(); + rwd.setConfidence(50); + rwd.setExtHypothesis("OK1"); + rwd.setHypothesis("OK2"); + rwd.setWord(words); + rwd.setFinal(true); + pitches.add(rwd); + + dtos.setNbest(pitches); + + ObjectMapper Obj = new ObjectMapper(); + //Obj.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + String jsonStr = null; + try { + jsonStr = Obj.writeValueAsString(dtos); + System.out.println(jsonStr); + } + catch (IOException e) { + e.printStackTrace(); + } + System.out.println("Jackson string: " ); + System.out.println(jsonStr); + + byte b1[] = jsonStr.getBytes(); + + try { + this.sendInt32(b1.length, false); + this.sendBytes(b1, b1.length, true); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + + public void run() { + System.out.print("Accepted connection. "); + + try { + // open a new PrintWriter and BufferedReader on the socket + /* + output = new PrintWriter(client.getOutputStream(), true); + input = new BufferedReader(new InputStreamReader(client.getInputStream())); + */ + + try { + this.m_sock_in = client.getInputStream(); + this.m_sock_out = client.getOutputStream(); + System.out.print("Reader and writer created. "); + } + catch (IOException e) { + e.printStackTrace(); + } + + String inString; + + this.recvControlMsg(); + this.recvAudioData(); + + this.sendSttResult(); + + /* + while ((inString = input.readLine()) == null); + System.out.println("Read command " + inString); + + // run the command using CommandExecutor and get its output + String outString = CommandExecutor.run(inString); + System.out.println("Server sending result to client"); + try { + Thread.sleep(3*1000); + } + catch (InterruptedException e) { + System.out.println("Sleep failed..."); + } + // send the result of the command to the client + output.println(outString); + */ + } + catch (IOException e) { + e.printStackTrace(); + } + finally { + // close the connection to the client + try { + client.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + System.out.println("Output closed."); + } + + } +} + diff --git a/server/Server.java b/src/main/java/com/example/hyokeun/asr/SpeechToTextService.java similarity index 70% rename from server/Server.java rename to src/main/java/com/example/hyokeun/asr/SpeechToTextService.java index 71c37df..e23ecd7 100644 --- a/server/Server.java +++ b/src/main/java/com/example/hyokeun/asr/SpeechToTextService.java @@ -1,15 +1,20 @@ +package com.example.hyokeun.asr; + +import com.example.hyokeun.asr.SpeechToText.ServerThread; + import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; + /* * Main server class. This class includes main(), and is the class that listens * for incoming connections and starts ServerThreads to handle those connections * */ -public class Server { +public class SpeechToTextService { /** * @param args @@ -18,11 +23,16 @@ public static void main(String[] args) { AtomicInteger numThreads = new AtomicInteger(0); // the list of threads is kept in a linked list ArrayList list = new ArrayList(); + + int port_no_to_use = 15432; + if (args.length != 0) { + port_no_to_use = Integer.parseInt(args[0]); + } try { // listen for incoming connections on port 15432 - ServerSocket socket = new ServerSocket(15432); - System.out.println("Server listening on port 15432"); + ServerSocket socket = new ServerSocket(port_no_to_use); + System.out.println("\nServer listening on port " + port_no_to_use); // loop (forever) until program is stopped while(true) { @@ -34,7 +44,7 @@ public static void main(String[] args) { list.add(thrd); thrd.start(); numThreads.incrementAndGet(); - System.out.println("Thread " + numThreads.get() + " started."); + System.out.println("\nThread " + numThreads.get() + " started."); } }