Initial Commit

This commit is contained in:
2023-11-05 14:21:03 +02:00
commit 24c2751651
15 changed files with 1069 additions and 0 deletions

45
.gitignore vendored Normal file
View File

@@ -0,0 +1,45 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
.idea
testdir/

4
HEADER Normal file
View File

@@ -0,0 +1,4 @@
/*
* This file is part of JarManager, licensed under The MIT License (MIT).
* Copyright HypherionSA and Contributors
*/

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2021-2023 HypherionSA and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

96
build.gradle Normal file
View File

@@ -0,0 +1,96 @@
plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '7.0.0'
id "com.diffplug.spotless" version "6.13.0"
}
apply plugin: 'maven-publish'
var base_version = "${version_major}.${version_minor}.${version_patch}"
group = maven_group
version = base_version
archivesBaseName = "JarManager"
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
configurations {
shadeMe
implementation.extendsFrom shadeMe
}
repositories {
mavenCentral()
}
dependencies {
compileOnly "org.projectlombok:lombok:${lombok}"
annotationProcessor "org.projectlombok:lombok:${lombok}"
testCompileOnly "org.projectlombok:lombok:${lombok}"
testAnnotationProcessor "org.projectlombok:lombok:${lombok}"
shadeMe("me.lucko:jar-relocator:${jarrelocator}") {
exclude group: 'org.ow2.asm'
}
shadeMe "org.ow2.asm:asm:${asm}"
shadeMe "org.ow2.asm:asm-commons:${asm}"
}
shadowJar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
configurations = [project.configurations.getByName("shadeMe")]
archiveClassifier.set(null)
}
spotless {
java {
targetExclude("src/test/**")
licenseHeaderFile(rootProject.file("HEADER")).yearSeparator("-")
}
}
jar {
manifest {
attributes([
'Timestamp' : System.currentTimeMillis(),
'Specification-Title' : project.archivesBaseName,
'Specification-Version' : project.version,
'Implementation-Title' : project.archivesBaseName,
'Implementation-Version' : project.version,
'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
'Built-On-Java' : "${System.getProperty('java.vm.version')} (${System.getProperty('java.vm.vendor')})"
])
}
}
tasks.register('sourcesJar', Jar) {
from sourceSets.main.allSource
setArchiveClassifier("sources");
}
tasks.register('javadocJar', Jar) {
dependsOn 'javadoc'
from javadoc.destinationDir
setArchiveClassifier("javadoc");
}
publishing {
publications {
mavenJava(MavenPublication) {
artifact shadowJar
artifact sourcesJar
artifact javadocJar
}
}
repositories {
maven {
url System.getenv('MAVEN_URL')
credentials {
username System.getenv('MAVEN_USER')
password System.getenv('MAVEN_PASS')
}
}
}
}

10
gradle.properties Normal file
View File

@@ -0,0 +1,10 @@
version_major=1
version_minor=0
version_patch=0
maven_group=com.hypherionmc
# Dependencies
lombok=1.18.30
jarrelocator=1.5
asm=9.3

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#Sun Nov 05 12:10:59 SAST 2023
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@@ -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" "$@"

89
gradlew.bat vendored Normal file
View File

@@ -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

103
readme.md Normal file
View File

