
net.dongliu.jpackage.AddModuleInfo Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jpackage-maven-plugin Show documentation
Show all versions of jpackage-maven-plugin Show documentation
Easy ways to create JPackage Images
The newest version!
package net.dongliu.jpackage;
import org.moditect.internal.compiler.ModuleInfoCompiler;
import org.moditect.internal.shaded.javaparser.ast.modules.ModuleDeclaration;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;
/**
* Creates a copy of a given JAR file, adding a module-info.class descriptor.
*
* @author Gunnar Morling
*/
public class AddModuleInfo {
private final String moduleInfoSource;
private final Path inputJar;
private final Path outputDirectory;
private final boolean overwriteExistingFiles;
public AddModuleInfo(String moduleInfoSource, Path inputJar, Path outputDirectory,
boolean overwriteExistingFiles) {
this.moduleInfoSource = moduleInfoSource;
this.inputJar = inputJar;
this.outputDirectory = outputDirectory;
this.overwriteExistingFiles = overwriteExistingFiles;
}
public void run() {
if (Files.isDirectory(inputJar)) {
throw new IllegalArgumentException("Input JAR must not be a directory");
}
if (!Files.exists(outputDirectory)) {
throw new IllegalArgumentException("Output directory doesn't exist: " + outputDirectory);
}
Path outputJar = outputDirectory.resolve(inputJar.getFileName());
if (Files.exists(outputJar) && !overwriteExistingFiles) {
throw new RuntimeException("File " + outputJar + " already exists");
}
try {
Files.copy(inputJar, outputJar, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Couldn't copy JAR file", e);
}
ModuleDeclaration module = ModuleInfoCompiler.parseModuleInfo(moduleInfoSource);
byte[] clazz = ModuleInfoCompiler.compileModuleInfo(module, null, null);
Map env = new HashMap<>();
env.put("create", "true");
URI uri = URI.create("jar:" + outputJar.toUri().toString());
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Files.write(zipfs.getPath("module-info.class"), clazz,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Couldn't add module-info.class to JAR", e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy