commit 9f085af24ae3ff1967f7eef87bb131c0d4c056c8 Author: Walter Oggioni Date: Sat Sep 25 20:34:20 2021 +0200 initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..00a51af --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b6985c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..6cf98a9 --- /dev/null +++ b/build.gradle @@ -0,0 +1,100 @@ +plugins { + id 'java-gradle-plugin' + id 'net.woggioni.gradle.lombok' apply false + id 'maven-publish' +} + +allprojects { + apply plugin: 'java-library' + apply plugin: 'net.woggioni.gradle.lombok' + + repositories { + maven { + url = woggioniMavenRepositoryUrl + } + mavenCentral() + } + + group = "net.woggioni.gradle" + + lombok { + version = getProperty('version.lombok') + } + + dependencies { + add("testImplementation", create(group: "org.junit.jupiter", name:"junit-jupiter-api", version: project["version.junitJupiter"])) + add("testRuntimeOnly", create(group: "org.junit.jupiter", name: "junit-jupiter-engine", version: project["version.junitJupiter"])) + add("testImplementation", gradleTestKit()) + } + + tasks.named("test", Test) { + useJUnitPlatform() + } +} + +version = getProperty("version.executableJar") + +configurations { + embedded + compileOnly.extendsFrom(embedded) +} + +dependencies { + embedded project(path: "common", configuration: "archives") +} + +Provider copyLauncher = tasks.register("copyLauncher", Copy) { + from(project("launcher").tasks.named("tar").map {it.outputs }) + into(new File(project.buildDir, "resources/main/META-INF")) +} + +tasks.named("processResources") { + inputs.files(copyLauncher) +} + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +jar { + manifest { + attributes "version" : archiveVersion.get() + } + from { + configurations.named('embedded').map { + it.collect { + it.isDirectory() ? it : zipTree(it) + } + } + } +} + +gradlePlugin { + plugins { + create("ExecutableJarPlugin") { + id = "net.woggioni.gradle.executable-jar" + implementationClass = "net.woggioni.gradle.executable.jar.ExecutableJarPlugin" + } + } +} + +publishing { + repositories { + maven { + url = woggioniMavenRepositoryUrl + } + } + publications { + maven(MavenPublication) { + from(components["java"]) + } + } +} + +wrapper { + gradleVersion = "7.2" + distributionType = Wrapper.DistributionType.ALL +} + + diff --git a/common/build.gradle b/common/build.gradle new file mode 100644 index 0000000..2cf9fef --- /dev/null +++ b/common/build.gradle @@ -0,0 +1,10 @@ +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +jar { + manifest { + attributes "Automatic-Module-Name" : "net.woggioni.executable.jar" + } +} \ No newline at end of file diff --git a/common/src/main/java/net/woggioni/executable/jar/Common.java b/common/src/main/java/net/woggioni/executable/jar/Common.java new file mode 100644 index 0000000..e72ad8f --- /dev/null +++ b/common/src/main/java/net/woggioni/executable/jar/Common.java @@ -0,0 +1,117 @@ +package net.woggioni.executable.jar; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.util.AbstractMap; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import lombok.SneakyThrows; +import java.io.IOException; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class Common { + final private static char[] hexArray = "0123456789ABCDEF".toCharArray(); + + public static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + + @SneakyThrows + public static byte[] computeSHA256Digest(Supplier streamSupplier) { + byte[] buffer = new byte[Constants.BUFFER_SIZE]; + MessageDigest md = MessageDigest.getInstance("SHA-256"); + return computeDigest(streamSupplier, md, buffer); + } + + @SneakyThrows + public static byte[] computeDigest(Supplier streamSupplier, MessageDigest md, byte[] buffer) { + try(InputStream stream = new DigestInputStream(streamSupplier.get(), md)) { + while(stream.read(buffer) >= 0) {} + } + return md.digest(); + } + + @SneakyThrows + public static void computeSizeAndCrc32( + ZipEntry zipEntry, + InputStream inputStream, + byte[] buffer) { + CRC32 crc32 = new CRC32(); + long sz = 0L; + while (true) { + int read = inputStream.read(buffer); + if (read < 0) break; + sz += read; + crc32.update(buffer, 0, read); + } + zipEntry.setSize(sz); + zipEntry.setCompressedSize(sz); + zipEntry.setCrc(crc32.getValue()); + } + + @SneakyThrows + public static void write2Stream(InputStream inputStream, OutputStream os, + byte[] buffer) { + while (true) { + int read = inputStream.read(buffer); + if (read < 0) break; + os.write(buffer, 0, read); + } + } + + public static void write2Stream(InputStream inputStream, OutputStream os) { + write2Stream(inputStream, os, new byte[Constants.BUFFER_SIZE]); + } + + public static Optional> splitExtension(String fileName) { + int index = fileName.lastIndexOf('.'); + if (index == -1) { + return Optional.empty(); + } else { + return Optional.of( + new AbstractMap.SimpleEntry<>(fileName.substring(0, index), fileName.substring(index))); + } + } + + /** + * Helper method to create an {@link InputStream} from a file without having to catch the possibly + * thrown {@link IOException}, use {@link FileInputStream#FileInputStream(File)} if you need to catch it. + * @param file the {@link File} to be opened + * @return an open {@link InputStream} instance reading from the file + */ + @SneakyThrows + public static InputStream read(File file, boolean buffered) { + InputStream result = new FileInputStream(file); + return buffered ? new BufferedInputStream(result) : result; + } + + /** + * Helper method to create an {@link OutputStream} from a file without having to catch the possibly + * thrown {@link IOException}, use {@link FileOutputStream#FileOutputStream(File)} if you need to catch it. + * @param file the {@link File} to be opened + * @return an open {@link OutputStream} instance writing to the file + */ + @SneakyThrows + public static OutputStream write(File file, boolean buffered) { + OutputStream result = new FileOutputStream(file); + return buffered ? new BufferedOutputStream(result) : result; + } +} diff --git a/common/src/main/java/net/woggioni/executable/jar/Constants.java b/common/src/main/java/net/woggioni/executable/jar/Constants.java new file mode 100644 index 0000000..e770c8d --- /dev/null +++ b/common/src/main/java/net/woggioni/executable/jar/Constants.java @@ -0,0 +1,31 @@ +package net.woggioni.executable.jar; + +import java.util.Calendar; +import java.util.GregorianCalendar; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class Constants { + public static final String LIBRARIES_FOLDER = "LIB-INF"; + public static final String METADATA_FOLDER = "META-INF"; + public static final int BUFFER_SIZE = 0x10000; + public static final String DEFAULT_LAUNCHER = "net.woggioni.executable.jar.Launcher"; + public static final String AGENT_LAUNCHER = "net.woggioni.executable.jar.JavaAgentLauncher"; + public static final String JAVA_AGENTS_FILE = METADATA_FOLDER + "/javaAgents.properties"; + + public static class ManifestAttributes { + public static final String MAIN_MODULE = "Executable-Jar-Main-Module"; + public static final String MAIN_CLASS = "Executable-Jar-Main-Class"; + public static final String ENTRY_HASH = "SHA-256-Digest"; + } + + /** + * This value is used as a default file timestamp for all the zip entries when + * AbstractArchiveTask.isPreserveFileTimestamps + * is true; its value is taken from Gradle's ZipCopyAction + * for the reasons outlined there. + */ + public static final long ZIP_ENTRIES_DEFAULT_TIMESTAMP = + new GregorianCalendar(1980, Calendar.FEBRUARY, 1, 0, 0, 0).getTimeInMillis(); +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..ca927bb --- /dev/null +++ b/gradle.properties @@ -0,0 +1,7 @@ +woggioniMavenRepositoryUrl=https://mvn.woggioni.net/ + +version.executableJar=0.1 +version.lombok=1.18.16 +version.xclassloader=1.0 +version.junitJupiter=5.7.2 +version.junitPlatform=1.7.0 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 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..a0f7639 --- /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.2-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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 "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /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/launcher/build.gradle b/launcher/build.gradle new file mode 100644 index 0000000..7aa130f --- /dev/null +++ b/launcher/build.gradle @@ -0,0 +1,62 @@ +import java.util.jar.Attributes + +plugins { + id "net.woggioni.gradle.multi-release-jar" +} + +ext.setProperty("jpms.module.name", "net.woggioni.executable.jar") + +configurations { + embedded + compileOnly.extendsFrom(embedded) +} + +dependencies { + embedded project(path: ":common", configuration: 'archives') + embedded group: "net.woggioni", name: "xclassloader", version: getProperty("version.xclassloader") +} + +java { + modularity.inferModulePath = true +} + +tasks.withType(JavaCompile).configureEach { + javaCompiler = javaToolchains.compilerFor { + languageVersion = JavaLanguageVersion.of(16) + } + options.forkOptions.jvmArgs << "--illegal-access=permit" +} + +jar { + manifest { + attributes([ + (Attributes.Name.SPECIFICATION_TITLE) : "executable-jar-launcher", + (Attributes.Name.SEALED) : true + ].collectEntries { + [it.key.toString(), it.value.toString()] + }) + } +} + +tasks.register("tar", Tar) { + archiveFileName = "${project.name}.tar" + from(project.tasks.named(JavaPlugin.JAR_TASK_NAME) + .flatMap(Jar.&getArchiveFile) + .map(RegularFile.&getAsFile) + .map(project.&zipTree)) + from(configurations.named('embedded').map { + it.collect { + it.isDirectory() ? it : zipTree(it) + } + }) { + exclude("**/module-info.class") + exclude("META-INF/MANIFEST.MF") + } +} + +tasks.named(JavaPlugin.COMPILE_JAVA_TASK_NAME, JavaCompile) { + doFirst { + String path = project(":common").extensions.getByType(JavaPluginExtension).sourceSets.named("main").get().output.asPath + options.compilerArgs.addAll(["--patch-module", "net.woggioni.executable.jar=$path"]) + } +} diff --git a/launcher/src/main/java/net/woggioni/executable/jar/JavaAgentLauncher.java b/launcher/src/main/java/net/woggioni/executable/jar/JavaAgentLauncher.java new file mode 100644 index 0000000..7460868 --- /dev/null +++ b/launcher/src/main/java/net/woggioni/executable/jar/JavaAgentLauncher.java @@ -0,0 +1,37 @@ +package net.woggioni.executable.jar; + +import java.io.InputStream; +import java.lang.instrument.Instrumentation; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.Enumeration; +import java.util.Map; +import java.util.Properties; +import lombok.SneakyThrows; + +class JavaAgentLauncher { + + @SneakyThrows + static void premain(String agentArguments, Instrumentation instrumentation) { + ClassLoader cl = JavaAgentLauncher.class.getClassLoader(); + Enumeration it = cl.getResources(Constants.JAVA_AGENTS_FILE); + while (it.hasMoreElements()) { + URL url = it.nextElement(); + Properties properties = new Properties(); + try (InputStream is = url.openStream()) { + properties.load(is); + } + for (Map.Entry entry : properties.entrySet()) { + String agentClassName = (String) entry.getKey(); + String agentArgs = (String) entry.getValue(); + Class agentClass = cl.loadClass(agentClassName); + Method premainMethod = agentClass.getMethod("premain", String.class, Instrumentation.class); + premainMethod.invoke(null, agentArgs, instrumentation); + } + } + } + + static void agentmain(String agentArguments, Instrumentation instrumentation) { + premain(agentArguments, instrumentation); + } +} \ No newline at end of file diff --git a/launcher/src/main/java/net/woggioni/executable/jar/Launcher.java b/launcher/src/main/java/net/woggioni/executable/jar/Launcher.java new file mode 100644 index 0000000..b77616c --- /dev/null +++ b/launcher/src/main/java/net/woggioni/executable/jar/Launcher.java @@ -0,0 +1,92 @@ +package net.woggioni.executable.jar; + +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URL; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import lombok.SneakyThrows; +import lombok.extern.java.Log; + + +@Log +public class Launcher { + + @SneakyThrows + private static URI findCurrentJar() { + String launcherClassName = Launcher.class.getName(); + URL url = Launcher.class.getClassLoader().getResource(launcherClassName.replace('.', '/') + ".class"); + if (url == null || !"jar".equals(url.getProtocol())) + throw new IllegalStateException(String.format("The class %s must be used inside a JAR file", launcherClassName)); + String path = url.getPath(); + return new URI(path.substring(0, path.indexOf('!'))); + } + + @SneakyThrows + public static void main(String[] args) { + URI currentJar = findCurrentJar(); + URL manifestResource = Launcher.class.getResource("/" + JarFile.MANIFEST_NAME); + if(Objects.isNull(manifestResource)) { + throw new RuntimeException("Launcher manifest not found"); + } + Manifest mf = new Manifest(); + try(InputStream is = manifestResource.openStream()) { + mf.read(is); + } + try(FileSystem fs = FileSystems.newFileSystem(Paths.get(currentJar), null)) { + Attributes mainAttributes = mf.getMainAttributes(); + + Collector, List> immutableListCollector = Collector.of( + ArrayList::new, + List::add, + (l1, l2) -> { l1.addAll(l2); return l1; }, + Collections::unmodifiableList); + List jarList = StreamSupport.stream(fs.getRootDirectories().spliterator(), false).flatMap(new Function>() { + @Override + @SneakyThrows + public Stream apply(Path path) { + return Files.list(path.resolve(Constants.LIBRARIES_FOLDER)) + .filter(Files::isRegularFile) + .filter(p -> p.getFileName().toString().endsWith(".jar")); + } + }).flatMap(new Function>() { + @Override + @SneakyThrows + public Stream apply(Path path) { + return StreamSupport.stream(FileSystems.newFileSystem(path, null).getRootDirectories().spliterator(), false); + } + }).collect(immutableListCollector); + + String mainClassName = mainAttributes.getValue(Constants.ManifestAttributes.MAIN_CLASS); + String mainModuleName = mainAttributes.getValue(Constants.ManifestAttributes.MAIN_MODULE); + Class mainClass = MainClassLoader.loadMainClass(jarList, mainModuleName, mainClassName); + try { + Method mainMethod = mainClass.getMethod("main", String[].class); + Class returnType = mainMethod.getReturnType(); + if (mainMethod.getReturnType() != Void.TYPE) { + throw new IllegalArgumentException(String.format("Main method in class '%s' " + + "has wrong return type, expected '%s', found '%s' instead", mainClass, Void.class.getName(), returnType)); + } + mainMethod.invoke(null, (Object) args); + } catch (NoSuchMethodException nsme) { + throw new IllegalArgumentException(String.format("No valid main method found in class '%s'", mainClass), nsme); + } + } + } +} diff --git a/launcher/src/main/java/net/woggioni/executable/jar/MainClassLoader.java b/launcher/src/main/java/net/woggioni/executable/jar/MainClassLoader.java new file mode 100644 index 0000000..215bc56 --- /dev/null +++ b/launcher/src/main/java/net/woggioni/executable/jar/MainClassLoader.java @@ -0,0 +1,13 @@ +package net.woggioni.executable.jar; + +import java.nio.file.Path; +import lombok.SneakyThrows; + + +class MainClassLoader { + @SneakyThrows + static Class loadMainClass(Iterable roots, String mainModuleName, String mainClassName) { + ClassLoader pathClassLoader = new net.woggioni.xclassloader.PathClassLoader(roots); + return pathClassLoader.loadClass(mainClassName); + } +} diff --git a/launcher/src/main/java/net/woggioni/executable/jar/PathClassLoader.java b/launcher/src/main/java/net/woggioni/executable/jar/PathClassLoader.java new file mode 100644 index 0000000..61282fc --- /dev/null +++ b/launcher/src/main/java/net/woggioni/executable/jar/PathClassLoader.java @@ -0,0 +1,190 @@ +package net.woggioni.executable.jar; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import lombok.SneakyThrows; + +/** + * A classloader that loads classes from a {@link Path} instance + */ +public final class PathClassLoader extends ClassLoader { + + private final Iterable paths; + + static { + registerAsParallelCapable(); + } + + public PathClassLoader(Path ...path) { + this(Arrays.asList(path), null); + } + + public PathClassLoader(Iterable paths) { + this(paths, null); + } + + public PathClassLoader(Iterable paths, ClassLoader parent) { + super(parent); + this.paths = paths; + } + + @Override + @SneakyThrows + protected Class findClass(String name) { + String resource = name.replace('.', '/').concat(".class"); + for(Path path : paths) { + Path classPath = path.resolve(resource); + if (Files.exists(classPath)) { + byte[] byteCode = Files.readAllBytes(classPath); + return defineClass(name, byteCode, 0, byteCode.length); + } + } + throw new ClassNotFoundException(name); + } + + @Override + @SneakyThrows + protected URL findResource(String name) { + for(Path path : paths) { + Path resolved = path.resolve(name); + if (Files.exists(resolved)) { + return toURL(resolved); + } + } + return null; + } + + @Override + protected Enumeration findResources(final String name) throws IOException { + final List resources = new ArrayList<>(1); + for(Path path : paths) { + Files.walkFileTree(path, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (!name.isEmpty()) { + this.addIfMatches(resources, file); + } + return super.visitFile(file, attrs); + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + if (!name.isEmpty() || path.equals(dir)) { + this.addIfMatches(resources, dir); + } + return super.preVisitDirectory(dir, attrs); + } + + void addIfMatches(List resources, Path file) throws IOException { + if (path.relativize(file).toString().equals(name)) { + resources.add(toURL(file)); + } + } + }); + } + return Collections.enumeration(resources); + } + + private static URL toURL(Path path) throws IOException { + return new URL(null, path.toUri().toString(), PathURLStreamHandler.INSTANCE); + } + + private static final class PathURLConnection extends URLConnection { + + private final Path path; + + PathURLConnection(URL url, Path path) { + super(url); + this.path = path; + } + + @Override + public void connect() {} + + @Override + public long getContentLengthLong() { + try { + return Files.size(this.path); + } catch (IOException e) { + throw new RuntimeException("could not get size of: " + this.path, e); + } + } + + @Override + public InputStream getInputStream() throws IOException { + return Files.newInputStream(this.path); + } + + @Override + public OutputStream getOutputStream() throws IOException { + return Files.newOutputStream(this.path); + } + + @Override + @SneakyThrows + public String getContentType() { + return Files.probeContentType(this.path); + } + + @Override + @SneakyThrows + public long getLastModified() { + BasicFileAttributes attributes = Files.readAttributes(this.path, BasicFileAttributes.class); + return attributes.lastModifiedTime().toMillis(); + } + } + + @NoArgsConstructor(access = AccessLevel.PRIVATE) + private static final class PathURLStreamHandler extends URLStreamHandler { + + static final URLStreamHandler INSTANCE = new PathURLStreamHandler(); + + @Override + @SneakyThrows + protected URLConnection openConnection(URL url) { + List stack = new ArrayList<>(); + URL currentURL = url; + while(true) { + String file = currentURL.getFile(); + int exclamationMark = file.lastIndexOf('!'); + if(exclamationMark != -1) { + stack.add(file.substring(exclamationMark + 1)); + currentURL = new URL(file.substring(0, exclamationMark)); + } else { + stack.add(file); + break; + } + } + + Path path; + FileSystem fs = FileSystems.getDefault(); + while(true) { + String pathString = stack.remove(stack.size() - 1); + path = fs.getPath(pathString); + if(stack.isEmpty()) break; + else { + fs = FileSystems.newFileSystem(path, null); + } + } + return new PathURLConnection(url, path); + } + } +} \ No newline at end of file diff --git a/launcher/src/main/java9/module-info.java b/launcher/src/main/java9/module-info.java new file mode 100644 index 0000000..e39a33f --- /dev/null +++ b/launcher/src/main/java9/module-info.java @@ -0,0 +1,6 @@ +module net.woggioni.executable.jar { + requires java.logging; + requires static lombok; + requires net.woggioni.xclassloader; + requires java.instrument; +} \ No newline at end of file diff --git a/launcher/src/main/java9/net/woggioni/executable/jar/MainClassLoader.java b/launcher/src/main/java9/net/woggioni/executable/jar/MainClassLoader.java new file mode 100644 index 0000000..6b889b9 --- /dev/null +++ b/launcher/src/main/java9/net/woggioni/executable/jar/MainClassLoader.java @@ -0,0 +1,39 @@ +package net.woggioni.executable.jar; + +import java.lang.module.Configuration; +import java.lang.module.ModuleFinder; +import java.nio.file.Path; +import java.util.Collections; +import java.util.Optional; + +import lombok.SneakyThrows; + +import net.woggioni.xclassloader.PathClassLoader; +import net.woggioni.xclassloader.PathModuleFinder; + +class MainClassLoader { + @SneakyThrows + static Class loadMainClass(Iterable roots, String mainModuleName, String mainClassName) { + if (mainModuleName == null) { + ClassLoader pathClassLoader = new net.woggioni.xclassloader.PathClassLoader(roots); + return pathClassLoader.loadClass(mainClassName); + } else { + ModuleLayer bootLayer = ModuleLayer.boot(); + Configuration bootConfiguration = bootLayer.configuration(); + Configuration cfg = bootConfiguration.resolve(new PathModuleFinder(roots), ModuleFinder.of(), Collections.singletonList(mainModuleName)); + ClassLoader pathClassLoader = new PathClassLoader(roots, cfg, null); + ModuleLayer.Controller controller = + ModuleLayer.defineModules(cfg, Collections.singletonList(ModuleLayer.boot()), moduleName -> pathClassLoader); + ModuleLayer layer = controller.layer(); + for(Module module : layer.modules()) { + controller.addReads(module, pathClassLoader.getUnnamedModule()); + } + Module mainModule = layer.findModule(mainModuleName).orElseThrow( + () -> new IllegalStateException(String.format("Main module '%s' not found", mainModuleName))); + return Optional.ofNullable(mainClassName) + .or(() -> mainModule.getDescriptor().mainClass()) + .map(className -> Class.forName(mainModule, className)) + .orElseThrow(() -> new IllegalStateException(String.format("Unable to determine main class name for module '%s'", mainModule.getName()))); + } + } +} diff --git a/launcher/src/test/java/net/woggioni/executable/jar/FooTest.java b/launcher/src/test/java/net/woggioni/executable/jar/FooTest.java new file mode 100644 index 0000000..9b1a4ed --- /dev/null +++ b/launcher/src/test/java/net/woggioni/executable/jar/FooTest.java @@ -0,0 +1,149 @@ +package net.woggioni.executable.jar; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.HashMap; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import lombok.SneakyThrows; +import org.gradle.internal.impldep.org.junit.Ignore; +import org.junit.jupiter.api.Test; + +public class FooTest { + @Test + @SneakyThrows + void foo() { + Path.of(new URI("jar:file:///home/woggioni/code/wson/benchmark/build/libs/benchmark-executable-1.0.jar")); + } + + @Test + @SneakyThrows + void foo2() { + Path p = Path.of(new URI("file:///home/woggioni/code/wson/benchmark/build/libs/benchmark-executable-1.0.jar")); + FileSystem fs = FileSystems.newFileSystem(p, null); + StreamSupport.stream(fs.getRootDirectories().spliterator(), false).flatMap(new Function>() { + @Override + @SneakyThrows + public Stream apply(Path path) { + return Files.list(path); + } + }).forEach(r -> { + System.out.println(r); + }); + } + + @Test + @SneakyThrows + void test() { + Path fatJar = Path.of("/home/woggioni/code/wson/benchmark/build/libs/benchmark-executable-1.0.jar"); + List jars = StreamSupport.stream(FileSystems.newFileSystem(fatJar, null).getRootDirectories().spliterator(), false) + .flatMap(new Function>() { + @Override + @SneakyThrows + public Stream apply(Path root) { + Path libDir = root.resolve("/LIB-INF"); + if (Files.exists(libDir) && Files.isDirectory(libDir)) { + return Files.list(libDir); + } else { + return Stream.empty(); + } + } + }).flatMap(new Function>() { + @Override + @SneakyThrows + public Stream apply(Path path) { + return StreamSupport.stream(FileSystems.newFileSystem(path, null).getRootDirectories().spliterator(), false); + } + }).collect(Collectors.toList()); + PathClassLoader p = new PathClassLoader(jars.toArray(new Path[jars.size()])); + Class cl = p.loadClass("net.woggioni.wson.serialization.binary.JBONParser"); + System.out.println(cl); + URL resource = p.findResource("citylots.json.xz"); + resource.openStream(); + } + + @Test + @Ignore + @SneakyThrows + void test2() { + FileSystem fs = FileSystems.newFileSystem(new URI("jar:file:/home/woggioni/code/wson/benchmark/build/libs/benchmark-executable-1.0.jar"), new HashMap<>()); + String s = "jar:jar:file:///home/woggioni/code/wson/benchmark/build/libs/benchmark-executable-1.0.jar!/LIB-INF/wson-test-utils-1.0.jar!/citylots.json.xz"; + URI uri = new URI(s); + Files.list(Path.of(uri)).forEach(System.out::println); + } + + private static final class PathURLConnection extends URLConnection { + + private final Path path; + + PathURLConnection(URL url, Path path) { + super(url); + this.path = path; + } + + @Override + public void connect() {} + + @Override + public long getContentLengthLong() { + try { + return Files.size(this.path); + } catch (IOException e) { + throw new RuntimeException("could not get size of: " + this.path, e); + } + } + + @Override + public InputStream getInputStream() throws IOException { + return Files.newInputStream(this.path); + } + + @Override + public OutputStream getOutputStream() throws IOException { + return Files.newOutputStream(this.path); + } + + @Override + @SneakyThrows + public String getContentType() { + return Files.probeContentType(this.path); + } + + @Override + @SneakyThrows + public long getLastModified() { + BasicFileAttributes attributes = Files.readAttributes(this.path, BasicFileAttributes.class); + return attributes.lastModifiedTime().toMillis(); + } + } + + @NoArgsConstructor(access = AccessLevel.PRIVATE) + private static final class PathURLStreamHandler extends URLStreamHandler { + + static final URLStreamHandler INSTANCE = new PathURLStreamHandler(); + + @Override + @SneakyThrows + protected URLConnection openConnection(URL url) { + URI uri = url.toURI(); + Path path = Paths.get(uri); + return new PathURLConnection(url, path); + } + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..d489b0e --- /dev/null +++ b/settings.gradle @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + maven { + url = 'https://woggioni.net/mvn/' + } + } + + plugins { + id 'net.woggioni.gradle.lombok' version "0.1" + id "net.woggioni.gradle.multi-release-jar" version "0.1" + } +} + +rootProject.name = 'executable-jar' + +include 'common' +include 'launcher' \ No newline at end of file diff --git a/src/main/java/net/woggioni/gradle/executable/jar/ExecutableJarPlugin.java b/src/main/java/net/woggioni/gradle/executable/jar/ExecutableJarPlugin.java new file mode 100644 index 0000000..8caeb06 --- /dev/null +++ b/src/main/java/net/woggioni/gradle/executable/jar/ExecutableJarPlugin.java @@ -0,0 +1,18 @@ +package net.woggioni.gradle.executable.jar; + +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.plugins.BasePluginExtension; +import org.gradle.api.plugins.JavaPlugin; +import org.gradle.api.tasks.bundling.Jar; + +public class ExecutableJarPlugin implements Plugin { + @Override + public void apply(Project project) { + BasePluginExtension basePluginExtension = project.getExtensions().getByType(BasePluginExtension.class); + project.getTasks().register("executable-jar", ExecutableJarTask.class, t -> { + t.includeLibraries(project.getConfigurations().named(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)); + t.includeLibraries(project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class)); + }); + } +} diff --git a/src/main/java/net/woggioni/gradle/executable/jar/ExecutableJarTask.java b/src/main/java/net/woggioni/gradle/executable/jar/ExecutableJarTask.java new file mode 100644 index 0000000..9f3d048 --- /dev/null +++ b/src/main/java/net/woggioni/gradle/executable/jar/ExecutableJarTask.java @@ -0,0 +1,280 @@ +package net.woggioni.gradle.executable.jar; + +import java.io.File; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.security.MessageDigest; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.function.Supplier; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; +import javax.annotation.Nonnull; +import javax.inject.Inject; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import net.woggioni.executable.jar.Common; +import net.woggioni.executable.jar.Constants; +import org.gradle.api.GradleException; +import org.gradle.api.internal.file.CopyActionProcessingStreamAction; +import org.gradle.api.internal.file.copy.CopyAction; +import org.gradle.api.internal.file.copy.CopyActionProcessingStream; +import org.gradle.api.internal.file.copy.FileCopyDetailsInternal; +import org.gradle.api.model.ObjectFactory; +import org.gradle.api.plugins.BasePluginExtension; +import org.gradle.api.plugins.JavaApplication; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Optional; +import org.gradle.api.tasks.WorkResult; +import org.gradle.api.tasks.bundling.AbstractArchiveTask; +import org.gradle.util.GradleVersion; + + +import static java.util.zip.Deflater.BEST_COMPRESSION; +import static java.util.zip.Deflater.NO_COMPRESSION; +import static net.woggioni.executable.jar.Constants.*; + +@SuppressWarnings({"unused" }) +public class ExecutableJarTask extends AbstractArchiveTask { + + private static final String MINIMUM_GRADLE_VERSION = "6.0"; + + static { + if (GradleVersion.current().compareTo(GradleVersion.version(MINIMUM_GRADLE_VERSION)) < 0) { + throw new GradleException(ExecutableJarTask.class.getName() + + " requires Gradle " + MINIMUM_GRADLE_VERSION + " or newer."); + } + } + + @Getter(onMethod_ = {@Input}) + private final Property mainClass; + + @Getter(onMethod_ = {@Input, @Optional}) + private final Property mainModule; + + private final Properties javaAgents = new Properties(); + + @Input + public Set> getJavaAgents() { + return Collections.unmodifiableSet(javaAgents.entrySet()); + } + + public void javaAgent(String className, String args) { + javaAgents.put(className, args); + } + + public void includeLibraries(Object... files) { + into(LIBRARIES_FOLDER, (copySpec) -> copySpec.from(files)); + } + + + @Inject + public ExecutableJarTask(ObjectFactory objects) { + setGroup("build"); + setDescription("Creates an executable jar file, embedding all of its runtime dependencies"); + BasePluginExtension basePluginExtension = getProject().getExtensions().getByType(BasePluginExtension.class); + getDestinationDirectory().set(basePluginExtension.getDistsDirectory()); + getArchiveBaseName().convention(getProject().getName()); + getArchiveExtension().convention("jar"); + getArchiveVersion().convention(getProject().getVersion().toString()); + getArchiveAppendix().convention("executable"); + exclude("**/module-info.class"); + + mainClass = objects.property(String.class); + mainModule = objects.property(String.class); + JavaApplication javaApplication = getProject().getExtensions().findByType(JavaApplication.class); + if(!Objects.isNull(javaApplication)) { + mainClass.convention(javaApplication.getMainClass()); + mainModule.convention(javaApplication.getMainModule()); + } + from(getProject().tarTree(LauncherResource.instance), copySpec -> exclude(JarFile.MANIFEST_NAME)); + } + + @Input + public String getLauncherArchiveHash() { + return Common.bytesToHex(Common.computeSHA256Digest(LauncherResource.instance::read)); + } + + @RequiredArgsConstructor + private static class StreamAction implements CopyActionProcessingStreamAction { + + private final ZipOutputStream zoos; + private final Manifest manifest; + private final MessageDigest md; + private final ZipEntryFactory zipEntryFactory; + private final byte[] buffer; + + @Override + @SneakyThrows + public void processFile(FileCopyDetailsInternal fileCopyDetails) { + String entryName = fileCopyDetails.getRelativePath().toString(); + if (!fileCopyDetails.isDirectory() && entryName.startsWith(LIBRARIES_FOLDER)) { + Supplier streamSupplier = () -> Common.read(fileCopyDetails.getFile(), false); + Attributes attr = manifest.getEntries().computeIfAbsent(entryName, it -> new Attributes()); + md.reset(); + attr.putValue(Constants.ManifestAttributes.ENTRY_HASH, + Base64.getEncoder().encodeToString(Common.computeDigest(streamSupplier, md, buffer))); + } + if (METADATA_FOLDER.equals(entryName)) return; + if (fileCopyDetails.isDirectory()) { + ZipEntry zipEntry = zipEntryFactory.createDirectoryEntry(entryName, fileCopyDetails.getLastModified()); + zoos.putNextEntry(zipEntry); + } else { + ZipEntry zipEntry = zipEntryFactory.createZipEntry(entryName, fileCopyDetails.getLastModified()); + boolean compressed = Common.splitExtension(fileCopyDetails.getSourceName()) + .map(entry -> ".jar".equals(entry.getValue())) + .orElse(false); + if (!compressed) { + zipEntry.setMethod(ZipEntry.DEFLATED); + } else { + try (InputStream is = Common.read(fileCopyDetails.getFile(), false)) { + Common.computeSizeAndCrc32(zipEntry, is, buffer); + } + zipEntry.setMethod(ZipEntry.STORED); + } + zoos.putNextEntry(zipEntry); + try (InputStream is = Common.read(fileCopyDetails.getFile(), false)) { + Common.write2Stream(is, zoos, buffer); + } + } + } + } + + @SuppressWarnings("SameParameterValue") + @RequiredArgsConstructor + private static final class ZipEntryFactory { + + private final boolean isPreserveFileTimestamps; + private final long defaultLastModifiedTime; + + @Nonnull + ZipEntry createZipEntry(String entryName, long lastModifiedTime) { + ZipEntry zipEntry = new ZipEntry(entryName); + zipEntry.setTime(isPreserveFileTimestamps ? lastModifiedTime : ZIP_ENTRIES_DEFAULT_TIMESTAMP); + return zipEntry; + } + + @Nonnull + ZipEntry createZipEntry(String entryName) { + return createZipEntry(entryName, defaultLastModifiedTime); + } + + @Nonnull + ZipEntry createDirectoryEntry(@Nonnull String entryName, long lastModifiedTime) { + ZipEntry zipEntry = createZipEntry(entryName.endsWith("/") ? entryName : entryName + '/', lastModifiedTime); + zipEntry.setMethod(ZipEntry.STORED); + zipEntry.setCompressedSize(0); + zipEntry.setSize(0); + zipEntry.setCrc(0); + return zipEntry; + } + + @Nonnull + ZipEntry createDirectoryEntry(@Nonnull String entryName) { + return createDirectoryEntry(entryName, defaultLastModifiedTime); + } + + @Nonnull + ZipEntry copyOf(@Nonnull ZipEntry zipEntry) { + if (zipEntry.getMethod() == ZipEntry.STORED) { + return new ZipEntry(zipEntry); + } else { + ZipEntry newEntry = new ZipEntry(zipEntry.getName()); + newEntry.setMethod(ZipEntry.DEFLATED); + newEntry.setTime(zipEntry.getTime()); + newEntry.setExtra(zipEntry.getExtra()); + newEntry.setComment(zipEntry.getComment()); + return newEntry; + } + } + } + + @Override + @Nonnull + protected CopyAction createCopyAction() { + File destination = getArchiveFile().get().getAsFile(); + return new CopyAction() { + + private final ZipEntryFactory zipEntryFactory = new ZipEntryFactory(isPreserveFileTimestamps(), System.currentTimeMillis()); + + @Override + @Nonnull + @SneakyThrows + public WorkResult execute(@Nonnull CopyActionProcessingStream copyActionProcessingStream) { + Manifest manifest = new Manifest(); + Attributes mainAttributes = manifest.getMainAttributes(); + mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); + mainAttributes.put(Attributes.Name.MAIN_CLASS, DEFAULT_LAUNCHER); + mainAttributes.put(Attributes.Name.MULTI_RELEASE, "true"); + mainAttributes.put(new Attributes.Name("Launcher-Agent-Class"), AGENT_LAUNCHER); + mainAttributes.put(new Attributes.Name("Can-Redefine-Classes"), "true"); + mainAttributes.put(new Attributes.Name("Can-Retransform-Classes"), "true"); + mainAttributes.putValue(Constants.ManifestAttributes.MAIN_CLASS, mainClass.get()); + if(mainModule.isPresent()) { + mainAttributes.putValue(Constants.ManifestAttributes.MAIN_MODULE, mainModule.get()); + } + + MessageDigest md = MessageDigest.getInstance("SHA-256"); + byte[] buffer = new byte[Constants.BUFFER_SIZE]; + + /** + * The manifest has to be the first zip entry in a jar archive, as an example, + * {@link java.util.jar.JarInputStream} assumes the manifest is the first (or second at most) + * entry in the jar and simply returns a null manifest if that is not the case. + * In this case the manifest has to contain the hash of all the jar entries, so it cannot + * be computed in advance, we write all the entries to a temporary zip archive while computing the manifest, + * then we write the manifest to the final zip file as the first entry and, finally, + * we copy all the other entries from the temporary archive. + * + * The {@link org.gradle.api.Task#getTemporaryDir} directory is guaranteed + * to be unique per instance of this task. + */ + File temporaryJar = new File(getTemporaryDir(), "premature.zip"); + try (ZipOutputStream zipOutputStream = new ZipOutputStream(Common.write(temporaryJar, true))) { + zipOutputStream.setLevel(NO_COMPRESSION); + StreamAction streamAction = new StreamAction(zipOutputStream, manifest, md, zipEntryFactory, buffer); + copyActionProcessingStream.process(streamAction); + } + + try (ZipOutputStream zipOutputStream = new ZipOutputStream(Common.write(destination, true)); + ZipInputStream zipInputStream = new ZipInputStream(Common.read(temporaryJar, true))) { + zipOutputStream.setLevel(BEST_COMPRESSION); + ZipEntry zipEntry = zipEntryFactory.createDirectoryEntry(METADATA_FOLDER); + zipOutputStream.putNextEntry(zipEntry); + zipEntry = zipEntryFactory.createZipEntry(JarFile.MANIFEST_NAME); + zipEntry.setMethod(ZipEntry.DEFLATED); + zipOutputStream.putNextEntry(zipEntry); + manifest.write(zipOutputStream); + zipEntry = zipEntryFactory.createZipEntry(JAVA_AGENTS_FILE); + zipEntry.setMethod(ZipEntry.DEFLATED); + zipOutputStream.putNextEntry(zipEntry); + javaAgents.store(zipOutputStream, null); + + while (true) { + zipEntry = zipInputStream.getNextEntry(); + if (zipEntry == null) break; + // Create a new ZipEntry explicitly, without relying on + // subtle (undocumented?) behaviour of ZipInputStream. + zipOutputStream.putNextEntry(zipEntryFactory.copyOf(zipEntry)); + Common.write2Stream(zipInputStream, zipOutputStream, buffer); + } + return () -> true; + } + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/net/woggioni/gradle/executable/jar/LauncherResource.java b/src/main/java/net/woggioni/gradle/executable/jar/LauncherResource.java new file mode 100644 index 0000000..a7f746e --- /dev/null +++ b/src/main/java/net/woggioni/gradle/executable/jar/LauncherResource.java @@ -0,0 +1,42 @@ +package net.woggioni.gradle.executable.jar; + +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import javax.annotation.Nonnull; +import lombok.SneakyThrows; +import org.gradle.api.resources.ReadableResource; +import org.gradle.api.resources.ResourceException; + +final class LauncherResource implements ReadableResource { + static final ReadableResource instance = new LauncherResource(); + + private final URL url; + + private LauncherResource() { + url = getClass().getResource(String.format("/META-INF/%s", getDisplayName())); + } + + @Override + @Nonnull + @SneakyThrows + public InputStream read() throws ResourceException { + return url.openStream(); + } + + @Override + public String getDisplayName() { + return getBaseName() + ".tar"; + } + + @Override + @SneakyThrows + public URI getURI() { + return url.toURI(); + } + + @Override + public String getBaseName() { + return "launcher"; + } +} \ No newline at end of file