diff --git a/.gitignore b/.gitignore index ab7caeed..3619eec2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,7 @@ **/AP-TEST-SERVER/ /autoplug /test -.gradle -**/build/ -!src/**/build/ - -# Ignore Gradle GUI config -gradle-app.setting - -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) -!gradle-wrapper.jar - -# Avoid ignore Gradle wrappper properties -!gradle-wrapper.properties - -# Cache of project -.gradletasknamecache +/target/ # IDEA **/.idea/ diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..7967f30d Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..ff0085e1 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip \ No newline at end of file diff --git a/.run/AutoPlug-Client [build shadowJar -x test].run.xml b/.run/AutoPlug-Client [build shadowJar -x test].run.xml deleted file mode 100644 index 743cf7b0..00000000 --- a/.run/AutoPlug-Client [build shadowJar -x test].run.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.run/build-run-jar.run.xml b/.run/build-run-jar.run.xml deleted file mode 100644 index 500f8efa..00000000 --- a/.run/build-run-jar.run.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.run/build.run.xml b/.run/build.run.xml new file mode 100644 index 00000000..b9d3f6de --- /dev/null +++ b/.run/build.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/.run/gradle-build-example.run.xml b/.run/gradle-build-example.run.xml deleted file mode 100644 index 4b4cc7b9..00000000 --- a/.run/gradle-build-example.run.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - true - true - false - false - - - \ No newline at end of file diff --git a/.run/run-jar.run.xml b/.run/run-jar.run.xml deleted file mode 100644 index 3c53e260..00000000 --- a/.run/run-jar.run.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/README.md b/README.md index d0a993d0..d59c7857 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,8 @@ By commiting to an issue with the bounty tag you agree to these terms. Details: - Written in [Java](https://java.com/), with [JDK 8](https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html), inside of [IntelliJ IDEA](https://www.jetbrains.com/idea/) -- Built with [Gradle](https://gradle.org/), command: `./gradlew build shadowJar` (Linux and UNIX systems) or `.\gradlew.bat build shadowJar` (Windows systems) from project root directory to create the `./AP-TEST-SERVER/AutoPlug-Client.jar` +- Built with [1JPM](https://github.com/Osiris-Team/1JPM), command: `java ./src/main/java/JPM.java` +(if you want to directly run it too append `andRun` at the end). ## Libraries diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 2881e6b7..00000000 --- a/build.gradle +++ /dev/null @@ -1,158 +0,0 @@ -plugins { - id 'com.github.johnrengelman.shadow' version '8.1.1' - id 'java' -} - -/* - * Copyright (c) 2024 Osiris-Team. - * All rights reserved. - * - * This software is copyrighted work, licensed under the terms - * of the MIT-License. Consult the "LICENSE" file for details. - */ - -// Important for AutoPlugs Self-Updater! -// Also take a look at the generateAutoplugProperties task where these properties get turned into the actual autoplug.properties file. -group = 'com.osiris.autoplug.client' -version = '8.2.2' -description = 'Responsible for all the main actions.' - -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 -} - -// Important for AutoPlugs Self-Updater! -// Generates a autoplug.properties file inside the generated jar file, with the stuff inside -task generateAutoplugProperties { - def propertiesFile = file("$buildDir/resources/main/autoplug.properties") - outputs.file(propertiesFile) - - doLast { - propertiesFile.text = """# Properties - |# Generated on: ${new Date()} - |java.version=${System.properties['java.version']} - |version=${project.version} - |main-class=com.osiris.autoplug.client.Main - |slf4j.version=2.0.13 - |name=${rootProject.name} - |project.build.sourceEncoding=UTF-8 - |id=0 - |installation-path=./${rootProject.name}.jar - |""".stripMargin() - } -} - -// Make this jar executable -shadowJar { - archiveFileName = "${rootProject.name}.jar" - // Output into directory for manual tests - destinationDirectory = file('AP-TEST-SERVER') - dependsOn generateAutoplugProperties -} - -// Configure jar task -jar { - from sourceSets.main.output - archiveFileName = "original-${rootProject.name}.jar" - manifest { - attributes('Main-Class': 'com.osiris.autoplug.client.Main') - } - dependsOn generateAutoplugProperties -} - -repositories { - mavenCentral() - maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } - maven { url 'https://jitpack.io' } - maven { url 'https://repo.panda-lang.org/' } - maven { url 'https://repo.codemc.io/repository/maven-public/' } -} - -dependencies { - // To make sure transitive dependencies do not include an older version. This must stay at the top. - // See settings.gradle for converged/enforced transitive dependencies - implementation 'net.java.dev.jna:jna:5.14.0' // Also used in jsch https://github.com/mwiede/jsch/blob/master/pom.xml - implementation 'net.java.dev.jna:jna-platform:5.14.0' - // Also used in jsch https://github.com/mwiede/jsch/blob/master/pom.xml - implementation 'commons-io:commons-io:2.16.1' - // Also used in jsch https://github.com/mwiede/jsch/blob/master/pom.xml - implementation 'com.github.Osiris-Team:jansi:2.4.5' - implementation 'org.jetbrains:annotations:23.0.0' - implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.9.23' // Also used in okhttp - implementation 'org.jetbrains.kotlin:kotlin-stdlib-common:1.9.23' // Also used in okhttp - // To remove this annoying warning, add the dependency below: - // SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". - // SLF4J: Defaulting to no-operation (NOP) logger implementation - // SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details - // https://mvnrepository.com/artifact/org.slf4j/slf4j-simple - // https://stackoverflow.com/questions/7421612/slf4j-failed-to-load-class-org-slf4j-impl-staticloggerbinder - implementation 'org.slf4j:slf4j-api:2.0.13' - implementation 'org.slf4j:slf4j-nop:2.0.13' - - // https://github.com/Osiris-Team/AutoPlug-Core - implementation 'com.github.Osiris-Team:jlib:18.0' - - implementation 'com.github.Osiris-Team:Dyml:9.8.3' - implementation 'com.github.Osiris-Team:Better-Thread:5.1.2' - implementation 'com.github.Osiris-Team:Better-Layout:1.4.0' - implementation 'com.github.Osiris-Team:jProcesses2:2.1.9' - - // For getting hardware info - implementation 'com.github.oshi:oshi-core:6.6.1' - - // Needed for working with .zip and .jar files, in the Plugins-Updater - implementation 'net.lingala.zip4j:zip4j:2.11.3' - - // Needed for working with .tar.gz files, in the Java-Updater - implementation 'org.rauschig:jarchivelib:1.2.0' - - implementation 'org.jetbrains:annotations:13.0' - - // Extra terminal stuff - implementation 'org.jline:jline-reader:3.20.0' - - // Requests - // https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp - implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.14' - - implementation 'commons-lang:commons-lang:2.6' - - // https://mvnrepository.com/artifact/commons-net/commons-net - implementation 'commons-net:commons-net:3.9.0' - - // https://mvnrepository.com/artifact/com.jcraft/jsch - implementation 'com.github.mwiede:jsch:0.2.17' - - // Quartz Core - implementation 'org.quartz-scheduler:quartz:2.3.2' - - implementation 'org.tomlj:tomlj:1.0.0' - - // For GUI of tray icon - implementation 'com.formdev:flatlaf:2.2' - - testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2' - - // For Server Updater - implementation 'me.hsgamer:mc-server-updater-lib:3.4.0' - - // For SSH - // Before updating this dependency, make sure there are no vulnerabilities - // https://mvnrepository.com/artifact/org.apache.sshd/sshd-core - implementation 'org.apache.sshd:sshd-core:2.13.0' -} - -// Responsible for running all tests before building. -test { - useJUnitPlatform() -} - -tasks.withType(JavaCompile) { - options.encoding = 'UTF-8' -} - -// Ensure compileTestJava depends on generateAutoplugProperties -compileTestJava { - dependsOn generateAutoplugProperties -} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index e962cde8..00000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,15 +0,0 @@ -# -# Copyright (c) 2024 Osiris-Team. -# All rights reserved. -# -# This software is copyrighted work, licensed under the terms -# of the MIT-License. Consult the "LICENSE" file for details. -# - -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100755 index 7a531414..00000000 --- a/gradlew +++ /dev/null @@ -1,241 +0,0 @@ -#!/bin/sh - -# -# Copyright (c) 2024 Osiris-Team. -# All rights reserved. -# -# This software is copyrighted work, licensed under the terms -# of the MIT-License. Consult the "LICENSE" file for details. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - 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 -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# 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"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100755 index 93e3f59f..00000000 --- a/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 00000000..708460f9 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,206 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version @@project.version@@ +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. >&2 +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. >&2 +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. >&2 +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. >&2 +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/@@project.version@@/maven-wrapper-@@project.version@@.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/@@project.version@@/maven-wrapper-@@project.version@@.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..d35201e8 --- /dev/null +++ b/pom.xml @@ -0,0 +1,397 @@ + + + 4.0.0 + com.osiris.autoplug.client + AutoPlug-Client + 8.2.3 + + UTF-8 + 8 + 8.2.3 + com.osiris.autoplug.client.Main + 2.0.13 + AutoPlug-Client + 0 + ./AutoPlug-Client.jar + + + + osssonatypeorg + https://oss.sonatype.org/content/repositories/snapshots + + + jitpackio + https://jitpack.io + + + repopandalangorg + https://repo.panda-lang.org/ + + + repocodemcio + https://repo.codemc.io/repository/maven-public/ + + + + + + net.java.dev.jna + jna + 5.14.0 + compile + + + net.java.dev.jna + jna-platform + 5.14.0 + compile + + + commons-io + commons-io + 2.16.1 + compile + + + com.github.Osiris-Team + jansi + 2.4.5 + compile + + + org.jetbrains.kotlin + kotlin-stdlib + 1.9.23 + compile + + + org.jetbrains.kotlin + kotlin-stdlib-common + 1.9.23 + compile + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + 1.8.21 + compile + + + org.slf4j + slf4j-api + 2.0.13 + compile + + + org.jline + jline + 3.26.1 + compile + + + org.jetbrains + annotations + 23.0.0 + compile + + + + + + net.java.dev.jna + jna + 5.14.0 + compile + + + net.java.dev.jna + jna-platform + 5.14.0 + compile + + + commons-io + commons-io + 2.16.1 + compile + + + com.github.Osiris-Team + jansi + 2.4.5 + compile + + + org.jetbrains.kotlin + kotlin-stdlib + 1.9.23 + compile + + + org.jetbrains.kotlin + kotlin-stdlib-common + 1.9.23 + compile + + + org.slf4j + slf4j-api + 2.0.13 + compile + + + org.slf4j + slf4j-nop + 2.0.13 + compile + + + com.github.Osiris-Team + jlib + 18.4 + compile + + + com.github.Osiris-Team + Dyml + 9.8.3 + compile + + + com.github.Osiris-Team + Better-Thread + 5.1.2 + compile + + + com.github.Osiris-Team + Better-Layout + 1.4.0 + compile + + + com.github.Osiris-Team + jProcesses2 + 2.1.9 + compile + + + com.github.oshi + oshi-core + 6.6.1 + compile + + + net.lingala.zip4j + zip4j + 2.11.3 + compile + + + org.rauschig + jarchivelib + 1.2.0 + compile + + + org.jetbrains + annotations + 23.0.0 + compile + + + org.jline + jline-reader + 3.20.0 + compile + + + commons-lang + commons-lang + 2.6 + compile + + + commons-net + commons-net + 3.9.0 + compile + + + com.github.mwiede + jsch + 0.2.17 + compile + + + org.quartz-scheduler + quartz + 2.3.2 + compile + + + org.tomlj + tomlj + 1.0.0 + compile + + + com.formdev + flatlaf + 2.2 + compile + + + me.hsgamer + mc-server-updater-lib + 3.4.0 + compile + + + org.apache.sshd + sshd-core + 2.13.0 + compile + + + org.junit.jupiter + junit-jupiter + 5.9.2 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 8 + 8 + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + + + com.osiris.autoplug.client.Main + true + + + AutoPlug-Client-original + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.3.0 + + + jar-with-dependencies + + + + com.osiris.autoplug.client.Main + + + AutoPlug-Client + false + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.1 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.0.0 + + + resource-bundles + package + + test-resource-bundle + + + none + false + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.3.0 + + + enforce + + enforce + + + + + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + generate-properties + generate-resources + + write-project-properties + + + ${project.build.outputDirectory}/autoplug.properties + + + + + + + + + src/main/resources + true + + + + diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index edb9f4f1..00000000 --- a/settings.gradle +++ /dev/null @@ -1,43 +0,0 @@ -rootProject.name = 'AutoPlug-Client' - -buildscript { - repositories { - mavenCentral() - gradlePluginPortal() - } - dependencies { - classpath 'org.kordamp.gradle:enforcer-gradle-plugin:0.13.0' - } -} -apply plugin: 'org.kordamp.gradle.enforcer' - -/* - Fails when the same dependency exists more than once, with different versions or if it's a SNAPSHOT. - If that is the case specify/add that dependency in (transitive dependency) above, - with a version that is compatible with all other dependencies, or - try to find an alternative dependency with similar functionality. - Note that having this check is crucial to avoid runtime "method not found" errors that will lead to crashes - and/or unexpected behaviour. - */ -enforce { - rule(enforcer.rules.DependencyConvergence) { r -> - r.enabled - r.enforcerLevel - r.phases - r.failOnDynamicVersions - r.failOnChangingVersions - r.failOnNonReproducibleResolution - r.activateDependencyLocking - r.deactivateDependencyLocking - } - rule(enforcer.rules.ForceDependencies) { r -> - r.dependencies.add('net.java.dev.jna:jna:5.14.0') - r.dependencies.add('net.java.dev.jna:jna-platform:5.14.0') - r.dependencies.add('commons-io:commons-io:2.16.1') - r.dependencies.add('com.github.Osiris-Team:jansi:2.4.5') - r.dependencies.add('org.jetbrains:annotations:23.0.0') - r.dependencies.add('org.jetbrains.kotlin:kotlin-stdlib:1.9.23') - r.dependencies.add('org.jetbrains.kotlin:kotlin-stdlib-common:1.9.23') - r.dependencies.add('org.slf4j:slf4j-api:2.0.13') - } -} diff --git a/src/main/java/JPM.java b/src/main/java/JPM.java new file mode 100644 index 00000000..a66ce7a4 --- /dev/null +++ b/src/main/java/JPM.java @@ -0,0 +1,807 @@ +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.*; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +class ThisProject extends JPM.Project { + + public ThisProject(List args) { + // Override default configurations + this.groupId = "com.osiris.autoplug.client"; + this.artifactId = "AutoPlug-Client"; + this.version = "8.2.3"; + this.mainClass = "com.osiris.autoplug.client.Main"; + this.jarName = "AutoPlug-Client-original.jar"; + this.fatJarName = "AutoPlug-Client.jar"; + this.javaVersionSource = "8"; + this.javaVersionTarget = "8"; + + // Add repositories + addRepository("https://oss.sonatype.org/content/repositories/snapshots"); + addRepository("https://jitpack.io"); + addRepository("https://repo.panda-lang.org/"); + addRepository("https://repo.codemc.io/repository/maven-public/"); + + // Force dependencies + forceImplementation("net.java.dev.jna:jna:5.14.0"); + forceImplementation("net.java.dev.jna:jna-platform:5.14.0"); + forceImplementation("commons-io:commons-io:2.16.1"); + forceImplementation("com.github.Osiris-Team:jansi:2.4.5"); + forceImplementation("org.jetbrains.kotlin:kotlin-stdlib:1.9.23"); + forceImplementation("org.jetbrains.kotlin:kotlin-stdlib-common:1.9.23"); + forceImplementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.21"); + forceImplementation("org.slf4j:slf4j-api:2.0.13"); + + forceImplementation("org.jline:jline:3.26.1"); + forceImplementation("org.jetbrains:annotations:23.0.0"); + + // Add dependencies + implementation("net.java.dev.jna:jna:5.14.0"); + implementation("net.java.dev.jna:jna-platform:5.14.0"); + implementation("commons-io:commons-io:2.16.1"); + implementation("com.github.Osiris-Team:jansi:2.4.5"); + implementation("org.jetbrains.kotlin:kotlin-stdlib:1.9.23"); + implementation("org.jetbrains.kotlin:kotlin-stdlib-common:1.9.23"); + implementation("org.slf4j:slf4j-api:2.0.13"); + implementation("org.slf4j:slf4j-nop:2.0.13"); + implementation("com.github.Osiris-Team:jlib:18.4"); + implementation("com.github.Osiris-Team:Dyml:9.8.3"); + implementation("com.github.Osiris-Team:Better-Thread:5.1.2"); + implementation("com.github.Osiris-Team:Better-Layout:1.4.0"); + implementation("com.github.Osiris-Team:jProcesses2:2.1.9"); + implementation("com.github.oshi:oshi-core:6.6.1"); + implementation("net.lingala.zip4j:zip4j:2.11.3"); + implementation("org.rauschig:jarchivelib:1.2.0"); + implementation("org.jetbrains:annotations:23.0.0"); + implementation("org.jline:jline-reader:3.20.0"); + implementation("commons-lang:commons-lang:2.6"); + implementation("commons-net:commons-net:3.9.0"); + implementation("com.github.mwiede:jsch:0.2.17"); + implementation("org.quartz-scheduler:quartz:2.3.2"); + implementation("org.tomlj:tomlj:1.0.0"); + implementation("com.formdev:flatlaf:2.2"); + implementation("me.hsgamer:mc-server-updater-lib:3.4.0"); + implementation("org.apache.sshd:sshd-core:2.13.0"); + + testImplementation("org.junit.jupiter:junit-jupiter:5.9.2"); + + // Add custom plugins + plugins.add(new AutoPlugPropertiesPlugin()); + } + + public static void main(String[] _args) throws Exception { + List args = Arrays.asList(_args); + File cwd = new File(System.getProperty("user.dir")); + ThisProject project = new ThisProject(args); + project.generatePom(); + JPM.executeMaven("clean", "package", "-DskipTests"); + + File testServerDir = new File(cwd+"/AP-TEST-SERVER"); + testServerDir.mkdirs(); + String jarName = project.artifactId+".jar"; + Files.copy(new File(cwd+"/target/"+jarName).toPath(), + new File(testServerDir+"/"+jarName).toPath(), + StandardCopyOption.REPLACE_EXISTING); + if(args.contains("andRun")){ + Process result = new ProcessBuilder("java", "-jar", jarName).directory(testServerDir).inheritIO().start(); + } + } + + /** + * Custom plugin for generating autoplug.properties. + * Important for AutoPlugs Self-Updater! + * Generates a autoplug.properties file inside the generated jar file, with the stuff inside + * Also take look at where these properties get turned into the actual autoplug.properties file. + */ + private static class AutoPlugPropertiesPlugin extends JPM.Plugin { + public AutoPlugPropertiesPlugin() { + super("org.codehaus.mojo", "properties-maven-plugin", "1.0.0"); + onBeforeToXML((project, pom) -> { + JPM.Execution execution = new JPM.Execution("generate-properties", "generate-resources"); + execution.addGoal("write-project-properties"); + execution.addConfiguration("outputFile", "${project.build.outputDirectory}/autoplug.properties"); + addExecution(execution); + + pom.put("properties java.version", project.javaVersionSource); + pom.put("properties version", project.version); + // The main class or this jars entry point. Is optional. + pom.put("properties main-class", project.mainClass); + pom.put("properties slf4j.version", "2.0.13"); + pom.put("properties name", project.artifactId); + pom.put("properties project.build.sourceEncoding", "UTF-8"); + pom.put("properties id", "0"); + // The installation path, is where this jar should be installed to + // You can enter a directory path in linux and windows format. + // A dot "." like above means in the current jars working directory aka System.getProperty("user.dir"). + // Some examples: + // ./installDir/MyApp.jar or C:/HelloDir/MyApp.jar + pom.put("properties installation-path", "./"+project.artifactId+".jar"); + }); + } + } +} + +class ThirdPartyPlugins extends JPM.Plugins{ + // Add third party plugins below, find them here: https://github.com/topics/1jpm-plugin?o=desc&s=updated + // (If you want to develop a plugin take a look at "JPM.Clean" class further below to get started) +} + +// 1JPM version 2.1.1 by Osiris-Team: https://github.com/Osiris-Team/1JPM +// To upgrade JPM, replace the JPM class below with its newer version +public class JPM { + public static final List plugins = new ArrayList<>(); + private static final String mavenVersion = "3.9.8"; + private static final String mavenWrapperVersion = "3.3.2"; + private static final String mavenWrapperScriptUrlBase = "https://raw.githubusercontent.com/apache/maven-wrapper/maven-wrapper-"+ mavenWrapperVersion +"/maven-wrapper-distribution/src/resources/"; + private static final String mavenWrapperJarUrl = "https://repo1.maven.org/maven2/org/apache/maven/wrapper/maven-wrapper/"+ mavenWrapperVersion +"/maven-wrapper-"+ mavenWrapperVersion +".jar"; + private static final String mavenWrapperPropsContent = "distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/"+ mavenVersion +"/apache-maven-"+ mavenVersion +"-bin.zip"; + + public static void main(String[] args) throws Exception { + ThisProject.main(args); + } + + public static void executeMaven(String... args) throws IOException, InterruptedException { + boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win"); + + ProcessBuilder p = new ProcessBuilder(); + List finalArgs = new ArrayList<>(); + File userDir = new File(System.getProperty("user.dir")); + File mavenWrapperFile = new File(userDir, "mvnw" + (isWindows ? ".cmd" : "")); + File propertiesFile = new File(userDir, ".mvn/wrapper/maven-wrapper.properties"); + File mavenWrapperJarFile = new File(userDir, ".mvn/wrapper/maven-wrapper.jar"); + + if (!mavenWrapperFile.exists()) { + downloadMavenWrapper(mavenWrapperFile); + if(!isWindows) mavenWrapperFile.setExecutable(true); + } + if(!mavenWrapperJarFile.exists()) downloadMavenWrapperJar(mavenWrapperJarFile); + if (!propertiesFile.exists()) createMavenWrapperProperties(propertiesFile); + + finalArgs.add(mavenWrapperFile.getAbsolutePath()); + finalArgs.addAll(Arrays.asList(args)); + p.command(finalArgs); + p.inheritIO(); + System.out.print("Executing: "); + for (String arg : finalArgs) { + System.out.print(arg+" "); + } + System.out.println(); + Process result = p.start(); + result.waitFor(); + if(result.exitValue() != 0) + throw new RuntimeException("Maven ("+mavenWrapperFile.getName()+") finished with an error ("+result.exitValue()+"): "+mavenWrapperFile.getAbsolutePath()); + } + + private static void downloadMavenWrapper(File script) throws IOException { + String wrapperUrl = mavenWrapperScriptUrlBase + script.getName(); + + System.out.println("Downloading file from: " + wrapperUrl); + URL url = new URL(wrapperUrl); + script.getParentFile().mkdirs(); + Files.copy(url.openStream(), script.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + + private static void downloadMavenWrapperJar(File jar) throws IOException { + String wrapperUrl = mavenWrapperJarUrl; + + System.out.println("Downloading file from: " + wrapperUrl); + URL url = new URL(wrapperUrl); + jar.getParentFile().mkdirs(); + Files.copy(url.openStream(), jar.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + + private static void createMavenWrapperProperties(File propertiesFile) throws IOException { + // Create the .mvn directory if it doesn't exist + File mvnDir = propertiesFile.getParentFile(); + if (!mvnDir.exists()) { + mvnDir.mkdirs(); + } + + // Write default properties content to the file + try (FileWriter writer = new FileWriter(propertiesFile)) { + writer.write(mavenWrapperPropsContent); + } + } + + // + // API and Models + // + + public static class Plugins { + } + + public static interface ConsumerWithException extends Serializable { + void accept(T t) throws Exception; + } + + public static class Dependency { + public String groupId; + public String artifactId; + public String version; + public String scope; + public List transitiveDependencies; + + public Dependency(String groupId, String artifactId, String version) { + this(groupId, artifactId, version, "compile", new ArrayList<>()); + } + + public Dependency(String groupId, String artifactId, String version, String scope) { + this(groupId, artifactId, version, scope, new ArrayList<>()); + } + + public Dependency(String groupId, String artifactId, String version, String scope, List transitiveDependencies) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + this.scope = scope; + this.transitiveDependencies = transitiveDependencies; + } + + @Override + public String toString() { + return groupId + ":" + artifactId + ":" + version + ":" + scope; + } + + public XML toXML(){ + XML xml = new XML("dependency"); + xml.put("groupId", groupId); + xml.put("artifactId", artifactId); + xml.put("version", version); + if (scope != null) { + xml.put("scope", scope); + } + return xml; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Dependency that = (Dependency) o; + return Objects.equals(groupId, that.groupId) && + Objects.equals(artifactId, that.artifactId) && + Objects.equals(version, that.version) && + Objects.equals(scope, that.scope); + } + + @Override + public int hashCode() { + return Objects.hash(groupId, artifactId, version, scope); + } + } + + public static class Repository{ + public String id; + public String url; + + public Repository(String id, String url) { + this.id = id; + this.url = url; + } + + public static Repository fromUrl(String url){ + String id = url.split("//")[1].split("/")[0].replace(".", "").replace("-", ""); + return new Repository(id, url); + } + + public XML toXML(){ + XML xml = new XML("repository"); + xml.put("id", id); + xml.put("url", url); + return xml; + } + } + + public static class XML { + private Document document; + private Element root; + + // Constructor initializes the XML document with a root element. + public XML(String rootName) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.newDocument(); + root = document.createElement(rootName); + document.appendChild(root); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } + } + + // Method to append another XML object to this XML document's root. + public XML add(XML otherXML) { + Node importedNode = document.importNode(otherXML.root, true); + root.appendChild(importedNode); + return this; + } + + // Method to append another XML object to a specific element in this XML document. + public XML add(String key, XML otherXML) { + Element parentElement = getOrCreateElement(key); + Node importedNode = document.importNode(otherXML.root, true); + parentElement.appendChild(importedNode); + return this; + } + + // Method to add a value to the XML document at the specified path. + public XML put(String key, String value) { + Element currentElement = getOrCreateElement(key); + if(value != null && !value.isEmpty()) + currentElement.setTextContent(value); + return this; + } + + // Method to add a comment to the XML document at the specified path. + public XML putComment(String key, String comment) { + Element currentElement = getOrCreateElement(key); + Node parentNode = currentElement.getParentNode(); + Node commentNode = document.createComment(comment); + + // Insert the comment before the specified element. + parentNode.insertBefore(commentNode, currentElement); + return this; + } + + public XML putAttributes(String key, String... attributes) { + if (attributes.length % 2 != 0) { + throw new IllegalArgumentException("Attributes must be in key-value pairs."); + } + + Element currentElement = getOrCreateElement(key); + + // Iterate over pairs of strings to set each attribute on the element. + for (int i = 0; i < attributes.length; i += 2) { + String attrName = attributes[i]; + String attrValue = attributes[i + 1]; + currentElement.setAttribute(attrName, attrValue); + } + return this; + } + + // Method to add attributes to an element in the XML document at the specified path. + public XML putAttributes(String key, Map attributes) { + Element currentElement = getOrCreateElement(key); + + // Set each attribute in the map on the element. + for (Map.Entry entry : attributes.entrySet()) { + currentElement.setAttribute(entry.getKey(), entry.getValue()); + } + return this; + } + + // Helper method to traverse or create elements based on a path. + private Element getOrCreateElement(String key) { + if (key == null || key.trim().isEmpty()) return root; + String[] path = key.split(" "); + Element currentElement = root; + + for (String nodeName : path) { + Element childElement = null; + NodeList children = currentElement.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(nodeName)) { + childElement = (Element) child; + break; + } + } + + if (childElement == null) { + childElement = document.createElement(nodeName); + currentElement.appendChild(childElement); + } + currentElement = childElement; + } + + return currentElement; + } + + // Method to convert the XML document to a pretty-printed string. + public String toString() { + try { + javax.xml.transform.TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance(); + javax.xml.transform.Transformer transformer = transformerFactory.newTransformer(); + + // Enable pretty printing with indentation and newlines. + transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // Adjust indent space as needed + + javax.xml.transform.dom.DOMSource domSource = new javax.xml.transform.dom.DOMSource(document); + java.io.StringWriter writer = new java.io.StringWriter(); + javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(writer); + transformer.transform(domSource, result); + + return writer.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void main(String[] args) { + // Example usage of the XML class. + XML xml = new XML("root"); + xml.put("this is a key", "value"); + xml.put("this is another key", "another value"); + xml.putComment("this is another", "This is a comment for 'another'"); + Map atr = new HashMap<>(); + atr.put("attr1", "value1"); + atr.put("attr2", "value2"); + xml.putAttributes("this is a key", atr); + System.out.println(xml.toString()); + } + } + + public static class Plugin { + public List> beforeToXMLListeners = new CopyOnWriteArrayList<>(); + protected String groupId; + protected String artifactId; + protected String version; + + // Gets cleared after execute + protected Map configuration = new HashMap<>(); + // Gets cleared after execute + protected List executions = new ArrayList<>(); + // Gets cleared after execute + protected List dependencies = new ArrayList<>(); + + public Plugin(String groupId, String artifactId, String version) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + } + + public void addConfiguration(String key, String value) { + configuration.put(key, value); + } + + public void addExecution(Execution execution) { + executions.add(execution); + } + + public void addDependency(Dependency dependency) { + dependencies.add(dependency); + } + + public Plugin onBeforeToXML(BiConsumer code){ + beforeToXMLListeners.add(code); + return this; + } + + private void executeBeforeToXML(Project project, XML projectXML) { + for (BiConsumer code : beforeToXMLListeners) { + code.accept(project, projectXML); + } + } + + private void executeAfterToXML(Project project) { + configuration.clear(); + executions.clear(); + dependencies.clear(); + } + + + public XML toXML(Project project, XML projectXML) { + executeBeforeToXML(project, projectXML); + + // Create an XML object for the element + XML xml = new XML("plugin"); + xml.put("groupId", groupId); + xml.put("artifactId", artifactId); + xml.put("version", version); + + // Add elements if present + if (!configuration.isEmpty()) { + for (Map.Entry entry : configuration.entrySet()) { + xml.put("configuration " + entry.getKey(), entry.getValue()); + } + } + + // Add if not empty + if (!executions.isEmpty()) { + for (Execution execution : executions) { + xml.add("executions", execution.toXML()); + } + } + + // Add if not empty + if (!dependencies.isEmpty()) { + for (Dependency dependency : dependencies) { + xml.add("dependencies", dependency.toXML()); + } + } + + executeAfterToXML(project); + return xml; + } + } + + public static class Execution { + private String id; + private String phase; + private List goals; + private Map configuration; + + public Execution(String id, String phase) { + this.id = id; + this.phase = phase; + this.goals = new ArrayList<>(); + this.configuration = new HashMap<>(); + } + + public void addGoal(String goal) { + goals.add(goal); + } + + public void addConfiguration(String key, String value) { + configuration.put(key, value); + } + + public XML toXML() { + // Create an instance of XML with the root element + XML xml = new XML("execution"); + + // Add element + xml.put("id", id); + + // Add element if it is not null or empty + if (phase != null && !phase.isEmpty()) { + xml.put("phase", phase); + } + + // Add element if goals list is not empty + if (!goals.isEmpty()) { + xml.put("goals", ""); // Placeholder for element + for (String goal : goals) { + xml.put("goals goal", goal); + } + } + + // Add element if configuration map is not empty + if (!configuration.isEmpty()) { + xml.put("configuration", ""); // Placeholder for element + for (Map.Entry entry : configuration.entrySet()) { + xml.put("configuration " + entry.getKey(), entry.getValue()); + } + } + + // Return the XML configuration as a string + return xml; + } + } + + public static class Project { + protected String jarName = "output.jar"; + protected String fatJarName = "output-fat.jar"; + protected String mainClass = "com.example.Main"; + protected String groupId = "com.example"; + protected String artifactId = "project"; + protected String version = "1.0.0"; + protected String javaVersionSource = "8"; + protected String javaVersionTarget = "8"; + protected List repositories = new ArrayList<>(); + protected List dependenciesManaged = new ArrayList<>(); + protected List dependencies = new ArrayList<>(); + protected List plugins = new ArrayList<>(); + protected List compilerArgs = new ArrayList<>(); + + public void addRepository(String url){ + repositories.add(Repository.fromUrl(url)); + } + + public void testImplementation(String s){ + String[] split = s.split(":"); + if(split.length < 3) throw new RuntimeException("Does not contain all required details: "+s); + addDependency(split[0], split[1], split[2]).scope = "test"; + } + + public void implementation(String s){ + String[] split = s.split(":"); + if(split.length < 3) throw new RuntimeException("Does not contain all required details: "+s); + addDependency(split[0], split[1], split[2]); + } + + public Dependency addDependency(String groupId, String artifactId, String version) { + Dependency dep = new Dependency(groupId, artifactId, version); + dependencies.add(dep); + return dep; + } + + public void forceImplementation(String s){ + String[] split = s.split(":"); + if(split.length < 3) throw new RuntimeException("Does not contain all required details: "+s); + forceDependency(split[0], split[1], split[2]); + } + + public void forceDependency(String groupId, String artifactId, String version) { + dependenciesManaged.add(new Dependency(groupId, artifactId, version)); + } + + public void addCompilerArg(String arg) { + compilerArgs.add(arg); + } + + public void generatePom() throws IOException { + // Create a new XML document with the root element + XML pom = new XML("project"); + pom.putComment("", "\n\n\n\nAUTO-GENERATED FILE, CHANGES SHOULD BE DONE IN ./JPM.java or ./src/main/java/JPM.java\n\n\n\n"); + pom.putAttributes("", + "xmlns", "http://maven.apache.org/POM/4.0.0", + "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", + "xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + ); + + // Add element + pom.put("modelVersion", "4.0.0"); + + // Add main project identifiers + pom.put("groupId", groupId); + pom.put("artifactId", artifactId); + pom.put("version", version); + + // Add element + pom.put("properties project.build.sourceEncoding", "UTF-8"); + + // Add if not empty + if (!repositories.isEmpty()) { + for (Repository rep : repositories) { + pom.add("repositories", rep.toXML()); + } + } + + // Add if there are managed dependencies + if (!dependenciesManaged.isEmpty()) { + for (Dependency dep : dependenciesManaged) { + pom.add("dependencyManagement dependencies", dep.toXML()); + } + } + + // Add if there are dependencies + if (!dependencies.isEmpty()) { + for (Dependency dep : dependencies) { + pom.add("dependencies", dep.toXML()); + } + } + + // Add section with plugins and resources + for (Plugin plugin : JPM.plugins) { + pom.add("build plugins", plugin.toXML(this, pom)); + } + for (Plugin plugin : plugins) { + pom.add("build plugins", plugin.toXML(this, pom)); + } + + // Add resources with a comment + pom.putComment("build resources", "Sometimes unfiltered resources cause unexpected behaviour, thus enable filtering."); + pom.put("build resources resource directory", "src/main/resources"); + pom.put("build resources resource filtering", "true"); + + // Write to pom.xml + File pomFile = new File(System.getProperty("user.dir") + "/pom.xml"); + try (FileWriter writer = new FileWriter(pomFile)) { + writer.write(pom.toString()); + } + System.out.println("Generated pom.xml file."); + } + } + + static { + plugins.add(CompilerPlugin.get); + } + public static class CompilerPlugin extends Plugin { + public static CompilerPlugin get = new CompilerPlugin(); + public CompilerPlugin() { + super("org.apache.maven.plugins", "maven-compiler-plugin", "3.8.1"); + onBeforeToXML((project, pom) -> { + addConfiguration("source", project.javaVersionSource); + addConfiguration("target", project.javaVersionTarget); + + // Add compiler arguments from the project + if (!project.compilerArgs.isEmpty()) { + for (String arg : project.compilerArgs) { + addConfiguration("compilerArgs arg", arg); + } + } + }); + } + } + + static { + plugins.add(JarPlugin.get); + } + public static class JarPlugin extends Plugin { + public static JarPlugin get = new JarPlugin(); + public JarPlugin() { + super("org.apache.maven.plugins", "maven-jar-plugin", "3.2.0"); + onBeforeToXML((project, pom) -> { + addConfiguration("archive manifest addClasspath", "true"); + addConfiguration("archive manifest mainClass", project.mainClass); + addConfiguration("finalName", project.jarName.replace(".jar", "")); + }); + } + } + + static { + plugins.add(AssemblyPlugin.get); + } + public static class AssemblyPlugin extends Plugin { + public static AssemblyPlugin get = new AssemblyPlugin(); + public AssemblyPlugin() { + super("org.apache.maven.plugins", "maven-assembly-plugin", "3.3.0"); + onBeforeToXML((project, pom) -> { + addConfiguration("descriptorRefs descriptorRef", "jar-with-dependencies"); + addConfiguration("archive manifest mainClass", project.mainClass); + addConfiguration("finalName", project.fatJarName.replace(".jar", "")); + addConfiguration("appendAssemblyId", "false"); + + Execution execution = new Execution("make-assembly", "package"); + execution.addGoal("single"); + addExecution(execution); + }); + } + } + + static { + plugins.add(SourcePlugin.get); + } + public static class SourcePlugin extends Plugin { + public static SourcePlugin get = new SourcePlugin(); + public SourcePlugin() { + super("org.apache.maven.plugins", "maven-source-plugin", "3.2.1"); + onBeforeToXML((project, pom) -> { + Execution execution = new Execution("attach-sources", null); + addExecution(execution); + execution.addGoal("jar"); + }); + } + } + + static { + plugins.add(JavadocPlugin.get); + } + public static class JavadocPlugin extends Plugin { + public static JavadocPlugin get = new JavadocPlugin(); + public JavadocPlugin() { + super("org.apache.maven.plugins", "maven-javadoc-plugin", "3.0.0"); + onBeforeToXML((project, pom) -> { + Execution execution = new Execution("resource-bundles", "package"); + addExecution(execution); + execution.addGoal("resource-bundle"); + execution.addGoal("test-resource-bundle"); + execution.addConfiguration("doclint", "none"); + execution.addConfiguration("detectOfflineLinks", "false"); + }); + } + } + + static { + plugins.add(EnforcerPlugin.get); + } + public static class EnforcerPlugin extends Plugin { + public static EnforcerPlugin get = new EnforcerPlugin(); + public EnforcerPlugin() { + super("org.apache.maven.plugins", "maven-enforcer-plugin", "3.3.0"); + onBeforeToXML((project, pom) -> { + Execution execution = new Execution("enforce", null); + addExecution(execution); + execution.addGoal("enforce"); + execution.addConfiguration("rules dependencyConvergence", ""); + }); + } + } +} + + diff --git a/src/main/java/com/osiris/autoplug/client/Main.java b/src/main/java/com/osiris/autoplug/client/Main.java index 7c458494..8f8e7d74 100644 --- a/src/main/java/com/osiris/autoplug/client/Main.java +++ b/src/main/java/com/osiris/autoplug/client/Main.java @@ -137,6 +137,7 @@ public static void main(String[] _args) { AL.start(autoplug_label.asString(), debug.asBoolean(), // must be a new Yaml and not the LoggerConfig GD.AP_LATEST_LOG, + true, force_ansi.asBoolean() ); AL.mirrorSystemStreams(GD.FILE_OUT, GD.FILE_ERR_OUT); diff --git a/src/test/java/com/osiris/autoplug/client/UtilsTest.java b/src/test/java/com/osiris/autoplug/client/UtilsTest.java index 738f7d02..84878de3 100644 --- a/src/test/java/com/osiris/autoplug/client/UtilsTest.java +++ b/src/test/java/com/osiris/autoplug/client/UtilsTest.java @@ -60,6 +60,6 @@ public static void initDefaults() throws IOException { public static void initLogger() { File logFile = new File(System.getProperty("user.dir") + "/logs/latest.log"); logFile.getParentFile().mkdirs(); - new AL().start("AL", true, logFile, false); + new AL().start("AL", true, logFile, false, false); } }