commit 8b0d9648199670e95ce1bb9bb28b4b9cc9f71311 Author: saile2204 Date: Thu Jul 29 16:23:39 2021 +0200 Initial commit diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..73f69e0 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/LinuxVolumeControl.iml b/.idea/LinuxVolumeControl.iml new file mode 100644 index 0000000..2e531fa --- /dev/null +++ b/.idea/LinuxVolumeControl.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..61a9130 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..fb6a41a --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,20 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..ed0b7d9 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries-with-intellij-classes.xml b/.idea/libraries-with-intellij-classes.xml new file mode 100644 index 0000000..9fa3156 --- /dev/null +++ b/.idea/libraries-with-intellij-classes.xml @@ -0,0 +1,65 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..3bdc404 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..bd12a1b --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..797acea --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..e96534f --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..834f853 --- /dev/null +++ b/build.gradle @@ -0,0 +1,34 @@ + +plugins { + id'application' + id'com.github.johnrengelman.shadow' version '5.2.0' +} + +mainClassName = 'de.sailehd.Main' +version = '0.1.1' + +sourceCompatibility = targetCompatibility = 1.8 + +repositories { + jcenter() + mavenCentral() + maven { + name 'm2-dv8tion' + url 'https://m2.dv8tion.net/releases' + } +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + implementation("ch.qos.logback:logback-classic:1.2.3") + implementation 'com.fazecast:jSerialComm:[2.0.0,3.0.0)' + implementation 'com.jcraft:jsch:0.1.55' + implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.0' + implementation group: 'javax.mail', name: 'mail', version: '1.4.1' + implementation group: 'net.java.dev.jna', name: 'jna', version: '4.5.1' + implementation group: 'org.projectlombok', name: 'lombok', version: '1.16.20' + implementation 'net.java.dev.jna:jna:4.5.1' +} + +compileJava.options.encoding = 'UTF-8' \ No newline at end of file diff --git a/config.esb b/config.esb new file mode 100644 index 0000000..ccb266b --- /dev/null +++ b/config.esb @@ -0,0 +1,6 @@ +config.esb +{ +ArrayList Slider = { System Microsoft|Edge spotify } +Boolean debug = false +String portName = ttyACM0 +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c 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..f371643 --- /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-7.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/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..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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 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%" == "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%"=="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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..abb7473 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'LinuxVolumeControl' + diff --git a/src/main/java/de/sailehd/CombinedSink.java b/src/main/java/de/sailehd/CombinedSink.java new file mode 100644 index 0000000..f668852 --- /dev/null +++ b/src/main/java/de/sailehd/CombinedSink.java @@ -0,0 +1,7 @@ +package de.sailehd; + +public class CombinedSink { + public Integer combinedSinkID; + public String name; + public Integer moduleNumber; +} \ No newline at end of file diff --git a/src/main/java/de/sailehd/Main.java b/src/main/java/de/sailehd/Main.java new file mode 100644 index 0000000..6b36e64 --- /dev/null +++ b/src/main/java/de/sailehd/Main.java @@ -0,0 +1,168 @@ +package de.sailehd; + +import java.io.IOException; +import com.fazecast.jSerialComm.*; +import de.sailehd.support.Debug; +import de.sailehd.support.EasyBase; +import de.sailehd.support.TextColor; + +import java.io.*; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; + +public class Main { + + + private Thread loop; + private static EasyBase config; + + + public static void main(String[] args) throws Exception { + config = new EasyBase("config"); + //PulseAudio.setDefaultSink(0); + + config.createData("portName", new String("ttyACM0")); + config.createData("debug", false); + + ArrayList SliderArray = new ArrayList(); + SliderArray.add("System"); + SliderArray.add("Microsoft|Edge"); + SliderArray.add("spotify"); + config.createData("Slider", SliderArray); + + + ArrayList sliderValues = new ArrayList(); + SerialPort comPort = null; + Main main = new Main(); + + + if(SerialPort.getCommPort((String) config.getData("portName")) != null){ + comPort = SerialPort.getCommPort((String) config.getData("portName")); + Debug.log(TextColor.GREEN + "Port " + comPort + " was found."); + } + else{ + Debug.log(TextColor.RED + "Port " + comPort + " not found."); + System.exit(8); + } + + + try{ + comPort.openPort(); + comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0); + Debug.log(TextColor.GREEN + "Connected to Port " + comPort.getSystemPortName() + "."); + } + catch (Exception e){ + Debug.log(TextColor.RED + "Could not connect to Port " + comPort.getSystemPortName() + "."); + System.exit(8); + } + + + + InputStream in = comPort.getInputStream(); + try + { + Scanner scan = new Scanner(in);; + + int startSkip = 20; + while (scan.hasNextLine()){ + String line = scan.nextLine(); + if(startSkip <= 0){ + + for (Float value: parseInput(line)) { + sliderValues.add(map(value, 0.00f, 5.00f, 0f, 100f)); + } + + + main.loop(sliderValues, (boolean) config.getData("debug")); + + } + else{ + startSkip--; + } + sliderValues = new ArrayList(); + } + + } catch (Exception e) { e.printStackTrace(); } + + + } + + public void loop(ArrayList sliderValues, boolean debug) throws IOException { + ArrayList slider = (ArrayList) config.getData("Slider"); + if(debug){ + Debug.clear(); + StringBuilder debugRegisterdDivices = new StringBuilder(); + debugRegisterdDivices.append("Registered Devices: "); + for (String sliderVal : slider) { + if(slider.indexOf(sliderVal) != slider.size() - 1){ + debugRegisterdDivices.append(sliderVal + ", "); + } + else{ + debugRegisterdDivices.append(sliderVal); + } + } + + Debug.log(debugRegisterdDivices.toString()); + + int i = 0; + for (Float value : sliderValues) { + try { + Debug.log("Slider[" + i + "]" + ": " + value + "% | " + slider.get(i)); + }catch (Exception e){ + Debug.log("Slider[" + i + "]" + ": " + value + "%"); + } + + + i++; + } + + + } + + + + for (String application : slider) { + //Debug.log(slider.indexOf(application) + ""); + if(application.equals("System")){ + PulseAudio.setVolumeOutput(PulseAudio.getDefaultSinkIndex(), sliderValues.get(slider.indexOf(application)).intValue()); + } + else{ + PulseAudio.setVolumeInput(PulseAudio.getInputSinkFormApplicationIndex(application), sliderValues.get(slider.indexOf(application)).intValue()); + } + + } + //PulseAudio.setVolumeInput(PulseAudio.getInputSinkFormApplicationIndex("Microsoft Edge"), sliderValues.get(1)); + //PulseAudio.setVolumeInput(PulseAudio.getInputSinkFormApplicationIndex("spotify"), sliderValues.get(2)); + + + + } + + public static ArrayList parseInput(String line){ + ArrayList sliderValues = new ArrayList(); + + String[] valuesRaw = line.split("\\|"); + + for (String valueRaw: valuesRaw) { + sliderValues.add(Float.parseFloat(valueRaw)); + } + + return sliderValues; + } + + public static long map(long x, long in_min, long in_max, long out_min, long out_max) { + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + } + public static double map(double x, double in_min, double in_max, double out_min, double out_max) { + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + } + public static float map(float x, float in_min, float in_max, float out_min, float out_max) { + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + } + public static int map(int x, int in_min, int in_max, int out_min, int out_max) { + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + } +} diff --git a/src/main/java/de/sailehd/PulseAudio.java b/src/main/java/de/sailehd/PulseAudio.java new file mode 100644 index 0000000..d1b2bb7 --- /dev/null +++ b/src/main/java/de/sailehd/PulseAudio.java @@ -0,0 +1,741 @@ +package de.sailehd; + +import de.sailehd.support.Debug; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.*; +import java.util.concurrent.Semaphore; + +public class PulseAudio { + public static final String module = "PulseAudio"; + public static final int ABORT_COUNTER_MAX = 500; + public static final int MIN_TIME_BETWEEN_PA_ACCESS_MS = 0; + private static long lastAccess = 0; + private static Semaphore semaphorePulseAudio = new Semaphore(1); + + public static class Log { + private static Boolean output = false; + + public static void setOutput(Boolean val) { + output = val; + } + + public static void log(String str) { + if (output) { + System.out.println(module + ": " + str); + } + } + } + + public static class SinkInput { + public Process playProcess; + public Process getProcess; + public int sinkInputID; + } + + public enum Player { + MPLAYER, XINE + } + + /** + * This method limits the access to PulseAudio, by waiting a minimum time + * between two accesses. This is used to prevent crashes in PulseAudio. It + * needs to be called before any other action in PulseAudio. + */ + public static synchronized void checkAccessTime() { + if (lastAccess == 0) { + lastAccess = System.currentTimeMillis(); + return; + } else { + while (System.currentTimeMillis() - lastAccess < MIN_TIME_BETWEEN_PA_ACCESS_MS) + ; + lastAccess = System.currentTimeMillis(); + return; + } + } + + /** + * This method creates a PulseAudio null sink and returns the index of the + * created sink + * + * @param sinkName + * name of the sink to create + * + * @return >0: index of the newly created null sink -1: not able to identify + * created sink -2: sink not created + * @throws IOException + */ + public static int createSink(String sinkName) throws IOException { + checkAccessTime(); + + HashSet indicesBefore = new HashSet(); + HashSet indicesAfter = new HashSet(); + + String scheme = " | grep index | sed 's/\\([ \t]*\\|[ \t]*\\*[ \t]*\\)index: //'"; + String cmd = "pacmd list-sinks" + scheme; + + /* reading in sink numbers */ + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + String line; + while ((line = in.readLine()) != null) { + indicesBefore.add(Integer.decode(line)); + } + + p = Runtime.getRuntime().exec( + new String[] { + "/bin/bash", + "-c", + "pactl load-module module-null-sink sink_name=" + + sinkName }); + + /* + * this is necessary to allow PulseAudio some CPU time to create the + * sink + */ + in.close(); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + /* reading in sink numbers */ + p = Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", cmd }); + lsOut = p.getInputStream(); + r = new InputStreamReader(lsOut); + in = new BufferedReader(r); + while ((line = in.readLine()) != null) { + indicesAfter.add(Integer.decode(line)); + } + in.close(); + + /* compare sink numbers before and after creating */ + indicesAfter.removeAll(indicesBefore); + if (indicesAfter.size() > 1) { + /* Error! Could not identify created sink! */ + Log.log("Error! Could not identify null sink!"); + return -1; + } else if (indicesAfter.size() == 0) { + /* Error! Sink could not be created */ + Log.log("Error! Could not create null sink!"); + return -2; + } else { + /* successfully created and identified stream */ + int index = (int) indicesAfter.toArray()[0]; + Log.log("created null sink " + sinkName + " at index " + index); + return index; + } + } + + /** + * This method loads a stream from a given URL via the defined player and + * returns the handle to the player process, as well as the index of the + * created PulseAudio sink input + * + * @param URL + * address of the stream to open + * @param player + * player to use to play stream + * @param sink + * sink to play into (0: default sink), applicable for mplayer + * only + * @return class containing the process handle and the index of the created + * sink-input index for the created stream + * @throws IOException + */ + public static SinkInput createStream(String URL, Player player, int sink) + throws IOException { + checkAccessTime(); + + HashSet indicesBefore = new HashSet(); + HashSet indicesAfter = new HashSet(); + SinkInput returnVal = new SinkInput(); + + String scheme = " | grep index | sed 's/\\([ \t]*\\|[ \t]*\\*[ \t]*\\)index: //'"; + String cmd = "pacmd list-sink-inputs" + scheme; + + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + String line; + Log.log("indices before:"); + while ((line = in.readLine()) != null) { + indicesBefore.add(Integer.decode(line)); + Log.log(line); + } + + if (player == Player.MPLAYER) { + if (sink == 0) { + returnVal.playProcess = Runtime.getRuntime().exec( + new String[] { + "/bin/bash", + "-c", + "/usr/bin/mplayer -ao pulse " + URL + + " > /dev/null 2>&1" }); + } else { + returnVal.playProcess = Runtime.getRuntime().exec( + new String[] { + "/bin/bash", + "-c", + "/usr/bin/mplayer -ao pulse::" + sink + " " + + URL + " > /dev/null 2>&1" }); + } + } else if (player == Player.XINE) { + returnVal.playProcess = Runtime.getRuntime().exec( + new String[] { + "/bin/bash", + "-c", + "/usr/bin/aaxine -A pulseaudio " + URL + + " > /dev/null 2>&1" }); + } + + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + int abortCounter = 0; + + while (indicesBefore.containsAll(indicesAfter)) { + indicesAfter = new HashSet<>(); + p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + lsOut = p.getInputStream(); + r = new InputStreamReader(lsOut); + in = new BufferedReader(r); + while ((line = in.readLine()) != null) { + indicesAfter.add(Integer.decode(line)); + } + + abortCounter++; + if (abortCounter > ABORT_COUNTER_MAX) { + break; + } + } + + Log.log("indices after:"); + for (Iterator i = indicesAfter.iterator(); i.hasNext();) { + Integer integer = (Integer) i.next(); + + Log.log("" + integer); + } + + in.close(); + r.close(); + lsOut.close(); + + indicesAfter.removeAll(indicesBefore); + if (indicesAfter.size() > 1) { + /* Error! Could not identify created stream! */ + Log.log("Error! Could not identify stream sink (" + URL + ")!"); + returnVal.sinkInputID = -1; + return returnVal; + } else if (indicesAfter.size() == 0) { + /* Error! Stream could not be created */ + Log.log("Error! Could not create stream (" + URL + ")!"); + returnVal.sinkInputID = -2; + return returnVal; + } else { + /* successfully created and identified stream */ + returnVal.sinkInputID = (int) indicesAfter.toArray()[0]; + Log.log("created stream (" + URL + ") at sink " + sink + + ", sinkInput: " + returnVal.sinkInputID); + return returnVal; + } + } + + /** + * This method sets the default sink for PulseAudio applications + * + * @param sinkIndex + * index of the sink to make default + * @throws IOException + */ + public static void setDefaultSink(int sinkIndex) throws IOException { + checkAccessTime(); + + Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", + "pacmd set-default-sink " + sinkIndex }); + Log.log("changed default sink to " + sinkIndex); + } + + /** + * This method combines a set of given sinks + * + * @param combinedSink + * element containing combined sink parameters + * @param sinks + * collection of sinks indices to combine + * @return index of newly created sink + * @throws IOException + */ + public static int combineSinks(CombinedSink combinedSink, + Collection sinks) throws IOException { + checkAccessTime(); + + HashSet indicesBefore = new HashSet(); + HashSet indicesAfter = new HashSet(); + + String scheme = " | grep index | sed 's/\\([ \t]*\\|[ \t]*\\*[ \t]*\\)index: //'"; + String cmd = "pacmd list-sinks" + scheme; + + /* reading in sink numbers */ + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + String line; + Log.log("indices before: "); + while ((line = in.readLine()) != null) { + indicesBefore.add(Integer.decode(line)); + Log.log(line); + } + + String combindCmd = "pactl load-module module-combine-sink sink_name=" + + combinedSink.name + " slaves="; + Iterator it = sinks.iterator(); + while (it.hasNext()) { + int sinkNo = it.next(); + combindCmd = combindCmd.concat(Integer.toString(sinkNo)); + if (it.hasNext()) { + combindCmd = combindCmd.concat(","); + } + } + byte[] consoleInput = new byte[10]; + InputStream inStream = Runtime.getRuntime() + .exec(new String[] { "/bin/bash", "-c", combindCmd }) + .getInputStream(); + int read = -1; + while (read == -1) { + read = inStream.read(consoleInput); + } + int moduleNumber = Integer + .decode(new String(consoleInput, 0, read - 1)); + combinedSink.moduleNumber = moduleNumber; + Log.log("module number of sink: " + moduleNumber); + + in.close(); + + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + /* reading in sink numbers */ + p = Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", cmd }); + lsOut = p.getInputStream(); + r = new InputStreamReader(lsOut); + in = new BufferedReader(r); + Log.log("indices after: "); + while ((line = in.readLine()) != null) { + indicesAfter.add(Integer.decode(line)); + Log.log(line); + } + in.close(); + + /* compare sink numbers before and after creating */ + indicesAfter.removeAll(indicesBefore); + if (indicesAfter.size() > 1) { + /* Error! Could not identify created sink! */ + Log.log("Error! Could not identify combined sink!"); + return -1; + } else if (indicesAfter.size() == 0) { + /* Error! Sink could not be created */ + Log.log("Error! Could not create combined sink!"); + return -2; + } else { + /* successfully created and identified stream */ + int index = (int) indicesAfter.toArray()[0]; + Log.log("created combined sink " + combinedSink.name + " at index " + + index); + return index; + } + } + + /** + * This method finds the sink for a given sinkInput + * + * @param sinkInput + * sinkInput to find sink for + * @return index of sink receiving sinkInput + * @throws IOException + */ + public static int getSinkIndex(int sinkInput) throws IOException { + checkAccessTime(); + + String scheme = " | grep -A 4 \"index: " + + sinkInput + + "\" | grep \"sink\" | sed 's/[ \t]*sink: //' | sed 's/[ \t].*//'"; + String cmd1 = "pacmd list-sink-inputs" + scheme; + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd1 }); + + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + + String line; + while ((line = in.readLine()) != null) { + return Integer.decode(line); + } + + return -1; + } + + public static int getDefaultSinkIndex() throws IOException { + checkAccessTime(); + + String scheme = " | grep -e 'name:' -e 'index:'"; + String cmd1 = "pacmd list-sinks" + scheme; + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd1 }); + + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + + String line; + + while ((line = in.readLine()) != null) { + if(line.contains("*")){ + return getIntegers(line).get(0); + } + } + + return -1; + } + + public static ArrayList getIntegers(String string) { + string = string.replaceAll("[^-?0-9]+", " "); + ArrayList integers = new ArrayList(); + for (String s: Arrays.asList(string.trim().split(" "))) { + integers.add(Integer.decode(s)); + } + + return integers; + } + + + /** + * This method moves the given sink input to the given destination sink + * + * @param sinkInput + * sinkInput to move + * @param destinationSink + * destination sink to move sink input to + * @throws IOException + */ + public static void moveSinkInput(int sinkInput, int destinationSink) + throws IOException { + checkAccessTime(); + + Runtime.getRuntime().exec( + new String[] { + "/bin/bash", + "-c", + "pactl move-sink-input " + sinkInput + " " + + destinationSink }); + Log.log("moved sink input " + sinkInput + " to sink " + destinationSink); + } + + /** + * This method sets the volume of the given sink + * + * @param sink + * sink to adjust volume + * @param volume_percent + * volume to set in percent + * @throws IOException + */ + public static void setVolumeOutput(int sink, int volume_percent) + throws IOException { + checkAccessTime(); + + int volume = 65535 / 100 * volume_percent; + Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", + "pacmd set-sink-volume " + sink + " " + volume }); + Log.log("set volume of output-sink " + sink + " to " + volume + " (" + + volume_percent + "%)"); + } + + public static void setVolumeInput(int sink, int volume_percent) + throws IOException { + checkAccessTime(); + + int volume = 65535 / 100 * volume_percent; + Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", + "pacmd set-sink-input-volume " + sink + " " + volume}); + Log.log("set volume of input-sink " + sink + " to " + volume + " (" + + volume_percent + "%)"); + } + + /** + * This method returns the sink index to a given deviceIdentifier + * + * @param devicePath + * sysfs.path of the device + * @return index of the device to find + */ + public static int getIndex(String devicePath) { + checkAccessTime(); + + try { + String scheme = " | grep -B 42 \"" + + devicePath + + "\" | grep \"index\" | sed 's/\\([ \t]*\\|[ \t]*\\*[ \t]*\\)index: //'"; + String cmd1 = "pacmd list-sinks" + scheme; + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd1 }); + + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + + String line; + while ((line = in.readLine()) != null) { + return Integer.decode(line); + } + + return -1; + } catch (IOException e) { + e.printStackTrace(); + + return -1; + } + } + + /** + * This method starts a stream via wget + * + * @param wgetURL + * URL of stream to open via wget + * @param sink + * sink to attach stream to + * @return stream information of created stream + * @throws IOException + */ + public static SinkInput startMusicStream(String wgetURL, Integer sink, + String pipePathFull) throws IOException { + checkAccessTime(); + + HashSet indicesBefore = new HashSet(); + HashSet indicesAfter = new HashSet(); + SinkInput returnVal = new SinkInput(); + + String scheme = " | grep index | sed 's/\\([ \t]*\\|[ \t]*\\*[ \t]*\\)index: //'"; + String cmd = "pacmd list-sink-inputs" + scheme; + + Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", "rm " + pipePathFull }); + Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", "mkfifo " + pipePathFull }); + + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + String line; + while ((line = in.readLine()) != null) { + indicesBefore.add(Integer.decode(line)); + } + in.close(); + Log.log("starting WGET process for stream " + wgetURL); + returnVal.getProcess = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", + "wget \"" + wgetURL + "\" -O - > " + pipePathFull }); + Log.log("completed starting WGET process for stream " + wgetURL); + + Log.log("starting play process for stream " + wgetURL + " from pipe " + + pipePathFull + " on sink " + sink); + returnVal.playProcess = Runtime.getRuntime().exec( + new String[] { + "/bin/bash", + "-c", + "mplayer -ao pulse::" + sink + " -cache 2048 " + + pipePathFull + " > /dev/null 2>&1" }); + Log.log("completed starting play process for stream " + wgetURL + + " from pipe " + pipePathFull + " on sink " + sink); + + while (indicesBefore.containsAll(indicesAfter)) { + indicesAfter = new HashSet<>(); + p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + lsOut = p.getInputStream(); + r = new InputStreamReader(lsOut); + in = new BufferedReader(r); + while ((line = in.readLine()) != null) { + indicesAfter.add(Integer.decode(line)); + } + } + in.close(); + + indicesAfter.removeAll(indicesBefore); + if (indicesAfter.size() > 1) { + /* Error! Could not identify created stream! */ + Log.log("Error! Could not identify stream sink (" + wgetURL + ")!"); + returnVal.sinkInputID = -1; + return returnVal; + } else if (indicesAfter.size() == 0) { + /* Error! Stream could not be created */ + Log.log("Error! Could not create stream (" + wgetURL + ")!"); + returnVal.sinkInputID = -2; + return returnVal; + } else { + /* successfully created and identified stream */ + returnVal.sinkInputID = (int) indicesAfter.toArray()[0]; + Log.log("created stream (" + wgetURL + ") at sink " + sink + + ", sinkInput: " + returnVal.sinkInputID); + return returnVal; + } + } + + /** + * This method checks if a sink exists, which includes the given + * sinkNamePart. + * + * @param sinkNamePart + * full or part of the name of the sink to check + * + * @return true: sink with this part in the name exists false: sink does not + * exist + */ + public static Boolean checkIfOutoutSinkExists(String sinkNamePart) { + Boolean sinkExists = false; + + try { + String cmd = "pacmd list-sinks | grep \"name: \""; + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + String line; + while ((line = in.readLine()) != null) { + if (line.contains(sinkNamePart)) { + sinkExists = true; + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return sinkExists; + } + + public static Boolean checkIfInputSinkExists(String sinkNamePart) { + Boolean sinkExists = false; + + try { + String cmd = "pacmd list-sink-inputs | tr '\\n' '\\r' | perl -pe 's/.*? *index: ([0-9]+).+?application\\.name = \"([^\\r]+)\"\\r.+?(?=index:|$)/\\2:\\1\\r/g' | tr '\\r' '\\n'"; + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + String line; + while ((line = in.readLine()) != null) { + if (line.contains(sinkNamePart)) { + sinkExists = true; + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return sinkExists; + } + + public static int getInputSinkFormApplicationIndex(String sinkNamePart) { + int sinkIndex = -1; + + try { + String cmd = "pacmd list-sink-inputs | tr '\\n' '\\r' | perl -pe 's/.*? *index: ([0-9]+).+?application\\.name = \"([^\\r]+)\"\\r.+?(?=index:|$)/\\2:\\1\\r/g' | tr '\\r' '\\n'"; + Process p = Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", cmd }); + InputStream lsOut = p.getInputStream(); + InputStreamReader r = new InputStreamReader(lsOut); + BufferedReader in = new BufferedReader(r); + String line; + while ((line = in.readLine()) != null) { + if (line.contains(sinkNamePart)) { + sinkIndex = Integer.parseInt(line.split(":")[1]); + + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return sinkIndex; + } + + + /** + * This method ensures that only one instance accesses PulseAudio. It also + * ensures that timing requirements are kept. + */ + public static void acquireSemaphore() throws InterruptedException { + checkAccessTime(); + semaphorePulseAudio.acquire(); + } + + /** + * This method ensures that only one instance accesses PulseAudio. It also + * ensures that timing requirements are kept. + */ + public static void releaseSemaphore() throws InterruptedException { + lastAccess = System.currentTimeMillis(); + semaphorePulseAudio.release(); + } + + /** + * This method deletes a combined sink from the list of sinks. + * + * @param sink + * element containing combined sink parameters + */ + public static void removeSink(CombinedSink sink) { + try { + Log.log("removing unused sink (module number: " + sink.moduleNumber + + ")"); + Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", + "pactl unload-module " + sink.moduleNumber }); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * This method removes an input from a sink. + * + * @param sinkInputID + * ID of the sink input to remove + */ + public static void removeSinkInput(Integer sinkInputID) { + try { + Log.log("removing sinkInputID " + sinkInputID + " from sink"); + Runtime.getRuntime().exec( + new String[] { "/bin/bash", "-c", + "pacmd kill-sink-input " + sinkInputID }); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/de/sailehd/support/Debug.java b/src/main/java/de/sailehd/support/Debug.java new file mode 100644 index 0000000..31bf6f4 --- /dev/null +++ b/src/main/java/de/sailehd/support/Debug.java @@ -0,0 +1,42 @@ +package de.sailehd.support; + +public class Debug { + + public static void log(String message){ + System.out.println(message); + } + + public static void logError(String message){ + System.err.println(message); + } + + public static void logWarning(String message){ System.out.println(TextColor.YELLOW + message + TextColor.RESET);} + + public static void clear(){ + System.out.print("\033[H\033[2J"); + + System.out.flush(); + } + + public final static void clearConsole() + { + try + { + final String os = System.getProperty("os.name"); + + if (os.contains("Windows")) + { + Runtime.getRuntime().exec("cls"); + } + else + { + Runtime.getRuntime().exec("clear"); + } + } + catch (final Exception e) + { + // Handle any exceptions. + } + } + +} diff --git a/src/main/java/de/sailehd/support/EasyBase.java b/src/main/java/de/sailehd/support/EasyBase.java new file mode 100644 index 0000000..ee7149e --- /dev/null +++ b/src/main/java/de/sailehd/support/EasyBase.java @@ -0,0 +1,777 @@ +package de.sailehd.support; + +import java.io.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.Scanner; + +public class EasyBase { + + private File easyBase = null; + private ArrayList lines = new ArrayList(); + private String fileName; + private String baseName; + + + public EasyBase(String name){ + fileName = name + ".esb"; + baseName = name; + UpdateBaseFile(false); + } + + public void UpdateBaseFile(boolean debugMessage){ + try { + File newDataBase = new File(fileName); + if (newDataBase.createNewFile()) { + System.out.println("File created: " + newDataBase.getName()); + easyBase = newDataBase; + initFile(easyBase); + } else { + //System.out.println("File already exists."); + try{ + ClassLoader classLoader = getClass().getClassLoader(); + File tempEasyBase = new File(fileName); + try{ + if(tempEasyBase.getName().endsWith(".esb")){ + lines = readFile(tempEasyBase); + try { + if(lines.get(0).equals(fileName) && lines.get(1).equals("{") && lines.get(lines.size() - 1).equals("}")){ + easyBase = tempEasyBase; + if(debugMessage){ + System.out.println(baseName +" Initialized"); + } + + //System.out.println(lines.toString()); + } + } + catch (Exception e){ + System.out.println("The File is not a vaild Database"); + e.printStackTrace(); + } + + } + } + catch (Exception e){ + System.out.println("The File is not a vaild Database"); + e.printStackTrace(); + } + } + catch (Exception e){ + e.printStackTrace(); + } + } + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + } + + private ArrayList readFile(File file){ + ArrayList tempLines = new ArrayList(); + try { + Scanner myReader = new Scanner(file); + while (myReader.hasNextLine()) { + String data = myReader.nextLine(); + tempLines.add(data); + } + myReader.close(); + } catch (FileNotFoundException e) { + print("An error occurred."); + e.printStackTrace(); + } + + return tempLines; + } + + private boolean checkForDuplicate(String name){ + UpdateBaseFile(false); + for (String line : lines) { + if(line.contains(name)){ + return true; + } + } + return false; + } + + private void initFile(File file){ + try { + PrintStream fW = new PrintStream(file); + fW.println(file.getName()); + fW.println("{"); + fW.println("}"); + print("File Initialized"); + } catch (IOException e) { + print("An error occurred."); + e.printStackTrace(); + } + } + + private void rewriteFile(){ + try { + PrintStream fW = new PrintStream(easyBase); + for (String line : lines) { + try{ + fW.println(line); + } + catch (Exception e){ + e.printStackTrace(); + } + } + //print("File Rewritten"); + } + catch (Exception e){ + e.printStackTrace(); + } + UpdateBaseFile(false); + } + + public void createData(String name, Object data){ + UpdateBaseFile(false); + try{ + if(checkForDuplicate(name)){ + //print("Data already exists"); + //print(lines.toString()); + //editData("name", data); + return; + } + + if(data instanceof String){ + lines.add(2, "String " + name + " = " + (String) data); + rewriteFile(); + } + else if(data instanceof Byte){ + lines.add(2, "Byte " + name + " = " + (Byte) data); + rewriteFile(); + } + else if(data instanceof Short){ + lines.add(2, "Short " + name + " = " + (Short) data); + rewriteFile(); + } + else if(data instanceof Integer){ + lines.add(2, "Integer " + name + " = " + (Integer) data); + rewriteFile(); + } + else if(data instanceof Long){ + lines.add(2, "Long " + name + " = " + (Long) data); + rewriteFile(); + } + else if(data instanceof Float){ + lines.add(2, "Float " + name + " = " + (Float) data); + rewriteFile(); + } + else if(data instanceof Double){ + lines.add(2, "Double " + name + " = " + (Double) data); + rewriteFile(); + } + else if(data instanceof Boolean){ + lines.add(2, "Boolean " + name + " = " + (Boolean) data); + rewriteFile(); + } + else if(data instanceof ArrayList){ + StringBuilder builder = new StringBuilder(); + + if(((ArrayList) data).get(0) instanceof String){ + if(((ArrayList) data).size() != 0){ + for (String listdata : (ArrayList) data) { + String temp = listdata.replace(' ', '|'); + builder.append(temp + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else if(((ArrayList) data).get(0) instanceof Byte){ + if(((ArrayList) data).size() != 0){ + for (Byte listdata : (ArrayList) data) { + builder.append(listdata + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else if(((ArrayList) data).get(0) instanceof Short){ + if(((ArrayList) data).size() != 0){ + for (Short listdata : (ArrayList) data) { + builder.append(listdata + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else if(((ArrayList) data).get(0) instanceof Integer){ + if(((ArrayList) data).size() != 0){ + for (Integer listdata : (ArrayList) data) { + builder.append(listdata + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else if(((ArrayList) data).get(0) instanceof Long){ + if(((ArrayList) data).size() != 0){ + for (Long listdata : (ArrayList) data) { + builder.append(listdata + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else if(((ArrayList) data).get(0) instanceof Float){ + if(((ArrayList) data).size() != 0){ + for (Float listdata : (ArrayList) data) { + builder.append(listdata + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else if(((ArrayList) data).get(0) instanceof Double){ + if(((ArrayList) data).size() != 0){ + for (Double listdata : (ArrayList) data) { + builder.append(listdata + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else if(((ArrayList) data).get(0) instanceof Boolean){ + if(((ArrayList) data).size() != 0){ + for (Boolean listdata : (ArrayList) data) { + builder.append(listdata + " "); + } + } + + lines.add(2, "ArrayList " + name + " = " + "{ " + builder.toString() + "}"); + rewriteFile(); + } + else{ + print("Datatype is not allowd in ArrayList"); + UpdateBaseFile(false); + return; + } + } + else{ + print("Datatype ist not valid"); + } + } + catch (Exception e){ + e.printStackTrace(); + } + UpdateBaseFile(false); + } + + public Object getData(String name){ + UpdateBaseFile(false); + for (String line : lines) { + String[] lineStrings = line.split(" "); + ArrayList lineArrayList = new ArrayList(); + for(String s : lineStrings){ + if(!line.equals("")){ + lineArrayList.add(s); + } + } + //print(lines.toString()); + if(lineArrayList.size() > 1){ + if(lineArrayList.get(1).equals(name)){ + if(lineArrayList.get(0).equals("String")){ + StringBuilder string = new StringBuilder(); + for (String word : lineArrayList){ + if(lineArrayList.size() == 4){ + return lineArrayList.get(3); + } + else if(lineArrayList.indexOf(word) >= 3){ + string.append(word + " "); + } + } + return string.toString(); + } + else if(lineArrayList.get(0).equals("Byte")){ + return Byte.parseByte(lineArrayList.get(lineArrayList.size() - 1)); + } + else if(lineArrayList.get(0).equals("Short")){ + return Short.parseShort(lineArrayList.get(lineArrayList.size() - 1)); + } + else if(lineArrayList.get(0).equals("Integer")){ + return Integer.parseInt(lineArrayList.get(lineArrayList.size() - 1)); + } + else if(lineArrayList.get(0).equals("Long")){ + return Long.parseLong(lineArrayList.get(lineArrayList.size() - 1)); + } + else if(lineArrayList.get(0).equals("Float")){ + return Float.parseFloat(lineArrayList.get(lineArrayList.size() - 1)); + } + else if(lineArrayList.get(0).equals("Double")){ + return Double.parseDouble(lineArrayList.get(lineArrayList.size() - 1)); + } + else if(lineArrayList.get(0).equals("Boolean")){ + return Boolean.parseBoolean(lineArrayList.get(lineArrayList.size() - 1)); + } + else{ + print(easyBase.getName() + ": " + "Filetype not Found!"); + return null; + } + } + else if(lineArrayList.get(0).startsWith("ArrayList") && lineArrayList.get(2).equals(name)){ + int startIntex = lineArrayList.indexOf("{"); + int endIntex = lineArrayList.indexOf("}"); + ArrayList arrayVars = new ArrayList(); + for (String i : lineArrayList) { + int currentIndex = lineArrayList.indexOf(i); + if(currentIndex < endIntex && currentIndex > startIntex){ + arrayVars.add(currentIndex); + } + } + ArrayList output = new ArrayList(); + for (Integer i : arrayVars) { + if(lineArrayList.get(1).contains("")){ + String temp = lineArrayList.get(i).replace('|', ' '); + output.add(temp); + } + else if(lineArrayList.get(1).contains("")){ + output.add(Byte.parseByte(lineArrayList.get(i))); + } + else if(lineArrayList.get(1).contains("")){ + output.add(Short.parseShort(lineArrayList.get(i))); + } + else if(lineArrayList.get(1).contains("")){ + output.add(Integer.parseInt(lineArrayList.get(i))); + } + else if(lineArrayList.get(1).contains("")){ + output.add(Long.parseLong(lineArrayList.get(i))); + } + else if(lineArrayList.get(1).contains("")){ + output.add(Float.parseFloat(lineArrayList.get(i))); + } + else if(lineArrayList.get(1).contains("")){ + output.add(Double.parseDouble(lineArrayList.get(i))); + } + else if(lineArrayList.get(1).contains("")){ + output.add(Boolean.parseBoolean(lineArrayList.get(i))); + } + } + + + + return output; + } + + } + + } + return null; + } + + public void editData(String name, Object data){ + for (String line : lines) { + String[] lineStrings = line.split(" "); + ArrayList lineArrayList = new ArrayList(); + for(String s : lineStrings){ + lineArrayList.add(s); + } + if(lineArrayList.size() > 1){ + if(lineArrayList.get(1).equals(name)){ + if(lineArrayList.get(0).equals("String")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Byte")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Short")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Integer")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Long")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Float")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Double")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Boolean")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else{ + print(easyBase.getName() + ": " + "Filetype not Found!"); + } + UpdateBaseFile(false); + } + else if(lineArrayList.get(0).startsWith("ArrayList") && lineArrayList.get(2).equals(name)){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + createData(name, data); + rewriteFile(); + UpdateBaseFile(false); + return; + + } + } + } + } + + public void deleteData(String name){ + UpdateBaseFile(false); + for (String line : lines) { + String[] lineStrings = line.split(" "); + ArrayList lineArrayList = new ArrayList(); + for(String s : lineStrings){ + lineArrayList.add(s); + } + if(lineArrayList.size() > 1){ + if(lineArrayList.get(1).equals(name)){ + if(lineArrayList.get(0).equals("String")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Byte")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Short")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Integer")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Long")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Float")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Double")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else if(lineArrayList.get(0).equals("Boolean")){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + } + else{ + print(easyBase.getName() + ": " + "Filetype not Found!"); + } + } + else if(lineArrayList.get(0).startsWith("ArrayList") && lineArrayList.get(2).equals(name)){ + lines.remove(line); + rewriteFile(); + UpdateBaseFile(false); + return; + + } + } + } + UpdateBaseFile(false); + } + + public void arrayAdd(String name, Object data){ + UpdateBaseFile(false); + if(data instanceof String){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((String) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Byte){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((Byte) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Short){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((Short) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Integer){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((Integer) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Long){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((Long) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Float){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((Float) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Double){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((Double) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Boolean){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.add((Boolean) data); + editData(name, tempList); + rewriteFile(); + } + UpdateBaseFile(false); + } + + public void arrayRemove(String name, Object data){ + UpdateBaseFile(false); + if(data instanceof String){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((String) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Byte){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Byte) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Short){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Short) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Integer){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Integer) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Long){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Long) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Float){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Float) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Double){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Double) data); + editData(name, tempList); + rewriteFile(); + } + else if(data instanceof Boolean){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Boolean) data); + editData(name, tempList); + rewriteFile(); + } + UpdateBaseFile(false); + } + + public int arrayIndexOf(String name, Object data){ + UpdateBaseFile(false); + if(data instanceof String){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + return tempList.indexOf((String) data); + } + else if(data instanceof Byte){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Byte) data); + return tempList.indexOf((Byte) data); + } + else if(data instanceof Short){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Short) data); + return tempList.indexOf((Short) data); + } + else if(data instanceof Integer){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Integer) data); + return tempList.indexOf((Integer) data); + } + else if(data instanceof Long){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Long) data); + return tempList.indexOf((Long) data); + } + else if(data instanceof Float){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Float) data); + return tempList.indexOf((Float) data); + } + else if(data instanceof Double){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Double) data); + return tempList.indexOf((Double) data); + } + else if(data instanceof Boolean){ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + tempList.remove((Boolean) data); + return tempList.indexOf((Boolean) data); + } + else{ + print("Object was not found in Array"); + return 0; + } + } + + public int arraySize(String name){ + UpdateBaseFile(false); + try{ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + return tempList.size(); + } + catch (Exception e){ + e.printStackTrace(); + } + print("Index not found in Array"); + return 0; + } + + public Object arrayGet(String name, int i){ + UpdateBaseFile(false); + try{ + ArrayList tempList = new ArrayList(); + tempList = (ArrayList) getData(name); + return tempList.get(i); + } + catch (Exception e){ + e.printStackTrace(); + } + print("Index not found in Array"); + return null; + } + + public ArrayList getAll(){ + UpdateBaseFile(false); + ArrayList names = new ArrayList(); + for (String str: lines) { + if(!(str.endsWith(".esb")) && !str.equals("{") && !str.equals("}")){ + if(str.startsWith("ArrayList")){ + String[] strings = str.split(" "); + names.add(strings[2]); + } + else{ + String[] strings = str.split(" "); + names.add(strings[1]); + } + } + } + ArrayList returnList = new ArrayList(); + for (String str : names) { + returnList.add(getData(str)); + } + + return returnList; + } + + private void print(String message){ + Integer tempInt = easyBase.getName().indexOf("."); + System.out.println(easyBase.getName().substring(0, tempInt) + ": " + message); + } +} diff --git a/src/main/java/de/sailehd/support/FileClient.java b/src/main/java/de/sailehd/support/FileClient.java new file mode 100644 index 0000000..e89584b --- /dev/null +++ b/src/main/java/de/sailehd/support/FileClient.java @@ -0,0 +1,21 @@ +package de.sailehd.support; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; + +public class FileClient { + public ArrayList ls(String path){ + ArrayList list = new ArrayList(); + File folder = new File(path); + File[] listOfFiles = folder.listFiles(); + + for (File file : listOfFiles) { + if (file.isFile()) { + list.add(file.getName()); + } + } + return list; + } +} diff --git a/src/main/java/de/sailehd/support/FileManager.java b/src/main/java/de/sailehd/support/FileManager.java new file mode 100644 index 0000000..60cf769 --- /dev/null +++ b/src/main/java/de/sailehd/support/FileManager.java @@ -0,0 +1,109 @@ +package de.sailehd.support; + +import java.io.*; +import java.util.ArrayList; + +public class FileManager { + + public static boolean moveFileToDirectory(File sourceFile, String targetPath) { + File tDir = new File(targetPath); + if (tDir.exists()) { + String newFilePath = targetPath+File.separator+sourceFile.getName(); + File movedFile = new File(newFilePath); + if (movedFile.exists()) + movedFile.delete(); + return sourceFile.renameTo(new File(newFilePath)); + } else { + Debug.log("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist"); + return false; + } + } + + public static ArrayList GetFiles(File directory, String[] types){ + ArrayList tempFiles = new ArrayList(); + + for(String type : types){ + for (int i = 0; i < directory.listFiles().length; i++) { + if (directory.listFiles()[i].isDirectory()) { + for (File file: GetFiles(directory.listFiles()[i], types)) { + if(file.getName().endsWith("." + type)){ + tempFiles.add(file); + } + } + } + else if(directory.listFiles()[i].isFile()){ + if(directory.listFiles()[i].getName().endsWith("." + type)){ + tempFiles.add(directory.listFiles()[i]); + } + } + + } + } + return tempFiles; + } + + public static void copyFileUsingStream(File source, File dest) throws IOException { + InputStream is = null; + OutputStream os = null; + try { + is = new FileInputStream(source); + os = new FileOutputStream(dest); + byte[] buffer = new byte[1024]; + int length; + while ((length = is.read(buffer)) > 0) { + os.write(buffer, 0, length); + } + } finally { + is.close(); + os.close(); + } + } + + public static void combineAudioFiles(String audioFilesFolder, String outputFile, String[] fileformats) throws IOException { + File folder = new File(audioFilesFolder); + ArrayList files = new ArrayList(GetFiles(folder,fileformats)); + Debug.log(TextColor.YELLOW + "File Merge Start" + TextColor.RESET); + + FileInputStream tempstream = null; + SequenceInputStream sistream = null; + + try { + FileWriter myWriter = new FileWriter("tracks.txt"); + for (File file : files) { + String tempfile = file.getAbsolutePath(); + tempstream = new FileInputStream(tempfile); + sistream = new SequenceInputStream(tempstream, sistream); + Debug.log(TextColor.BLACK_BOLD + "File = " + TextColor.RESET + TextColor.BLUE_BOLD_BRIGHT + file.getName() + TextColor.RESET); + myWriter.write(file.getName() + "\n"); + } + myWriter.close(); + System.out.println("Successfully wrote to the trackFile."); + } + catch(Exception e){ + System.out.println("An error occurred."); + e.printStackTrace(); + System.exit(1); + } + + FileOutputStream fostream = new FileOutputStream(outputFile);//destinationfile + //Debug.log("Stream done"); + try { + Debug.log(TextColor.YELLOW + "Writing" + TextColor.RESET); + int temp; + while( ( temp = sistream.read() ) != -1) + { + fostream.write(temp); + } + } + catch (Exception e){ + + } + + //Debug.log("Closing Streams"); + fostream.close(); + sistream.close(); + tempstream.close(); + // Debug.log("Streams Closed"); + Debug.log(TextColor.GREEN + "Done" + TextColor.RESET); + } +} diff --git a/src/main/java/de/sailehd/support/Key.java b/src/main/java/de/sailehd/support/Key.java new file mode 100644 index 0000000..5c07d56 --- /dev/null +++ b/src/main/java/de/sailehd/support/Key.java @@ -0,0 +1,29 @@ +package de.sailehd.support; + +import java.awt.*; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; + +public class Key extends KeyAdapter{ + public static void type(String str) throws AWTException { + Robot robot = new Robot(); + for(char ch:str.toCharArray()){ + if(Character.isUpperCase(ch)){ + robot.keyPress(KeyEvent.VK_SHIFT); + robot.keyPress((int)ch); + robot.keyRelease((int)ch); + robot.keyRelease(KeyEvent.VK_SHIFT); + }else{ + char upCh = Character.toUpperCase(ch); + robot.keyPress((int)upCh); + robot.keyRelease((int)upCh); + } + } + } + + public static void press(int code){ + + } + + +} diff --git a/src/main/java/de/sailehd/support/ProcessBar.java b/src/main/java/de/sailehd/support/ProcessBar.java new file mode 100644 index 0000000..033aa54 --- /dev/null +++ b/src/main/java/de/sailehd/support/ProcessBar.java @@ -0,0 +1,119 @@ +package de.sailehd.support; + +import org.apache.commons.lang3.Range; +import org.apache.commons.lang3.time.StopWatch; + +public class ProcessBar { + + private int length; + private int steps; + private int localIndex = 0; + private boolean stopper = false; + StopWatch watch = new StopWatch(); + + public ProcessBar(int length){ + watch.start(); + this.length = length; + if(length < 100){ + return; + } + this.steps = length / 100; + } + + + public void update(Integer index, String extraInfo){ + if(index == length){ + watch.stop(); + } + build(index, extraInfo); + } + + + private void build(Integer index, String extraInfo){ + StringBuilder result = new StringBuilder(); + + for (int i = 1; i <= 100 ; i++) { + result.append(" "); + } + + if(index % steps == 0){ + localIndex++; + } + for (int i = 0; i < index; i++) { + if(i % steps == 0 && i != 0){ + result.replace(localIndex - 1,localIndex, "■"); + for (int j = 0; j < localIndex - 1; j++) { + result.replace(j, j + 1, "■"); + } + } + } + + result.insert(0, "0%"); + result.append("100%"); + + + if((watch.getTime() / 1000) < 60){ + result.append("\nPercent-Done:" + localIndex + "%" + " | Time:" + watch.getTime() / 1000 + "sec"); + if(watch.getTime() > 1000 && localIndex != 0){ + Integer timeRemaining = Math.toIntExact(((watch.getTime() / 1000) / localIndex) * 100); + + if(timeRemaining < 60){ + result.append(" | Time-Remaining:" + timeRemaining + "sec"); + } + else if(timeRemaining > 60 && timeRemaining < 3600){ + result.append(" | Time-Remaining:" + timeRemaining / 60 + "min" + timeRemaining % 60 + "sec"); + } + else{ + result.append(" | Time-Remaining:" + (timeRemaining /60) / 60 + "h " + (timeRemaining /60) % 60 + "min " + (timeRemaining % 60) % 60 + "sec"); + } + + } + } + else if((watch.getTime() / 1000) > 60 && (watch.getTime() / 1000) < 3600){ + result.append("\nPercent-Done:" + localIndex + "%" + " | Time:" + (watch.getTime() / 1000) / 60 + "min " + (watch.getTime() / 1000) % 60 + "sec"); + if(watch.getTime() > 1000 && localIndex != 0){ + Integer timeRemaining = Math.toIntExact(((watch.getTime() / 1000) / localIndex) * 100); + + if(timeRemaining < 60){ + result.append(" | Time-Remaining:" + timeRemaining + "sec"); + } + else if(timeRemaining > 60 && timeRemaining < 3600){ + result.append(" | Time-Remaining:" + timeRemaining / 60 + "min" + timeRemaining % 60 + "sec"); + } + else{ + result.append(" | Time-Remaining:" + (timeRemaining /60) / 60 + "h " + (timeRemaining /60) % 60 + "min " + (timeRemaining % 60) % 60 + "sec"); + } + + } + } + else{ + int time = Math.toIntExact(watch.getTime() / 1000); + + result.append("\nPercent-Done:" + localIndex + "%" + " | Time:" + (time /60) / 60 + "h " + (time /60) % 60 + "min " + (time % 60) % 60 + "sec"); + + if(watch.getTime() > 1000 && localIndex != 0){ + Integer timeRemaining = Math.toIntExact(((watch.getTime() / 1000) / localIndex) * 100); + + if(timeRemaining < 60){ + result.append(" | Time-Remaining" + timeRemaining + "sec"); + } + else if(timeRemaining > 60 && timeRemaining < 3600){ + result.append(" | Time-Remaining" + timeRemaining / 60 + "min" + timeRemaining % 60 + "sec"); + } + else{ + result.append(" | Time-Remaining" + (timeRemaining /60) / 60 + "h " + (timeRemaining /60) % 60 + "min " + (timeRemaining % 60) % 60 + "sec"); + } + + } + + } + result.append(" | Index:" + index); + if(extraInfo != null){ + result.append(" | " + extraInfo); + } + Debug.clear(); + Debug.log(result.toString()); + + } + +} diff --git a/src/main/java/de/sailehd/support/Random.java b/src/main/java/de/sailehd/support/Random.java new file mode 100644 index 0000000..6db8c55 --- /dev/null +++ b/src/main/java/de/sailehd/support/Random.java @@ -0,0 +1,33 @@ +package de.sailehd.support; + +import org.apache.commons.lang3.RandomStringUtils; + +public class Random { + public static int Range(int min, int max){ + return (int) ((Math.random() * (max - min)) + min); + } + + public static float Range(float min, float max){ + return (float) ((Math.random() * (max - min)) + min); + } + + public static double Range(double min, double max){ + return (double) ((Math.random() * (max - min)) + min); + } + + public static long Range(long min, long max){ + return (long) ((Math.random() * (max - min)) + min); + } + + public static short Range(short min, short max){ + return (short) ((Math.random() * (max - min)) + min); + } + + public static String String(int length, boolean useLetters, boolean useNumbers) { + String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); + + return generatedString; + } + + +} diff --git a/src/main/java/de/sailehd/support/SFTPClient.java b/src/main/java/de/sailehd/support/SFTPClient.java new file mode 100644 index 0000000..8d07856 --- /dev/null +++ b/src/main/java/de/sailehd/support/SFTPClient.java @@ -0,0 +1,149 @@ +package de.sailehd.support; + +import com.jcraft.jsch.*; + +import java.util.ArrayList; +import java.util.Vector; + +public class SFTPClient { + + private Session session = null; + + private String username = ""; + private String password = ""; + private String host = ""; + private String knownHostsPath = ""; + + private Integer port = 22; + + public SFTPClient(String knownHostsPath, String host, String username, String password, Integer port){ + this.knownHostsPath = knownHostsPath; + this.host = host; + this.port = port; + this.username = username; + this.password = password; + } + + public void connect() throws JSchException { + JSch jsch = new JSch(); + + // Uncomment the line below if the FTP server requires certificate + jsch.setKnownHosts(knownHostsPath); + // Uncomment the two lines below if the FTP server requires password + session = jsch.getSession(username, host, port); + session.setPassword(password); + session.setConfig("StrictHostKeyChecking", "no"); + session.connect(); + Debug.log("Connected to Server"); + } + + public void upload(String source, String destination) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + sftpChannel.put(source, destination); + sftpChannel.exit(); + } + + public void download(String source, String destination) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + sftpChannel.get(source, destination); + sftpChannel.exit(); + } + + public void rename(String oldPath, String newPath) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + sftpChannel.rename(oldPath, newPath); + sftpChannel.exit(); + } + + public void remove(String path) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + sftpChannel.rm(path); + sftpChannel.exit(); + } + + public void mkdir(String path) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + sftpChannel.mkdir(path); + sftpChannel.exit(); + } + + public void chmod(Integer permission ,String path) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + sftpChannel.chmod(permission, path); + sftpChannel.exit(); + } + + public ArrayList ls(String path) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + Vector filelist = sftpChannel.ls(path); + ArrayList list = new ArrayList(); + for (int i = 0; i < filelist.size(); i++) { + list.add(filelist.get(i).toString()); + } + ArrayList list2 = new ArrayList(); + for (String files : list) { + String[] filesParts = files.split(" "); + for (String i: filesParts) { + if(i == filesParts[filesParts.length - 1] && !(i.contains("..")) && !(i.equals("."))){ + list2.add(i); + } + } + + } + + sftpChannel.exit(); + return list2; + } + + public ArrayList lsWithPath(String path) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + Vector filelist = sftpChannel.ls(path); + ArrayList list = new ArrayList(); + for (int i = 0; i < filelist.size(); i++) { + list.add(filelist.get(i).toString()); + } + ArrayList list2 = new ArrayList(); + for (String files : list) { + String[] filesParts = files.split(" "); + for (String i: filesParts) { + if(i == filesParts[filesParts.length - 1] && !(i.contains("..")) && !(i.equals("."))){ + list2.add(path + i); + } + } + + } + + sftpChannel.exit(); + return list2; + } + + public void copy(Integer permission ,String path) throws JSchException, SftpException { + Channel channel = session.openChannel("sftp"); + channel.connect(); + ChannelSftp sftpChannel = (ChannelSftp) channel; + sftpChannel.exit(); + } + + + public void disconnect() { + if (session != null) { + session.disconnect(); + } + } +} diff --git a/src/main/java/de/sailehd/support/SManager.java b/src/main/java/de/sailehd/support/SManager.java new file mode 100644 index 0000000..deb7876 --- /dev/null +++ b/src/main/java/de/sailehd/support/SManager.java @@ -0,0 +1,44 @@ +package de.sailehd.support; + +public class SManager { + public static double similarity(String source, String target){ + String longer = source, shorter = target; + if (source.length() < target.length()) { + longer = target; shorter = source; + } + int longerLength = longer.length(); + if (longerLength == 0) { return 1.0;} + + return (longerLength - editDistance(longer, shorter)) / (double) longerLength; + } + + private static int editDistance(String source, String target) { + source = source.toLowerCase(); + target = target.toLowerCase(); + + int[] costs = new int[target.length() + 1]; + for (int i = 0; i <= source.length(); i++) { + int lastValue = i; + for (int j = 0; j <= target.length(); j++) { + if (i == 0) + costs[j] = j; + else { + if (j > 0) { + int newValue = costs[j - 1]; + if (source.charAt(i - 1) != target.charAt(j - 1)) + newValue = Math.min(Math.min(newValue, lastValue), + costs[j]) + 1; + costs[j - 1] = lastValue; + lastValue = newValue; + } + } + } + if (i > 0) + costs[target.length()] = lastValue; + } + return costs[target.length()]; + } + +} + + diff --git a/src/main/java/de/sailehd/support/TextColor.java b/src/main/java/de/sailehd/support/TextColor.java new file mode 100644 index 0000000..f4e0721 --- /dev/null +++ b/src/main/java/de/sailehd/support/TextColor.java @@ -0,0 +1,76 @@ +package de.sailehd.support; + +public class TextColor { + // Reset + public static final String RESET = "\u001B[0m"; + + // Regular Colors + public static final String ABLACK = "\u001B[30m"; + public static final String RED = "\u001B[31m"; + public static final String GREEN = "\u001B[32m"; + public static final String YELLOW = "\u001B[33m"; + public static final String BLUE = "\u001B[34m"; + public static final String PURPLE = "\u001B[35m"; + public static final String CYAN = "\u001B[36m"; + public static final String WHITE = "\u001B[37m"; + + // Bold + public static final String BLACK_BOLD = "\033[1;30m"; // BLACK + public static final String RED_BOLD = "\033[1;31m"; // RED + public static final String GREEN_BOLD = "\033[1;32m"; // GREEN + public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW + public static final String BLUE_BOLD = "\033[1;34m"; // BLUE + public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE + public static final String CYAN_BOLD = "\033[1;36m"; // CYAN + public static final String WHITE_BOLD = "\033[1;37m"; // WHITE + + // Underline + public static final String BLACK_UNDERLINED = "\033[4;30m"; // BLACK + public static final String RED_UNDERLINED = "\033[4;31m"; // RED + public static final String GREEN_UNDERLINED = "\033[4;32m"; // GREEN + public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW + public static final String BLUE_UNDERLINED = "\033[4;34m"; // BLUE + public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE + public static final String CYAN_UNDERLINED = "\033[4;36m"; // CYAN + public static final String WHITE_UNDERLINED = "\033[4;37m"; // WHITE + + // Background + public static final String BLACK_BACKGROUND = "\033[40m"; // BLACK + public static final String RED_BACKGROUND = "\033[41m"; // RED + public static final String GREEN_BACKGROUND = "\033[42m"; // GREEN + public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW + public static final String BLUE_BACKGROUND = "\033[44m"; // BLUE + public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE + public static final String CYAN_BACKGROUND = "\033[46m"; // CYAN + public static final String WHITE_BACKGROUND = "\033[47m"; // WHITE + + // High Intensity + public static final String BLACK_BRIGHT = "\033[0;90m"; // BLACK + public static final String RED_BRIGHT = "\033[0;91m"; // RED + public static final String GREEN_BRIGHT = "\033[0;92m"; // GREEN + public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW + public static final String BLUE_BRIGHT = "\033[0;94m"; // BLUE + public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE + public static final String CYAN_BRIGHT = "\033[0;96m"; // CYAN + public static final String WHITE_BRIGHT = "\033[0;97m"; // WHITE + + // Bold High Intensity + public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK + public static final String RED_BOLD_BRIGHT = "\033[1;91m"; // RED + public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN + public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW + public static final String BLUE_BOLD_BRIGHT = "\033[1;94m"; // BLUE + public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE + public static final String CYAN_BOLD_BRIGHT = "\033[1;96m"; // CYAN + public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE + + // High Intensity backgrounds + public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK + public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED + public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN + public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW + public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE + public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE + public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m"; // CYAN + public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m"; // WHITE +}