@@ -0,0 +1,103 @@
## JarManager
JarManager is a java library that allows you un-pack jar files to a directory, pack directories to a jar and relocate packages inside a jar using [jar-relocator](https://github.com/lucko/jar-relocator).
The library is simple to use and doesn't require much configuration.
***
### Installation
Firstly, add our Maven to your `build.gradle` file.
```groovy
repositories {
mavenCentral()
// Your other repos might be here
maven {
url "https://maven.firstdarkdev.xyz/releases"
}
}
```
Next, add the library to your `build.gradle` file.
![](https://maven.firstdarkdev.xyz/api/badge/latest/releases/com/hypherionmc/jarmanager?color=40c14a&name=jarmanager)
View the latest version on our [Maven](https://maven.firstdarkdev.xyz/#/releases/com/hypherionmc/jarmanager) or use the version in the badge above
```groovy
dependencies {
// Existing dependencies
implementation "com.hypherionmc:jarmanager:1.0.0"
}
```
***
### Using the library
Once you have the library added to your project, using it is really simple.
#### Unpacking a Jar file
```java
public void unpackJar() throws IOException {
File testDirectory = new File("testdir");
File outputDirectory = new File(testDirectory, "output");
if (!outputDirectory.exists())
outputDirectory.mkdirs();
// Create a JarManager instance
JarManager manager = JarManager.getInstance();
// Unpack the Jar
manager.unpackJar(new File(testDirectory, "input.jar"), outputDirectory);
}
```
#### Repacking a Jar file
```java
public void repackJar() throws IOException {
File testDirectory = new File("testdir");
File inputDirectory = new File(testDirectory, "output");
// Create a JarManager instance
JarManager manager = JarManager.getInstance();
// Pack the Jar
manager.packJar(inputDirectory, new File(testDirectory, "output.jar"));
}
```
#### Relocating Packages
```java
public void remapJar() throws IOException {
File testDirectory = new File("testdir");
File inputFile = new File(testDirectory, "input.jar");
// Create a JarManager instance
JarManager manager = JarManager.getInstance();
// Remap the Jar
HashMap<String, String> rl = new HashMap<>();
rl.put("com.gitlab.cdagaming", "test.com.gitlab.cdagaming");
manager.remapJar(inputFile, new File(testDirectory, "remapped.jar"), rl);
}
```
***
### Licenses
JarManager is licensed under the MIT License.
JarManager includes the following embedded libraries:
* [jar-relocator](https://github.com/lucko/jar-relocator) - Licensed under [Apache-2.0 License](https://github.com/lucko/jar-relocator/blob/master/LICENSE.txt)
* [OW2 ASM](https://gitlab.ow2.org/asm/asm) - Licensed under [BSD 3-Clause License](https://gitlab.ow2.org/asm/asm/-/blob/master/LICENSE.txt?ref_type=heads)

2
settings.gradle Normal file
View File

@@ -0,0 +1,2 @@
rootProject.name = 'jarmanager'

View File

@@ -0,0 +1,84 @@
/*
* This file is part of JarManager, licensed under The MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.jarmanager;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import me.lucko.jarrelocator.JarRelocator;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.zip.Deflater;
/**
* @author HypherionSA
* Main JarManager class. Allows you to enable debugging, set the compression level and is a central place to run jar tasks
*/
@NoArgsConstructor(staticName = "getInstance")
public final class JarManager {
/**
* Enable additional debug logging
*/
@Getter
@Setter
private boolean debugMode = false;
/**
* Set the compression level for the output jar
*/
@Getter
@Setter
private int compressionLevel = Deflater.DEFAULT_COMPRESSION;
/**
* Pack a directory into a jar file
* @param inputDirectory - The directory containing the content for the jar
* @param outputJar - The file that the jar will be written to
* @return - The packaged jar file
* @throws IOException - Thrown when an IO error occurs
*/
public File packJar(File inputDirectory, File outputJar) throws IOException {
JarPackageTask task = new JarPackageTask(this, inputDirectory, outputJar);
return task.pack();
}
/**
* Unpack a jar file into a directory
* @param inputJar - The input jar file to be unpacked
* @param outputDirectory - The directory the jar file will be unpacked to
* @return - A list of unpacked files and directories
* @throws IOException - Thrown when an IO error occurs
*/
public List<File> unpackJar(File inputJar, File outputDirectory) throws IOException {
JarUnpackTask task = new JarUnpackTask(this, inputJar, outputDirectory);
return task.unpackJar();
}
/**
* Relocate or remap packages inside a jar file.
* For example, from com.google.gson to lib.com.google.gson
* @param inputJar - The input jar file that will be modified
* @param outputJar - The file the modified file will be saved to
* @param relocations - Packages to relocate. See example above
* @throws IOException - Thrown when an IO error occurs
*/
public void remapJar(File inputJar, File outputJar, HashMap<String, String> relocations) throws IOException {
// Set up temp file, to prevent accidental overwrites
File tempJar = new File(inputJar.getParentFile(), "tempRelocated.jar");
// Run the jar relocater task
JarRelocator relocator = new JarRelocator(inputJar, tempJar, relocations);
relocator.run();
// Move the temporary file to the outputJar
Files.move(tempJar.toPath(), outputJar.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}

View File

@@ -0,0 +1,180 @@
/*
* This file is part of JarManager, licensed under The MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.jarmanager;
import java.io.*;
import java.nio.file.Files;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
/**
* @author HypherionSA
* Internal task to perform the jar packing action. Should never be used directly.
* Should be invoked from {@link JarManager#packJar(File, File)}
*/
final class JarPackageTask {
// JarManager instance
private final JarManager jarManager;
// Output stream
private JarOutputStream outputStream;
// Files
private final File inputDirectory;
private final File outputJar;
/**
* Internal. Should not be used directly.
* Create a new instance of the jar packager task
* @param jarManager - Initialized instance of {@link JarManager}
* @param inputDirectory The input directory that will be packed
* @param outputJar - The output file the jar will be written to
*/
JarPackageTask(JarManager jarManager, File inputDirectory, File outputJar) {
this.jarManager = jarManager;
this.inputDirectory = inputDirectory;
this.outputJar = outputJar;
if (!inputDirectory.exists())
throw new IllegalStateException("inputDirectory does not exist");
if (!inputDirectory.isDirectory())
throw new IllegalStateException("inputDirectory is not a directory");
if (outputJar == null)
throw new IllegalStateException("outputJar cannot be null!");
}
/**
* Run the package task
* @return - The output jar that was packaged
* @throws IOException - Thrown when an IO error occurs
*/
File pack() throws IOException {
// Set up the output stream and set the chosen compression level
this.outputStream = new JarOutputStream(Files.newOutputStream(outputJar.toPath()));
this.outputStream.setLevel(jarManager.getCompressionLevel());
// Debug Logging
if (jarManager.isDebugMode())
System.out.println("Packing jar " + outputJar.getName());
// Processes the folder to add all files and directories to the output jar
this.addFilesRecursively(inputDirectory, null);
// Debug Logging
if (jarManager.isDebugMode())
System.out.println("Packed jar " + outputJar.getName());
// Close the output stream
try {
this.outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// Return the new jar
return outputJar;
}
/**
* Add a file to the output jar
* @param source - The file to be added
* @param outputDir - The output directory. Used to fix file names in the output jar
*/
private void addFile(File source, File outputDir) {
// Input reader stream
BufferedInputStream inputStream;
try {
// Get the correct file name for the final jar
String sourcePath = source.getAbsolutePath().substring(outputDir.getAbsolutePath().length() + 1);
// Source is a file. Process it
if (!source.isDirectory()) {
// Set up a new jar entry
JarEntry entry = new JarEntry(sourcePath.replace("\\", "/"));
entry.setTime(source.lastModified());
this.outputStream.putNextEntry(entry);
// Set up the input stream and buffer
inputStream = new BufferedInputStream(Files.newInputStream(source.toPath()));
byte[] buffer = new byte[1024];
int count;
// Read and write the file to the jar
while ((count = inputStream.read(buffer)) != -1) {
this.outputStream.write(buffer, 0, count);
}
// Close the input/output stream
this.outputStream.closeEntry();
inputStream.close();
return;
}
// Source is a directory. Add it to the jar, and process its files
String name = sourcePath.replace("\\", "/");
if (!name.isEmpty()) {
// Add a trailing slash to the file name if there isn't one
if (!name.endsWith("/")) {
name = name + "/";
}
// Write the jar entry to the jar
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
this.outputStream.putNextEntry(entry);
// Close the entry
this.outputStream.closeEntry();
}
// Loop over files in the directory
File[] files = source.listFiles();
if (files == null)
return;
for (File f : files) {
// Add the files to the output jar
this.addFile(f, outputDir);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Loop over files and folders in the inputDir to add them to the jar file
* @param inputDir - The input directory containing the files that will be added to the output jar
* @param outputDir - The directory holding the output. Used to fix file names in the output jar
*/
private void addFilesRecursively(File inputDir, File outputDir) {
if (outputDir == null)
outputDir = inputDir;
// Get a list of files and folders from the directory
File[] files = inputDir.listFiles();
if (files == null) {
if (jarManager.isDebugMode())
System.err.println("inputDirectory doesn't appear to contain files. Skipping...");
return;
}
for (File f : files) {
// It's a file. Add it
if (f.isFile()) {
this.addFile(f, outputDir);
continue;
}
// It's a folder. Process it to find files, to add to the jar
if (f.isDirectory())
this.addFilesRecursively(f, outputDir);
}
}
}

View File

@@ -0,0 +1,123 @@
/*
* This file is part of JarManager, licensed under The MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.jarmanager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* @author HypherionSA
* Internal task to perform the jar unpacking action. Should never be used directly.
* Should be invoked from {@link JarManager#unpackJar(File, File)}
*/
final class JarUnpackTask {
// JarManager instance
private final JarManager manager;
// List of unpacked files and directories that will be returned
private final List<File> files = new ArrayList<>();
// Files
private final File inputJar;
private final File outputDirectory;
/**
* Internal. Should not be used directly.
* Create a new instance of the jar unpacker task
* @param manager - Initialized instance of {@link JarManager}
* @param inputJar - The input jar that will be unpacked
* @param outputDirectory - The directory the jar will be unpacked to
*/
JarUnpackTask(JarManager manager, File inputJar, File outputDirectory) {
this.manager = manager;
this.inputJar = inputJar;
this.outputDirectory = outputDirectory;
if (!inputJar.exists())
throw new IllegalStateException("inputJar does not exist");
if (!inputJar.isFile())
throw new IllegalStateException("inputJar is not a file");
}
/**
* Run the unpack task
* @return - Returns a list of unpacked files and directories
* @throws IOException - Thrown when an IO error occurs
*/
List<File> unpackJar() throws IOException {
// Open the input file for processing
try (JarFile jarFile = new JarFile(inputJar)) {
// Debug Logging
if (manager.isDebugMode())
System.out.println("Unpacking " + jarFile.getName() + "...");
// Get a list of entries from the input jar
Enumeration<JarEntry> enumEntries = jarFile.entries();
// Create output directories
if (!outputDirectory.exists()) {
boolean created = outputDirectory.mkdirs();
if (created && manager.isDebugMode())
System.out.println("Created output directory " + outputDirectory.getAbsolutePath());
if (!created && manager.isDebugMode())
System.out.println("Failed to create output directory " + outputDirectory.getAbsolutePath());
}
// Process the entries
while (enumEntries.hasMoreElements()) {
JarEntry entry = enumEntries.nextElement();
// Entry is a directory. Skip and continue
if (entry.isDirectory())
continue;
// The output file that will be written
File outFile = new File(outputDirectory, entry.getName());
// Debug Logging
if (manager.isDebugMode()) {
System.out.println("[Unpacking] " + entry.getName() + " => " + outFile.getAbsolutePath());
}
// Create output directory for the file
outFile.getParentFile().mkdirs();
// Create the read and write streams
InputStream inputStream = jarFile.getInputStream(entry);
FileOutputStream outputStream = new FileOutputStream(outFile);
// Initialize the buffer
byte[] buffer = new byte[1024];
int read;
// Read the entry from the jar and write to the output directory
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
// Add the processed entry to the return list
this.files.add(outFile);
// Close everything
outputStream.close();
inputStream.close();
}
}
return this.files;
}
}

View File

@@ -0,0 +1,72 @@
import com.hypherionmc.jarmanager.JarManager;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.zip.Deflater;
public class JarTests {
private static final File testDirectory = new File("testdir");
private static final File outputDirectory = new File(testDirectory, "output");
public void unpackJar() throws IOException {
File testDirectory = new File("testdir");
File outputDirectory = new File(testDirectory, "output");
if (!outputDirectory.exists())
outputDirectory.mkdirs();
// Create a JarManager instance
JarManager manager = JarManager.getInstance();
// Unpack the Jar
manager.unpackJar(new File(testDirectory, "input.jar"), outputDirectory);
}
public void repackJar() throws IOException {
File testDirectory = new File("testdir");
File inputDirectory = new File(testDirectory, "output");
// Create a JarManager instance
JarManager manager = JarManager.getInstance();
// Unpack the Jar
manager.packJar(inputDirectory, new File(testDirectory, "output.jar"));
}
public void remapJar() throws IOException {
File testDirectory = new File("testdir");
File inputFile = new File(testDirectory, "input.jar");
// Create a JarManager instance
JarManager manager = JarManager.getInstance();
// Remap the Jar
HashMap<String, String> rl = new HashMap<>();
rl.put("com.gitlab.cdagaming", "test.com.gitlab.cdagaming");
manager.remapJar(inputFile, new File(testDirectory, "remapped.jar"), rl);
}
public static void main(String[] args) throws IOException {
if (!outputDirectory.exists())
outputDirectory.mkdirs();
File inputJar = new File(testDirectory, "forge.jar");
File outputJar = new File(testDirectory, "forge-output.jar");
// Unpack Jar
JarManager manager = JarManager.getInstance();
manager.unpackJar(inputJar, outputDirectory);
// Repack jar with best compression
manager.setCompressionLevel(Deflater.BEST_COMPRESSION);
manager.packJar(outputDirectory, outputJar);
// Relocation Test
HashMap<String, String> rl = new HashMap<>();
rl.put("com.gitlab.cdagaming", "test.com.gitlab.cdagaming");
manager.remapJar(outputJar, new File(testDirectory, "outputJar.jar"), rl);
}
}