diff --git a/core/src/main/java/org/moditect/Moditect.java b/core/src/main/java/org/moditect/Moditect.java index b029932..2722bb0 100644 --- a/core/src/main/java/org/moditect/Moditect.java +++ b/core/src/main/java/org/moditect/Moditect.java @@ -17,7 +17,6 @@ import java.nio.file.Path; import java.nio.file.Paths; -import java.text.NumberFormat; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -35,51 +34,28 @@ public class Moditect { public static void main(String[] args) throws Exception { CliArgs cliArgs = new CliArgs(); - new JCommander( cliArgs, args ); + new JCommander(cliArgs, args); - new AddModuleInfo( null, null, null, null, cliArgs.outputDirecory, cliArgs.jvmVersion, cliArgs.overwriteExistingFiles, cliArgs.timestamp ).run(); + new AddModuleInfo(null, null, null, null, cliArgs.outputDirecory, cliArgs.jvmVersion, cliArgs.overwriteExistingFiles, cliArgs.timestamp).run(); } @Parameters(separators = "=") private static class CliArgs { - @Parameter( - names = "--module-info", - required = true, - description = "Path to the module-info.java descriptor", - converter = PathConverter.class - ) + @Parameter(names = "--module-info", required = true, description = "Path to the module-info.java descriptor", converter = PathConverter.class) private Path moduleInfo; - @Parameter( - names = "--output-directory", - required = true, - description = "Path to a directory for storing the modularized JAR", - converter = PathConverter.class - ) + @Parameter(names = "--output-directory", required = true, description = "Path to a directory for storing the modularized JAR", converter = PathConverter.class) private Path outputDirecory; - @Parameter( - names = "--jvm-version", - required = false, - description = "The JVM version for which to add the module-info.java descriptor, " - + "or \"base\" to add the descriptor to the root of the jarfile (default: 9)" - ) + @Parameter(names = "--jvm-version", required = false, description = "The JVM version for which to add the module-info.java descriptor, " + + "or \"base\" to add the descriptor to the root of the jarfile (default: 9)") private String jvmVersion; - @Parameter( - names = "--overwrite-existing-files", - required = false, - description = "Whether to overwrite existing files or not" - ) + @Parameter(names = "--overwrite-existing-files", required = false, description = "Whether to overwrite existing files or not") private boolean overwriteExistingFiles; - @Parameter( - names = "--timestamp", - required = false, - description = "Timestamp used when writing archive entries", - converter = InstantConverter.class - ) + @Parameter(names = "--timestamp", required = false, description = "Timestamp used when writing archive entries", converter = InstantConverter.class) private Instant timestamp; } @@ -87,48 +63,49 @@ private static class PathConverter implements IStringConverter { @Override public Path convert(String value) { - return Paths.get( value ); + return Paths.get(value); } } private static class InstantConverter implements IStringConverter { - private static final Instant DATE_MIN = Instant.parse( "1980-01-01T00:00:02Z" ); - private static final Instant DATE_MAX = Instant.parse( "2099-12-31T23:59:59Z" ); + private static final Instant DATE_MIN = Instant.parse("1980-01-01T00:00:02Z"); + private static final Instant DATE_MAX = Instant.parse("2099-12-31T23:59:59Z"); @Override public Instant convert(String value) { - if ( value == null ) { + if (value == null) { return null; } // Number representing seconds since the epoch - if ( !value.isEmpty() && isNumeric( value ) ) { - return Instant.ofEpochSecond( Long.parseLong( value.trim() ) ); + if (!value.isEmpty() && isNumeric(value)) { + return Instant.ofEpochSecond(Long.parseLong(value.trim())); } try { // Parse the date in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'. - final Instant date = OffsetDateTime.parse( value ) - .withOffsetSameInstant( ZoneOffset.UTC ).truncatedTo( ChronoUnit.SECONDS ).toInstant(); + final Instant date = OffsetDateTime.parse(value) + .withOffsetSameInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS).toInstant(); - if ( date.isBefore( DATE_MIN ) || date.isAfter( DATE_MAX ) ) { - throw new IllegalArgumentException( "'" + date + "' is not within the valid range " - + DATE_MIN + " to " + DATE_MAX ); + if (date.isBefore(DATE_MIN) || date.isAfter(DATE_MAX)) { + throw new IllegalArgumentException("'" + date + "' is not within the valid range " + + DATE_MIN + " to " + DATE_MAX); } return date; } - catch ( DateTimeParseException pe ) { - throw new IllegalArgumentException( "Invalid project.build.outputTimestamp value '" + value + "'", - pe ); + catch (DateTimeParseException pe) { + throw new IllegalArgumentException("Invalid project.build.outputTimestamp value '" + value + "'", + pe); } } - private boolean isNumeric( String str ) { + private boolean isNumeric(String str) { try { - Long.parseLong( str.trim() ); + Long.parseLong(str.trim()); return true; - } catch( NumberFormatException e ) { + } + catch (NumberFormatException e) { return false; } } diff --git a/core/src/main/java/org/moditect/commands/AddModuleInfo.java b/core/src/main/java/org/moditect/commands/AddModuleInfo.java index 39cfc20..f3e8d72 100644 --- a/core/src/main/java/org/moditect/commands/AddModuleInfo.java +++ b/core/src/main/java/org/moditect/commands/AddModuleInfo.java @@ -53,7 +53,8 @@ public class AddModuleInfo { private final boolean overwriteExistingFiles; private final Instant timestamp; - public AddModuleInfo(String moduleInfoSource, String mainClass, String version, Path inputJar, Path outputDirectory, String jvmVersion, boolean overwriteExistingFiles, Instant timestamp) { + public AddModuleInfo(String moduleInfoSource, String mainClass, String version, Path inputJar, Path outputDirectory, String jvmVersion, + boolean overwriteExistingFiles, Instant timestamp) { this.moduleInfoSource = moduleInfoSource; this.mainClass = mainClass; this.version = version; @@ -74,7 +75,7 @@ public AddModuleInfo(String moduleInfoSource, String mainClass, String version, } } catch (NumberFormatException e) { - throw new IllegalArgumentException("Invalid JVM Version: " + jvmVersion + ". Allowed values are 'base' and integer values >= 9." ); + throw new IllegalArgumentException("Invalid JVM Version: " + jvmVersion + ". Allowed values are 'base' and integer values >= 9."); } } this.overwriteExistingFiles = overwriteExistingFiles; @@ -82,82 +83,82 @@ public AddModuleInfo(String moduleInfoSource, String mainClass, String version, } public void run() { - if ( Files.isDirectory( inputJar ) ) { - throw new IllegalArgumentException( "Input JAR must not be a directory" ); + 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); + if (!Files.exists(outputDirectory)) { + throw new IllegalArgumentException("Output directory doesn't exist: " + outputDirectory); } - Path outputJar = outputDirectory.resolve( inputJar.getFileName() ); + Path outputJar = outputDirectory.resolve(inputJar.getFileName()); - if ( Files.exists( outputJar ) && !overwriteExistingFiles ) { + if (Files.exists(outputJar) && !overwriteExistingFiles) { throw new RuntimeException( - "File " + outputJar + " already exists; either set 'overwriteExistingFiles' to true or specify another output directory" ); + "File " + outputJar + " already exists; either set 'overwriteExistingFiles' to true or specify another output directory"); } try { Files.copy(inputJar, outputJar, StandardCopyOption.REPLACE_EXISTING); } - catch(IOException e) { - throw new RuntimeException( "Couldn't copy JAR file", e ); + catch (IOException e) { + throw new RuntimeException("Couldn't copy JAR file", e); } - ModuleDeclaration module = ModuleInfoCompiler.parseModuleInfo( moduleInfoSource ); - byte[] clazz = ModuleInfoCompiler.compileModuleInfo( module, mainClass, version ); + ModuleDeclaration module = ModuleInfoCompiler.parseModuleInfo(moduleInfoSource); + byte[] clazz = ModuleInfoCompiler.compileModuleInfo(module, mainClass, version); Map env = new HashMap<>(); - env.put( "create", "true" ); - URI uri = URI.create( "jar:" + outputJar.toUri() ); - - try (FileSystem zipfs = FileSystems.newFileSystem( uri, env ) ) { - if (jvmVersion == null) { - Path path = zipfs.getPath("module-info.class"); - Files.write(path, clazz, - StandardOpenOption.CREATE, - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING ); - Files.setLastModifiedTime( path, toFileTime(timestamp) ); - } - else { - Path path = zipfs.getPath( "META-INF/versions", jvmVersion.toString(), "module-info.class" ); - Files.createDirectories( path.getParent() ); - Files.write( path, clazz, - StandardOpenOption.CREATE, - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING ); - FileTime lastModifiedTime = toFileTime( timestamp ); - // module-info.class - Files.setLastModifiedTime( path, lastModifiedTime ); - // jvmVersion - Files.setLastModifiedTime( path.getParent(), lastModifiedTime ); - // versions - Files.setLastModifiedTime( path.getParent().getParent(), lastModifiedTime ); - - Path manifestPath = zipfs.getPath( "META-INF/MANIFEST.MF" ); - Manifest manifest; - if ( Files.exists( manifestPath ) ) { - manifest = new Manifest( Files.newInputStream( manifestPath ) ); - } - else { - manifest = new Manifest(); - manifest.getMainAttributes().put( Attributes.Name.MANIFEST_VERSION, "1.0" ); - } - - manifest.getMainAttributes().put( new Attributes.Name("Multi-Release"), "true" ); - try (OutputStream manifestOs = Files.newOutputStream( manifestPath, StandardOpenOption.TRUNCATE_EXISTING )) { - manifest.write( manifestOs ); - } - Files.setLastModifiedTime( manifestPath, lastModifiedTime ); - } - } - catch(IOException e) { - throw new RuntimeException( "Couldn't add module-info.class to JAR", e ); + env.put("create", "true"); + URI uri = URI.create("jar:" + outputJar.toUri()); + + try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { + if (jvmVersion == null) { + Path path = zipfs.getPath("module-info.class"); + Files.write(path, clazz, + StandardOpenOption.CREATE, + StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING); + Files.setLastModifiedTime(path, toFileTime(timestamp)); + } + else { + Path path = zipfs.getPath("META-INF/versions", jvmVersion.toString(), "module-info.class"); + Files.createDirectories(path.getParent()); + Files.write(path, clazz, + StandardOpenOption.CREATE, + StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING); + FileTime lastModifiedTime = toFileTime(timestamp); + // module-info.class + Files.setLastModifiedTime(path, lastModifiedTime); + // jvmVersion + Files.setLastModifiedTime(path.getParent(), lastModifiedTime); + // versions + Files.setLastModifiedTime(path.getParent().getParent(), lastModifiedTime); + + Path manifestPath = zipfs.getPath("META-INF/MANIFEST.MF"); + Manifest manifest; + if (Files.exists(manifestPath)) { + manifest = new Manifest(Files.newInputStream(manifestPath)); + } + else { + manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + } + + manifest.getMainAttributes().put(new Attributes.Name("Multi-Release"), "true"); + try (OutputStream manifestOs = Files.newOutputStream(manifestPath, StandardOpenOption.TRUNCATE_EXISTING)) { + manifest.write(manifestOs); + } + Files.setLastModifiedTime(manifestPath, lastModifiedTime); + } + } + catch (IOException e) { + throw new RuntimeException("Couldn't add module-info.class to JAR", e); } } - private FileTime toFileTime( Instant timestamp ) { - return FileTime.from( timestamp != null ? timestamp : Instant.now() ); + private FileTime toFileTime(Instant timestamp) { + return FileTime.from(timestamp != null ? timestamp : Instant.now()); } } diff --git a/core/src/main/java/org/moditect/commands/CreateRuntimeImage.java b/core/src/main/java/org/moditect/commands/CreateRuntimeImage.java index bd35970..ee12293 100644 --- a/core/src/main/java/org/moditect/commands/CreateRuntimeImage.java +++ b/core/src/main/java/org/moditect/commands/CreateRuntimeImage.java @@ -62,8 +62,8 @@ public CreateRuntimeImage(Set modulePath, List modules, JarInclusi Path outputDirectory, Integer compression, boolean stripDebug, boolean ignoreSigningInformation, List excludeResourcesPatterns, Log log, boolean noHeaderFiles, boolean noManPages, boolean bindServices) { - this.modulePath = ( modulePath != null ? modulePath : Collections.emptySet() ); - this.modules = getModules( modules ); + this.modulePath = (modulePath != null ? modulePath : Collections.emptySet()); + this.modules = getModules(modules); this.jarInclusionPolicy = jarInclusionPolicy; this.dependencies = dependencies; this.projectJar = projectJar; @@ -80,11 +80,11 @@ public CreateRuntimeImage(Set modulePath, List modules, JarInclusi } private static List getModules(List modules) { - if ( modules == null || modules.isEmpty() ) { + if (modules == null || modules.isEmpty()) { throw new IllegalArgumentException("At least one module must be added using the configuration property."); } - return Collections.unmodifiableList( modules ); + return Collections.unmodifiableList(modules); } public void run() throws IOException { @@ -157,54 +157,53 @@ private void runJlink() throws AssertionError { File.separator + "jlink"; List command = new ArrayList<>(); - command.add( jlinkBin ); - - command.add( "--add-modules" ); - command.add( String.join( ",", modules ) ); - command.add( "--module-path" ); - command.add( modulePath.stream() - .map( Path::toString ) - .collect( Collectors.joining( File.pathSeparator ) ) - ); - command.add( "--output" ); - command.add( outputDirectory.toString() ); - - if ( launcher != null ) { - command.add( "--launcher" ); - command.add( launcher ); + command.add(jlinkBin); + + command.add("--add-modules"); + command.add(String.join(",", modules)); + command.add("--module-path"); + command.add(modulePath.stream() + .map(Path::toString) + .collect(Collectors.joining(File.pathSeparator))); + command.add("--output"); + command.add(outputDirectory.toString()); + + if (launcher != null) { + command.add("--launcher"); + command.add(launcher); } - if ( compression != null ) { - command.add( "--compress" ); - command.add( compression.toString() ); + if (compression != null) { + command.add("--compress"); + command.add(compression.toString()); } - if ( stripDebug ) { - command.add( "--strip-debug" ); + if (stripDebug) { + command.add("--strip-debug"); } if (ignoreSigningInformation) { - command.add( "--ignore-signing-information" ); + command.add("--ignore-signing-information"); } - if ( !excludeResourcesPatterns.isEmpty() ) { - command.add( "--exclude-resources=" + String.join( ",", excludeResourcesPatterns ) ); + if (!excludeResourcesPatterns.isEmpty()) { + command.add("--exclude-resources=" + String.join(",", excludeResourcesPatterns)); } - if ( noHeaderFiles ) { - command.add( "--no-header-files" ); + if (noHeaderFiles) { + command.add("--no-header-files"); } - if ( noManPages ) { - command.add( "--no-man-pages" ); + if (noManPages) { + command.add("--no-man-pages"); } - if ( bindServices ) { - command.add( "--bind-services" ); + if (bindServices) { + command.add("--bind-services"); } - log.debug( "Running jlink: " + String.join( " ", command ) ); + log.debug("Running jlink: " + String.join(" ", command)); - ProcessExecutor.run( "jlink", command, log ); + ProcessExecutor.run("jlink", command, log); } } diff --git a/core/src/main/java/org/moditect/commands/GenerateModuleInfo.java b/core/src/main/java/org/moditect/commands/GenerateModuleInfo.java index 38732e6..008fd17 100644 --- a/core/src/main/java/org/moditect/commands/GenerateModuleInfo.java +++ b/core/src/main/java/org/moditect/commands/GenerateModuleInfo.java @@ -26,8 +26,8 @@ import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -56,9 +56,9 @@ import com.github.javaparser.ast.modules.ModuleDeclaration; import com.github.javaparser.ast.modules.ModuleExportsDirective; import com.github.javaparser.ast.modules.ModuleOpensDirective; +import com.github.javaparser.ast.modules.ModuleProvidesDirective; import com.github.javaparser.ast.modules.ModuleRequiresDirective; import com.github.javaparser.ast.modules.ModuleUsesDirective; -import com.github.javaparser.ast.modules.ModuleProvidesDirective; import static com.github.javaparser.StaticJavaParser.parseName; @@ -84,25 +84,24 @@ public class GenerateModuleInfo { private ToolProvider jdeps; public GenerateModuleInfo( - Path inputJar, String moduleName, boolean open, - Set dependencies, List exportPatterns, - List opensPatterns, List requiresPatterns, - Path workingDirectory, Path outputDirectory, - Set opensResources, Set uses, Set provides, - boolean addServiceUses, List jdepsExtraArgs, Log log - ) { + Path inputJar, String moduleName, boolean open, + Set dependencies, List exportPatterns, + List opensPatterns, List requiresPatterns, + Path workingDirectory, Path outputDirectory, + Set opensResources, Set uses, Set provides, + boolean addServiceUses, List jdepsExtraArgs, Log log) { String autoModuleNameForInputJar = DependencyDescriptor.getAutoModuleNameFromInputJar(inputJar, null); // if no valid auto module name can be derived for the input JAR, create a copy of it and // inject the target module name into the manifest ("Automatic-Module-Name"), as otherwise // jdeps will fail (issue #37) - if ( autoModuleNameForInputJar != null ) { + if (autoModuleNameForInputJar != null) { this.autoModuleNameForInputJar = autoModuleNameForInputJar; this.inputJar = inputJar; } else { this.autoModuleNameForInputJar = moduleName; - this.inputJar = createCopyWithAutoModuleNameManifestHeader( workingDirectory, inputJar, moduleName ); + this.inputJar = createCopyWithAutoModuleNameManifestHeader(workingDirectory, inputJar, moduleName); } this.moduleName = moduleName; @@ -117,62 +116,62 @@ public GenerateModuleInfo( this.uses = uses; this.provides = provides; this.addServiceUses = addServiceUses; - this.serviceLoaderUseScanner = new ServiceLoaderUseScanner( log ); + this.serviceLoaderUseScanner = new ServiceLoaderUseScanner(log); this.jdepsExtraArgs = jdepsExtraArgs != null ? jdepsExtraArgs : Collections.emptyList(); this.log = log; - Optional jdeps = ToolProvider.findFirst( "jdeps" ); + Optional jdeps = ToolProvider.findFirst("jdeps"); - if ( jdeps.isPresent() ) { + if (jdeps.isPresent()) { this.jdeps = jdeps.get(); } else { - throw new RuntimeException( "jdeps tool not found" ); + throw new RuntimeException("jdeps tool not found"); } } public static Path createCopyWithAutoModuleNameManifestHeader(Path workingDirectory, Path inputJar, String moduleName) { - if ( moduleName == null ) { - throw new IllegalArgumentException( "No automatic name can be derived for the JAR " + inputJar + ", hence an explicit module name is required" ); + if (moduleName == null) { + throw new IllegalArgumentException("No automatic name can be derived for the JAR " + inputJar + ", hence an explicit module name is required"); } - Path copiedJar = createCopy( workingDirectory, inputJar ); + Path copiedJar = createCopy(workingDirectory, inputJar); Map env = new HashMap<>(); - env.put( "create", "true" ); - URI uri = URI.create( "jar:" + copiedJar.toUri().toString() ); + env.put("create", "true"); + URI uri = URI.create("jar:" + copiedJar.toUri().toString()); - try ( FileSystem zipfs = FileSystems.newFileSystem( uri, env ); - ByteArrayOutputStream baos = new ByteArrayOutputStream() ) { + try (FileSystem zipfs = FileSystems.newFileSystem(uri, env); + ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - Manifest manifest = getManifest( inputJar ); - manifest.getMainAttributes().putValue( "Automatic-Module-Name", moduleName ); + Manifest manifest = getManifest(inputJar); + manifest.getMainAttributes().putValue("Automatic-Module-Name", moduleName); - manifest.write( baos ); - Files.write( zipfs.getPath( "META-INF", "MANIFEST.MF" ), baos.toByteArray() ); + manifest.write(baos); + Files.write(zipfs.getPath("META-INF", "MANIFEST.MF"), baos.toByteArray()); return copiedJar; } - catch(IOException ioe) { - throw new RuntimeException( "Couldn't inject automatic module name into manifest", ioe ); + catch (IOException ioe) { + throw new RuntimeException("Couldn't inject automatic module name into manifest", ioe); } } private static Path createCopy(Path workingDirectory, Path inputJar) { try { - Path tempDir = Files.createTempDirectory( workingDirectory, null ); - Path copiedJar = tempDir.resolve( inputJar.getFileName() ); - Files.copy( inputJar, copiedJar ); + Path tempDir = Files.createTempDirectory(workingDirectory, null); + Path copiedJar = tempDir.resolve(inputJar.getFileName()); + Files.copy(inputJar, copiedJar); return copiedJar; } catch (IOException ieo) { - throw new RuntimeException( ieo ); + throw new RuntimeException(ieo); } } private static Manifest getManifest(Path inputJar) throws IOException { - try ( JarInputStream jar = new JarInputStream( Files.newInputStream( inputJar ) ) ) { + try (JarInputStream jar = new JarInputStream(Files.newInputStream(inputJar))) { Manifest manifest = jar.getManifest(); return manifest != null ? manifest : new Manifest(); @@ -180,59 +179,59 @@ private static Manifest getManifest(Path inputJar) throws IOException { } public GeneratedModuleInfo run() { - if ( Files.isDirectory( inputJar ) ) { - throw new IllegalArgumentException( "Input JAR must not be a directory" ); + if (Files.isDirectory(inputJar)) { + throw new IllegalArgumentException("Input JAR must not be a directory"); } - if ( !Files.exists( workingDirectory ) ) { - throw new IllegalArgumentException( "Working directory doesn't exist: " + workingDirectory ); + if (!Files.exists(workingDirectory)) { + throw new IllegalArgumentException("Working directory doesn't exist: " + workingDirectory); } - if ( !Files.exists( outputDirectory ) ) { - throw new IllegalArgumentException( "Output directory doesn't exist: " + outputDirectory ); + if (!Files.exists(outputDirectory)) { + throw new IllegalArgumentException("Output directory doesn't exist: " + outputDirectory); } Map optionalityPerModule = generateModuleInfo(); ModuleDeclaration moduleDeclaration = parseGeneratedModuleInfo(); - updateModuleInfo( optionalityPerModule, moduleDeclaration ); + updateModuleInfo(optionalityPerModule, moduleDeclaration); - return writeModuleInfo( moduleDeclaration ); + return writeModuleInfo(moduleDeclaration); } private void updateModuleInfo(Map optionalityPerModule, ModuleDeclaration moduleDeclaration) { - if ( open ) { - moduleDeclaration.setOpen( true ); + if (open) { + moduleDeclaration.setOpen(true); } - List requiresStatements = moduleDeclaration.findAll( ModuleRequiresDirective.class ); + List requiresStatements = moduleDeclaration.findAll(ModuleRequiresDirective.class); - for ( ModuleRequiresDirective moduleRequiresDirective : requiresStatements ) { - if ( Boolean.TRUE.equals( optionalityPerModule.get( moduleRequiresDirective.getNameAsString() ) ) ) { - moduleRequiresDirective.addModifier( Modifier.Keyword.STATIC ); + for (ModuleRequiresDirective moduleRequiresDirective : requiresStatements) { + if (Boolean.TRUE.equals(optionalityPerModule.get(moduleRequiresDirective.getNameAsString()))) { + moduleRequiresDirective.addModifier(Modifier.Keyword.STATIC); } // update any requires clauses to modules modularized with us to use the assigned module // name instead of the automatic module name - for ( DependencyDescriptor dependency : dependencies ) { - if ( dependency.getOriginalModuleName().equals( moduleRequiresDirective.getNameAsString() ) && dependency.getAssignedModuleName() != null ) { - moduleRequiresDirective.setName( dependency.getAssignedModuleName() ); + for (DependencyDescriptor dependency : dependencies) { + if (dependency.getOriginalModuleName().equals(moduleRequiresDirective.getNameAsString()) && dependency.getAssignedModuleName() != null) { + moduleRequiresDirective.setName(dependency.getAssignedModuleName()); } } - for ( DependencePattern dependence : requiresPatterns ) { - if ( dependence.matches( moduleRequiresDirective.getNameAsString() ) ) { - if ( !dependence.isInclusive() ) { - moduleDeclaration.remove( moduleRequiresDirective ); + for (DependencePattern dependence : requiresPatterns) { + if (dependence.matches(moduleRequiresDirective.getNameAsString())) { + if (!dependence.isInclusive()) { + moduleDeclaration.remove(moduleRequiresDirective); } - if ( dependence.isMatchAll() && dependence.getModifiers().isEmpty() ) { - moduleRequiresDirective.removeModifier(Modifier.Keyword.TRANSITIVE ); + if (dependence.isMatchAll() && dependence.getModifiers().isEmpty()) { + moduleRequiresDirective.removeModifier(Modifier.Keyword.TRANSITIVE); } else { moduleRequiresDirective.getModifiers().clear(); dependence.getModifiers() - .stream() - .map( m -> Modifier.Keyword.valueOf( m.toUpperCase( Locale.ENGLISH ) ) ) - .forEach( m -> moduleRequiresDirective.addModifier(m) ); + .stream() + .map(m -> Modifier.Keyword.valueOf(m.toUpperCase(Locale.ENGLISH))) + .forEach(m -> moduleRequiresDirective.addModifier(m)); } break; @@ -240,45 +239,37 @@ private void updateModuleInfo(Map optionalityPerModule, ModuleD } } - List exportStatements = moduleDeclaration.findAll( ModuleExportsDirective.class ); - for ( ModuleExportsDirective moduleExportsDirective : exportStatements ) { - applyExportPatterns( moduleDeclaration, moduleExportsDirective ); - applyOpensPatterns( moduleDeclaration, moduleExportsDirective ); + List exportStatements = moduleDeclaration.findAll(ModuleExportsDirective.class); + for (ModuleExportsDirective moduleExportsDirective : exportStatements) { + applyExportPatterns(moduleDeclaration, moduleExportsDirective); + applyOpensPatterns(moduleDeclaration, moduleExportsDirective); } - if ( moduleName != null ) { - moduleDeclaration.setName( moduleName ); + if (moduleName != null) { + moduleDeclaration.setName(moduleName); } - + opensResources.stream().forEach(resourcePackage -> moduleDeclaration.getDirectives().add( - new ModuleOpensDirective(parseName(resourcePackage), new NodeList<>()) - )); + new ModuleOpensDirective(parseName(resourcePackage), new NodeList<>()))); for (String usedService : uses) { - moduleDeclaration.getDirectives().add( new ModuleUsesDirective(parseName(usedService)) ); + moduleDeclaration.getDirectives().add(new ModuleUsesDirective(parseName(usedService))); } provides.stream().map( - providedService -> providedService.split("\\s+with\\s+") - ).forEach( - providedServiceArray -> moduleDeclaration.getDirectives().add( - new ModuleProvidesDirective( - parseName(providedServiceArray[0]), - NodeList.nodeList( - Arrays.stream( - providedServiceArray[1].split( "," ) - ).map( String::trim ).map(s -> parseName(s)).collect( - Collectors.toSet() - ) - ) - ) - ) - ); - - if ( addServiceUses ) { - Set usedServices = serviceLoaderUseScanner.getUsedServices( inputJar ); - for ( String usedService : usedServices ) { - moduleDeclaration.getDirectives().add( new ModuleUsesDirective(parseName(usedService)) ); + providedService -> providedService.split("\\s+with\\s+")).forEach( + providedServiceArray -> moduleDeclaration.getDirectives().add( + new ModuleProvidesDirective( + parseName(providedServiceArray[0]), + NodeList.nodeList( + Arrays.stream( + providedServiceArray[1].split(",")).map(String::trim).map(s -> parseName(s)).collect( + Collectors.toSet()))))); + + if (addServiceUses) { + Set usedServices = serviceLoaderUseScanner.getUsedServices(inputJar); + for (String usedService : usedServices) { + moduleDeclaration.getDirectives().add(new ModuleUsesDirective(parseName(usedService))); } } } @@ -286,17 +277,17 @@ private void updateModuleInfo(Map optionalityPerModule, ModuleD private ModuleDeclaration applyExportPatterns(ModuleDeclaration moduleDeclaration, ModuleExportsDirective moduleExportsDirective) { boolean foundMatchingPattern = false; - for (PackageNamePattern pattern : exportPatterns ) { - if ( pattern.matches( moduleExportsDirective.getNameAsString() ) ) { - if ( pattern.getKind() == Kind.INCLUSIVE ) { - if ( !pattern.getTargetModules().isEmpty() ) { - for (String module : pattern.getTargetModules() ) { - moduleExportsDirective.getModuleNames().add( parseName( module ) ); + for (PackageNamePattern pattern : exportPatterns) { + if (pattern.matches(moduleExportsDirective.getNameAsString())) { + if (pattern.getKind() == Kind.INCLUSIVE) { + if (!pattern.getTargetModules().isEmpty()) { + for (String module : pattern.getTargetModules()) { + moduleExportsDirective.getModuleNames().add(parseName(module)); } } } else { - moduleDeclaration.remove( moduleExportsDirective ); + moduleDeclaration.remove(moduleExportsDirective); } foundMatchingPattern = true; @@ -305,27 +296,27 @@ private ModuleDeclaration applyExportPatterns(ModuleDeclaration moduleDeclaratio } // remove export if not matched by any pattern - if ( !foundMatchingPattern ) { - moduleDeclaration.remove( moduleExportsDirective ); + if (!foundMatchingPattern) { + moduleDeclaration.remove(moduleExportsDirective); } return moduleDeclaration; } private ModuleDeclaration applyOpensPatterns(ModuleDeclaration moduleDeclaration, ModuleExportsDirective moduleExportsDirective) { - for (PackageNamePattern pattern : opensPatterns ) { - if ( pattern.matches( moduleExportsDirective.getNameAsString() ) ) { - if ( pattern.getKind() == Kind.INCLUSIVE ) { + for (PackageNamePattern pattern : opensPatterns) { + if (pattern.matches(moduleExportsDirective.getNameAsString())) { + if (pattern.getKind() == Kind.INCLUSIVE) { ModuleOpensDirective moduleOpensDirective = new ModuleOpensDirective(); - moduleOpensDirective.setName( moduleExportsDirective.getName() ); + moduleOpensDirective.setName(moduleExportsDirective.getName()); - if ( !pattern.getTargetModules().isEmpty() ) { - for (String module : pattern.getTargetModules() ) { - moduleOpensDirective.getModuleNames().add( parseName( module ) ); + if (!pattern.getTargetModules().isEmpty()) { + for (String module : pattern.getTargetModules()) { + moduleOpensDirective.getModuleNames().add(parseName(module)); } } - moduleDeclaration.getDirectives().add( moduleOpensDirective ); + moduleDeclaration.getDirectives().add(moduleOpensDirective); } break; @@ -340,51 +331,51 @@ private Map generateModuleInfo() throws AssertionError { List command = new ArrayList<>(); - command.add( "--generate-module-info" ); - command.add( workingDirectory.toString() ); + command.add("--generate-module-info"); + command.add(workingDirectory.toString()); - if ( !dependencies.isEmpty() ) { + if (!dependencies.isEmpty()) { StringBuilder modules = new StringBuilder(); StringBuilder modulePath = new StringBuilder(); boolean isFirst = true; - for ( DependencyDescriptor dependency : dependencies ) { - if ( isFirst ) { + for (DependencyDescriptor dependency : dependencies) { + if (isFirst) { isFirst = false; } else { - modules.append( "," ); - modulePath.append( File.pathSeparator ); + modules.append(","); + modulePath.append(File.pathSeparator); } String moduleName = DependencyDescriptor.getAutoModuleNameFromInputJar(dependency.getPath(), dependency.getAssignedModuleName()); - modules.append( moduleName ); - optionalityPerModule.put( moduleName, dependency.isOptional() ); - modulePath.append( dependency.getPath() ); + modules.append(moduleName); + optionalityPerModule.put(moduleName, dependency.isOptional()); + modulePath.append(dependency.getPath()); } - command.add( "--add-modules" ); - command.add( modules.toString() ); - command.add( "--module-path" ); - command.add( modulePath.toString() ); + command.add("--add-modules"); + command.add(modules.toString()); + command.add("--module-path"); + command.add(modulePath.toString()); } - command.addAll( jdepsExtraArgs ); - command.add( inputJar.toString() ); + command.addAll(jdepsExtraArgs); + command.add(inputJar.toString()); - log.info( "Running jdeps " + String.join( " ", command ) ); + log.info("Running jdeps " + String.join(" ", command)); LogWriter out = new LogWriter(log); - int result = jdeps.run( out, out, command.toArray( new String[0] ) ); + int result = jdeps.run(out, out, command.toArray(new String[0])); if (result != 0) { - throw new IllegalStateException("Invocation of jdeps failed: jdeps " + String.join( " ", command ) ); + throw new IllegalStateException("Invocation of jdeps failed: jdeps " + String.join(" ", command)); } return optionalityPerModule; } private ModuleDeclaration parseGeneratedModuleInfo() { - Path moduleDir = workingDirectory.resolve( autoModuleNameForInputJar ); + Path moduleDir = workingDirectory.resolve(autoModuleNameForInputJar); Path moduleInfo = moduleDir.resolve("module-info.java"); // JDK 11.0.11+ and 14+ put module-info.java in versions/ @@ -398,49 +389,49 @@ private ModuleDeclaration parseGeneratedModuleInfo() { } } - return ModuleInfoCompiler.parseModuleInfo( moduleInfo ); + return ModuleInfoCompiler.parseModuleInfo(moduleInfo); } private GeneratedModuleInfo writeModuleInfo(ModuleDeclaration moduleDeclaration) { - Path outputModuleInfo = recreateDirectory( outputDirectory, moduleDeclaration.getNameAsString() ) - .resolve( "module-info.java" ); + Path outputModuleInfo = recreateDirectory(outputDirectory, moduleDeclaration.getNameAsString()) + .resolve("module-info.java"); try { - Files.write( outputModuleInfo, moduleDeclaration.toString().getBytes() ); + Files.write(outputModuleInfo, moduleDeclaration.toString().getBytes()); - log.info( "Created module descriptor at " + outputModuleInfo ); + log.info("Created module descriptor at " + outputModuleInfo); } catch (IOException e) { - throw new RuntimeException( "Couldn't write module-info.java", e ); + throw new RuntimeException("Couldn't write module-info.java", e); } - return new GeneratedModuleInfo( moduleDeclaration.getNameAsString(), outputModuleInfo ); + return new GeneratedModuleInfo(moduleDeclaration.getNameAsString(), outputModuleInfo); } private Path recreateDirectory(Path parent, String directoryName) { - Path dir = parent.resolve( directoryName ); + Path dir = parent.resolve(directoryName); try { - if ( Files.exists( dir ) ) { - Files.walkFileTree( dir, new SimpleFileVisitor() { + if (Files.exists(dir)) { + Files.walkFileTree(dir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete( file ); + Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - Files.delete( dir ); + Files.delete(dir); return FileVisitResult.CONTINUE; } }); } - Files.createDirectory( dir ); + Files.createDirectory(dir); } catch (IOException e) { - throw new RuntimeException( "Couldn't recreate directory " + dir, e ); + throw new RuntimeException("Couldn't recreate directory " + dir, e); } return dir; diff --git a/core/src/main/java/org/moditect/commands/GenerateModuleList.java b/core/src/main/java/org/moditect/commands/GenerateModuleList.java index 2f0fb9f..8e88e07 100644 --- a/core/src/main/java/org/moditect/commands/GenerateModuleList.java +++ b/core/src/main/java/org/moditect/commands/GenerateModuleList.java @@ -15,10 +15,6 @@ */ package org.moditect.commands; -import org.moditect.internal.command.LogWriter; -import org.moditect.model.Version; -import org.moditect.spi.log.Log; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; @@ -29,59 +25,63 @@ import java.util.spi.ToolProvider; import java.util.stream.Collectors; +import org.moditect.internal.command.LogWriter; +import org.moditect.model.Version; +import org.moditect.spi.log.Log; + public class GenerateModuleList { - private final Path projectJar; - private final Set dependencies; - private final Version jvmVersion; - private final Log log; + private final Path projectJar; + private final Set dependencies; + private final Version jvmVersion; + private final Log log; - private final ToolProvider jdeps; + private final ToolProvider jdeps; - public GenerateModuleList(Path projectJar, Set dependencies, Version jvmVersion, Log log) { - this.projectJar = projectJar; - this.dependencies = dependencies; - this.jvmVersion = jvmVersion; - this.log = log; + public GenerateModuleList(Path projectJar, Set dependencies, Version jvmVersion, Log log) { + this.projectJar = projectJar; + this.dependencies = dependencies; + this.jvmVersion = jvmVersion; + this.log = log; - this.jdeps = ToolProvider - .findFirst( "jdeps" ) - .orElseThrow(() -> new RuntimeException("jdeps tool not found")); - } + this.jdeps = ToolProvider + .findFirst("jdeps") + .orElseThrow(() -> new RuntimeException("jdeps tool not found")); + } - public void run() { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - PrintStream out = new PrintStream(outStream); - jdeps.run(out , System.err, "--version"); - out.close(); - int jdepsVersion = Runtime.Version - .parse(outStream.toString().strip()) - .feature(); - if (jdepsVersion < 12) { - log.error("The jdeps option this plugin uses to list JDK modules only works flawlessly on JDK 12+, so please use that to run this goal."); - return; - } + public void run() { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(outStream); + jdeps.run(out, System.err, "--version"); + out.close(); + int jdepsVersion = Runtime.Version + .parse(outStream.toString().strip()) + .feature(); + if (jdepsVersion < 12) { + log.error("The jdeps option this plugin uses to list JDK modules only works flawlessly on JDK 12+, so please use that to run this goal."); + return; + } - List command = new ArrayList<>(); - command.add("--print-module-deps"); - command.add("--ignore-missing-deps"); - command.add("--multi-release"); - command.add(String.valueOf(jvmVersion.feature())); - command.add("--class-path"); - String classPath = dependencies.stream() - .map(Path::toAbsolutePath) - .map(Path::toString) - .collect(Collectors.joining(File.pathSeparator)); - command.add(classPath); - command.add(projectJar.toAbsolutePath().toString()); + List command = new ArrayList<>(); + command.add("--print-module-deps"); + command.add("--ignore-missing-deps"); + command.add("--multi-release"); + command.add(String.valueOf(jvmVersion.feature())); + command.add("--class-path"); + String classPath = dependencies.stream() + .map(Path::toAbsolutePath) + .map(Path::toString) + .collect(Collectors.joining(File.pathSeparator)); + command.add(classPath); + command.add(projectJar.toAbsolutePath().toString()); - log.debug( "Running jdeps " + String.join( " ", command ) ); + log.debug("Running jdeps " + String.join(" ", command)); - LogWriter logWriter = new LogWriter(log); - int result = jdeps.run( logWriter, logWriter, command.toArray( new String[0] ) ); - if (result != 0) { - throw new IllegalStateException("Invocation of jdeps failed: jdeps " + String.join( " ", command ) ); - } - } + LogWriter logWriter = new LogWriter(log); + int result = jdeps.run(logWriter, logWriter, command.toArray(new String[0])); + if (result != 0) { + throw new IllegalStateException("Invocation of jdeps failed: jdeps " + String.join(" ", command)); + } + } } diff --git a/core/src/main/java/org/moditect/internal/analyzer/ServiceLoaderUseScanner.java b/core/src/main/java/org/moditect/internal/analyzer/ServiceLoaderUseScanner.java index 713beb2..b2483b7 100644 --- a/core/src/main/java/org/moditect/internal/analyzer/ServiceLoaderUseScanner.java +++ b/core/src/main/java/org/moditect/internal/analyzer/ServiceLoaderUseScanner.java @@ -41,13 +41,13 @@ public ServiceLoaderUseScanner(Log log) { public Set getUsedServices(Path jar) { Set usedServices = new HashSet<>(); - try (JarFile jarFile = new JarFile( jar.toFile() ) ) { + try (JarFile jarFile = new JarFile(jar.toFile())) { jarFile.stream() - .filter( je -> !je.isDirectory() && je.getName().endsWith( ".class" ) ) - .forEach( je -> usedServices.addAll( getUsedServices( jarFile, je ) ) ); + .filter(je -> !je.isDirectory() && je.getName().endsWith(".class")) + .forEach(je -> usedServices.addAll(getUsedServices(jarFile, je))); } catch (IOException e) { - throw new RuntimeException( "Couldn't open or close JAR file " + jar, e ); + throw new RuntimeException("Couldn't open or close JAR file " + jar, e); } return usedServices; @@ -56,9 +56,9 @@ public Set getUsedServices(Path jar) { private Set getUsedServices(JarFile jarFile, JarEntry je) { Set usedServices = new HashSet<>(); - try ( InputStream classFile = jarFile.getInputStream( je ) ) { - new ClassReader( classFile ).accept( - new ClassVisitor( Opcodes.ASM9 ) { + try (InputStream classFile = jarFile.getInputStream(je)) { + new ClassReader(classFile).accept( + new ClassVisitor(Opcodes.ASM9) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { @@ -69,31 +69,30 @@ public MethodVisitor visitMethod(int access, String name, String desc, String si @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { - if ( owner.equals( "java/util/ServiceLoader" ) && name.equals( "load" ) ) { - if ( lastType == null ) { + if (owner.equals("java/util/ServiceLoader") && name.equals("load")) { + if (lastType == null) { // TODO Log class/method - log.warn( "Cannot derive uses clause from service loader invocation with non constant class literal" ); + log.warn("Cannot derive uses clause from service loader invocation with non constant class literal"); } else { - usedServices.add( lastType.getClassName() ); + usedServices.add(lastType.getClassName()); } } } @Override public void visitLdcInsn(Object cst) { - if ( cst instanceof Type ) { + if (cst instanceof Type) { lastType = (Type) cst; } }; }; } }, - 0 - ); + 0); } catch (IOException e) { - throw new RuntimeException( e ); + throw new RuntimeException(e); } return usedServices; diff --git a/core/src/main/java/org/moditect/internal/command/LogWriter.java b/core/src/main/java/org/moditect/internal/command/LogWriter.java index 9aada32..94636a9 100644 --- a/core/src/main/java/org/moditect/internal/command/LogWriter.java +++ b/core/src/main/java/org/moditect/internal/command/LogWriter.java @@ -27,7 +27,7 @@ */ public class LogWriter extends PrintWriter { - private static final String ERROR_PREFIX = "Error:"; + private static final String ERROR_PREFIX = "Error:"; private static final String WARNING_PREFIX = "Warning:"; private final Log log; diff --git a/core/src/main/java/org/moditect/internal/command/ProcessExecutor.java b/core/src/main/java/org/moditect/internal/command/ProcessExecutor.java index f3caf1c..920966f 100644 --- a/core/src/main/java/org/moditect/internal/command/ProcessExecutor.java +++ b/core/src/main/java/org/moditect/internal/command/ProcessExecutor.java @@ -31,41 +31,41 @@ public class ProcessExecutor { public static void run(String name, List command, Log log) { - ProcessBuilder builder = new ProcessBuilder( command ); + ProcessBuilder builder = new ProcessBuilder(command); Process process; List outputLines = new ArrayList<>(); try { process = builder.start(); - BufferedReader in = new BufferedReader( new InputStreamReader( process.getInputStream() ) ); + BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; - while ( ( line = in.readLine() ) != null ) { - outputLines.add( line ); - log.debug( line ); + while ((line = in.readLine()) != null) { + outputLines.add(line); + log.debug(line); } - BufferedReader err = new BufferedReader( new InputStreamReader( process.getErrorStream() ) ); - while ( ( line = err.readLine() ) != null ) { - log.error( line ); + BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); + while ((line = err.readLine()) != null) { + log.error(line); } process.waitFor(); } catch (IOException | InterruptedException e) { - for ( String line : outputLines ) { - log.error( line ); + for (String line : outputLines) { + log.error(line); } - throw new RuntimeException( "Couldn't run " + name, e ); + throw new RuntimeException("Couldn't run " + name, e); } - if ( process.exitValue() != 0 ) { - for ( String line : outputLines ) { - log.error( line ); + if (process.exitValue() != 0) { + for (String line : outputLines) { + log.error(line); } - throw new RuntimeException( "Execution of " + name + " failed" ); + throw new RuntimeException("Execution of " + name + " failed"); } } } diff --git a/core/src/main/java/org/moditect/internal/compiler/ModuleInfoCompiler.java b/core/src/main/java/org/moditect/internal/compiler/ModuleInfoCompiler.java index 3c73ea5..cc5d629 100644 --- a/core/src/main/java/org/moditect/internal/compiler/ModuleInfoCompiler.java +++ b/core/src/main/java/org/moditect/internal/compiler/ModuleInfoCompiler.java @@ -15,25 +15,15 @@ */ package org.moditect.internal.compiler; -import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; -import static org.objectweb.asm.Opcodes.ACC_MANDATED; -import static org.objectweb.asm.Opcodes.ACC_MODULE; -import static org.objectweb.asm.Opcodes.ACC_OPEN; -import static org.objectweb.asm.Opcodes.ACC_STATIC_PHASE; -import static org.objectweb.asm.Opcodes.ACC_SYNTHETIC; -import static org.objectweb.asm.Opcodes.ACC_TRANSITIVE; -import static org.objectweb.asm.Opcodes.V9; - import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.Iterator; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.nodeTypes.NodeWithModifiers; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ModuleVisitor; +import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.expr.Name; @@ -43,90 +33,96 @@ import com.github.javaparser.ast.modules.ModuleProvidesDirective; import com.github.javaparser.ast.modules.ModuleRequiresDirective; import com.github.javaparser.ast.modules.ModuleUsesDirective; +import com.github.javaparser.ast.nodeTypes.NodeWithModifiers; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static org.objectweb.asm.Opcodes.ACC_MANDATED; +import static org.objectweb.asm.Opcodes.ACC_MODULE; +import static org.objectweb.asm.Opcodes.ACC_OPEN; +import static org.objectweb.asm.Opcodes.ACC_STATIC_PHASE; +import static org.objectweb.asm.Opcodes.ACC_SYNTHETIC; +import static org.objectweb.asm.Opcodes.ACC_TRANSITIVE; +import static org.objectweb.asm.Opcodes.V9; public class ModuleInfoCompiler { static { - StaticJavaParser.getConfiguration().setLanguageLevel(JAVA_9 ); + StaticJavaParser.getConfiguration().setLanguageLevel(JAVA_9); } public static ModuleDeclaration parseModuleInfo(Path moduleInfo) { CompilationUnit ast; try { - ast = StaticJavaParser.parse( moduleInfo ); + ast = StaticJavaParser.parse(moduleInfo); } catch (IOException e) { - throw new RuntimeException( "Couldn't parse " + moduleInfo, e ); + throw new RuntimeException("Couldn't parse " + moduleInfo, e); } return ast.getModule() - .orElseThrow( () -> new IllegalArgumentException( "Not a module-info.java: " + moduleInfo ) ); + .orElseThrow(() -> new IllegalArgumentException("Not a module-info.java: " + moduleInfo)); } public static ModuleDeclaration parseModuleInfo(String moduleInfoSource) { - CompilationUnit ast = StaticJavaParser.parse( moduleInfoSource ); + CompilationUnit ast = StaticJavaParser.parse(moduleInfoSource); return ast.getModule() - .orElseThrow( () -> new IllegalArgumentException( "Not a module-info.java: " + moduleInfoSource ) ); + .orElseThrow(() -> new IllegalArgumentException("Not a module-info.java: " + moduleInfoSource)); } public static byte[] compileModuleInfo(ModuleDeclaration module, String mainClass, String version) { - ClassWriter classWriter = new ClassWriter( 0 ); - classWriter.visit( V9, ACC_MODULE, "module-info", null, null, null ); + ClassWriter classWriter = new ClassWriter(0); + classWriter.visit(V9, ACC_MODULE, "module-info", null, null, null); int moduleAccess = module.isOpen() ? ACC_SYNTHETIC | ACC_OPEN : ACC_SYNTHETIC; - ModuleVisitor mv = classWriter.visitModule( module.getNameAsString(), moduleAccess, version ); + ModuleVisitor mv = classWriter.visitModule(module.getNameAsString(), moduleAccess, version); - if ( mainClass != null ) { - mv.visitMainClass( getNameForBinary( mainClass ) ); + if (mainClass != null) { + mv.visitMainClass(getNameForBinary(mainClass)); } - for ( ModuleRequiresDirective requires : module.findAll( ModuleRequiresDirective.class ) ) { + for (ModuleRequiresDirective requires : module.findAll(ModuleRequiresDirective.class)) { mv.visitRequire( - requires.getName().asString(), - requiresModifiersAsInt( requires ), - null - ); + requires.getName().asString(), + requiresModifiersAsInt(requires), + null); } - for ( ModuleExportsDirective export : module.findAll( ModuleExportsDirective.class ) ) { + for (ModuleExportsDirective export : module.findAll(ModuleExportsDirective.class)) { mv.visitExport( - getNameForBinary( export.getNameAsString() ), + getNameForBinary(export.getNameAsString()), 0, export.getModuleNames() - .stream() - .map( Name::toString ) - .toArray( String[]::new ) - ); + .stream() + .map(Name::toString) + .toArray(String[]::new)); } - for ( ModuleProvidesDirective provides : module.findAll( ModuleProvidesDirective.class ) ) { + for (ModuleProvidesDirective provides : module.findAll(ModuleProvidesDirective.class)) { mv.visitProvide( - getNameForBinary( provides.getName() ), - provides.getWith() - .stream() - .map( ModuleInfoCompiler::getNameForBinary ) - .toArray( String[]::new ) - ); + getNameForBinary(provides.getName()), + provides.getWith() + .stream() + .map(ModuleInfoCompiler::getNameForBinary) + .toArray(String[]::new)); } - for ( ModuleUsesDirective uses : module.findAll( ModuleUsesDirective.class ) ) { - mv.visitUse( getNameForBinary( uses.getName() ) ); + for (ModuleUsesDirective uses : module.findAll(ModuleUsesDirective.class)) { + mv.visitUse(getNameForBinary(uses.getName())); } - for ( ModuleOpensDirective opens : module.findAll( ModuleOpensDirective.class ) ) { + for (ModuleOpensDirective opens : module.findAll(ModuleOpensDirective.class)) { mv.visitOpen( - getNameForBinary( opens.getNameAsString() ), + getNameForBinary(opens.getNameAsString()), 0, opens.getModuleNames() - .stream() - .map( Name::toString ) - .toArray( String[]::new ) - ); + .stream() + .map(Name::toString) + .toArray(String[]::new)); } - mv.visitRequire( "java.base", ACC_MANDATED, null ); + mv.visitRequire("java.base", ACC_MANDATED, null); mv.visitEnd(); classWriter.visitEnd(); @@ -135,25 +131,25 @@ public static byte[] compileModuleInfo(ModuleDeclaration module, String mainClas } private static String getNameForBinary(Name name) { - return getNameForBinary( name.asString() ); + return getNameForBinary(name.asString()); } private static String getNameForBinary(String typeName) { - Iterator parts = Arrays.asList( typeName.split( "\\." ) ).iterator(); + Iterator parts = Arrays.asList(typeName.split("\\.")).iterator(); StringBuilder typeNameForBinary = new StringBuilder(); - while ( parts.hasNext() ) { + while (parts.hasNext()) { String part = parts.next(); - typeNameForBinary.append( part ); + typeNameForBinary.append(part); // if the current part is upper-case, we assume it's a class and the following part is a nested class // that's as good as it gets without fully resolving all the type names against the module's classes - if ( parts.hasNext() ) { - if ( Character.isUpperCase( part.charAt(0) ) ) { - typeNameForBinary.append( "$" ); + if (parts.hasNext()) { + if (Character.isUpperCase(part.charAt(0))) { + typeNameForBinary.append("$"); } else { - typeNameForBinary.append( "/" ); + typeNameForBinary.append("/"); } } } @@ -164,10 +160,10 @@ private static String getNameForBinary(String typeName) { private static int requiresModifiersAsInt(NodeWithModifiers modifiers) { int result = 0; - if ( modifiers.hasModifier( Modifier.Keyword.STATIC ) ) { + if (modifiers.hasModifier(Modifier.Keyword.STATIC)) { result |= ACC_STATIC_PHASE; } - if ( modifiers.hasModifier( Modifier.Keyword.TRANSITIVE ) ) { + if (modifiers.hasModifier(Modifier.Keyword.TRANSITIVE)) { result |= ACC_TRANSITIVE; } diff --git a/core/src/main/java/org/moditect/internal/parser/JavaVersionHelper.java b/core/src/main/java/org/moditect/internal/parser/JavaVersionHelper.java index b2c5e4b..966e4dc 100644 --- a/core/src/main/java/org/moditect/internal/parser/JavaVersionHelper.java +++ b/core/src/main/java/org/moditect/internal/parser/JavaVersionHelper.java @@ -15,11 +15,11 @@ */ package org.moditect.internal.parser; -import org.moditect.spi.log.Log; - import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.moditect.spi.log.Log; + /** * Helper to extract and parse the current Java version to check if multi release path should be used or not. * @@ -81,7 +81,8 @@ Version javaVersion(String versionString) { debug("parsed.version -> " + version); return version; - } catch (IndexOutOfBoundsException | NumberFormatException ex) { + } + catch (IndexOutOfBoundsException | NumberFormatException ex) { error("The java version " + versionString + " has an invalid format. " + ex.getMessage()); return null; } @@ -119,9 +120,11 @@ private Version(int major, int minor, int mini) { int major() { return major; } + int minor() { return minor; } + int mini() { return mini; } diff --git a/core/src/main/java/org/moditect/internal/parser/JdepsExtraArgsExtractor.java b/core/src/main/java/org/moditect/internal/parser/JdepsExtraArgsExtractor.java index c3b1171..d6ceb7f 100644 --- a/core/src/main/java/org/moditect/internal/parser/JdepsExtraArgsExtractor.java +++ b/core/src/main/java/org/moditect/internal/parser/JdepsExtraArgsExtractor.java @@ -15,11 +15,10 @@ */ package org.moditect.internal.parser; -import org.moditect.spi.log.Log; - import java.util.List; import java.util.Optional; -import java.util.jar.JarFile; + +import org.moditect.spi.log.Log; public final class JdepsExtraArgsExtractor { @@ -66,7 +65,7 @@ private Optional extractVersionFromSameArgument(String multiReleaseArgu return Optional.empty(); } - String versionString = multiReleaseArgument.substring(MULTI_RELEASE_ARGUMENT.length()+1); + String versionString = multiReleaseArgument.substring(MULTI_RELEASE_ARGUMENT.length() + 1); debug("Version extracted from the same argument: " + versionString); return parseVersionNumber(versionString); } @@ -81,7 +80,8 @@ private Optional parseVersionNumber(String versionString) { } try { return Optional.of(Integer.parseInt(versionString)); - } catch (NumberFormatException ex) { + } + catch (NumberFormatException ex) { error("Invalid argument value for " + MULTI_RELEASE_ARGUMENT + ": " + versionString); return Optional.empty(); } diff --git a/core/src/main/java/org/moditect/model/DependencePattern.java b/core/src/main/java/org/moditect/model/DependencePattern.java index 99dfaca..5bb1ffa 100644 --- a/core/src/main/java/org/moditect/model/DependencePattern.java +++ b/core/src/main/java/org/moditect/model/DependencePattern.java @@ -32,35 +32,35 @@ */ public class DependencePattern { - private static final Pattern PATTERN = Pattern.compile( "((.*)\\s+)?(.*?)" ); + private static final Pattern PATTERN = Pattern.compile("((.*)\\s+)?(.*?)"); private final boolean inclusive; private final Pattern pattern; private final Set modifiers; public static List parsePatterns(String patterns) { - if ( patterns == null ) { + if (patterns == null) { return Collections.emptyList(); } - return Arrays.stream( patterns.trim().split(";") ) - .map( DependencePattern::parsePattern ) - .collect( Collectors.toList() ); + return Arrays.stream(patterns.trim().split(";")) + .map(DependencePattern::parsePattern) + .collect(Collectors.toList()); } public static DependencePattern parsePattern(String pattern) { pattern = pattern.trim(); - Matcher matcher = PATTERN.matcher( pattern ); - if ( !matcher.matches() ) { - throw new IllegalArgumentException( "Invalid dependence pattern: " + pattern ); + Matcher matcher = PATTERN.matcher(pattern); + if (!matcher.matches()) { + throw new IllegalArgumentException("Invalid dependence pattern: " + pattern); } else { - if ( matcher.group( 3 ) != null ) { - return new DependencePattern( matcher.group( 3 ), matcher.group( 2 ) ); + if (matcher.group(3) != null) { + return new DependencePattern(matcher.group(3), matcher.group(2)); } else { - return new DependencePattern( matcher.group( 2 ), null ); + return new DependencePattern(matcher.group(2), null); } } } @@ -74,20 +74,20 @@ private DependencePattern(String pattern, String modifiers) { this.inclusive = true; } - this.pattern = Pattern.compile( pattern.replace( ".", "\\." ).replace( "*", ".*" ) ); + this.pattern = Pattern.compile(pattern.replace(".", "\\.").replace("*", ".*")); - if ( modifiers == null ) { + if (modifiers == null) { this.modifiers = Collections.emptySet(); } else { - this.modifiers = Arrays.stream( modifiers.split( "\\s" ) ) - .map( String::trim ) - .collect( Collectors.toSet() ); + this.modifiers = Arrays.stream(modifiers.split("\\s")) + .map(String::trim) + .collect(Collectors.toSet()); } } - public boolean matches(String packageName ) { - return pattern.matcher( packageName ).matches(); + public boolean matches(String packageName) { + return pattern.matcher(packageName).matches(); } public Pattern getPattern() { @@ -99,7 +99,7 @@ public Set getModifiers() { } public boolean isMatchAll() { - return ".*".equals( pattern.pattern() ); + return ".*".equals(pattern.pattern()); } public boolean isInclusive() { diff --git a/core/src/main/java/org/moditect/model/DependencyDescriptor.java b/core/src/main/java/org/moditect/model/DependencyDescriptor.java index 0d27e1a..5c0207c 100644 --- a/core/src/main/java/org/moditect/model/DependencyDescriptor.java +++ b/core/src/main/java/org/moditect/model/DependencyDescriptor.java @@ -38,7 +38,7 @@ public DependencyDescriptor(Path path, boolean optional, String assignedModuleNa this.path = path; this.optional = optional; this.originalModuleName = getAutoModuleNameFromInputJar(path, assignedModuleName); - if(this.originalModuleName == null) { + if (this.originalModuleName == null) { throw new IllegalArgumentException("No assignedModuleName provided for jar with invalid module name: " + path); } this.assignedModuleName = assignedModuleName; @@ -46,7 +46,7 @@ public DependencyDescriptor(Path path, boolean optional, String assignedModuleNa public static String getAutoModuleNameFromInputJar(Path path, String invalidModuleName) { try { - return ModuleFinder.of( path ) + return ModuleFinder.of(path) .findAll() .iterator() .next() @@ -54,7 +54,7 @@ public static String getAutoModuleNameFromInputJar(Path path, String invalidModu .name(); } catch (FindException e) { - if ( e.getCause() != null && e.getCause().getMessage().contains( "Invalid module name" ) ) { + if (e.getCause() != null && e.getCause().getMessage().contains("Invalid module name")) { return invalidModuleName; } throw e; @@ -87,18 +87,19 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if ( this == obj ) + if (this == obj) return true; - if ( obj == null ) + if (obj == null) return false; - if ( getClass() != obj.getClass() ) + if (getClass() != obj.getClass()) return false; DependencyDescriptor other = (DependencyDescriptor) obj; - return path.equals( other.path ); + return path.equals(other.path); } @Override public String toString() { - return "DependencyDescriptor [path=" + path + ", optional=" + optional + ", originalModuleName=" + originalModuleName + ", assignedModuleName=" + assignedModuleName + "]"; + return "DependencyDescriptor [path=" + path + ", optional=" + optional + ", originalModuleName=" + originalModuleName + ", assignedModuleName=" + + assignedModuleName + "]"; } } diff --git a/core/src/main/java/org/moditect/model/JarInclusionPolicy.java b/core/src/main/java/org/moditect/model/JarInclusionPolicy.java index 8d2ed3a..db7c691 100644 --- a/core/src/main/java/org/moditect/model/JarInclusionPolicy.java +++ b/core/src/main/java/org/moditect/model/JarInclusionPolicy.java @@ -16,13 +16,15 @@ package org.moditect.model; public enum JarInclusionPolicy { - NONE, APP, APP_WITH_DEPENDENCIES; + NONE, + APP, + APP_WITH_DEPENDENCIES; - public boolean includeAppJar() { - return this == APP || this == APP_WITH_DEPENDENCIES; - } + public boolean includeAppJar() { + return this == APP || this == APP_WITH_DEPENDENCIES; + } - public boolean includeDependencies() { - return this == APP_WITH_DEPENDENCIES; - } + public boolean includeDependencies() { + return this == APP_WITH_DEPENDENCIES; + } } diff --git a/core/src/main/java/org/moditect/model/PackageNamePattern.java b/core/src/main/java/org/moditect/model/PackageNamePattern.java index 4dcfc60..c97cc8d 100644 --- a/core/src/main/java/org/moditect/model/PackageNamePattern.java +++ b/core/src/main/java/org/moditect/model/PackageNamePattern.java @@ -29,43 +29,43 @@ public static enum Kind { EXCLUSIVE; } - private static final Pattern INCLUSIVE_PATTERN = Pattern.compile( "(.*?)((\\s*to\\s)(.*))?" ); - private static final Pattern EXCLUSIVE_PATTERN = Pattern.compile( "(!)(.*?)" ); - private static final Pattern MODULES_PATTERN = Pattern.compile( "\\s*,\\s*" ); + private static final Pattern INCLUSIVE_PATTERN = Pattern.compile("(.*?)((\\s*to\\s)(.*))?"); + private static final Pattern EXCLUSIVE_PATTERN = Pattern.compile("(!)(.*?)"); + private static final Pattern MODULES_PATTERN = Pattern.compile("\\s*,\\s*"); private final Kind kind; private final Pattern pattern; private final List targetModules; public static List parsePatterns(String patterns) { - if ( patterns == null ) { + if (patterns == null) { return Collections.emptyList(); } - return Arrays.stream( patterns.trim().split(";") ) - .map( PackageNamePattern::parsePattern ) - .collect( Collectors.toList() ); + return Arrays.stream(patterns.trim().split(";")) + .map(PackageNamePattern::parsePattern) + .collect(Collectors.toList()); } public static PackageNamePattern parsePattern(String pattern) { pattern = pattern.trim(); - if ( pattern.startsWith( "!") ) { - Matcher matcher = EXCLUSIVE_PATTERN.matcher( pattern ); - if ( !matcher.matches() ) { - throw new IllegalArgumentException( "Invalid exclusive pattern: " + pattern ); + if (pattern.startsWith("!")) { + Matcher matcher = EXCLUSIVE_PATTERN.matcher(pattern); + if (!matcher.matches()) { + throw new IllegalArgumentException("Invalid exclusive pattern: " + pattern); } else { - return exclusive( matcher.group( 2 ) ); + return exclusive(matcher.group(2)); } } else { - Matcher matcher = INCLUSIVE_PATTERN.matcher( pattern ); - if ( !matcher.matches() ) { - throw new IllegalArgumentException( "Invalid inclusive pattern: " + pattern ); + Matcher matcher = INCLUSIVE_PATTERN.matcher(pattern); + if (!matcher.matches()) { + throw new IllegalArgumentException("Invalid inclusive pattern: " + pattern); } else { - return inclusive( matcher.group( 1 ), matcher.group( 2 ) != null ? modules(matcher.group( 4 )) : Collections.emptyList() ); + return inclusive(matcher.group(1), matcher.group(2) != null ? modules(matcher.group(4)) : Collections.emptyList()); } } } @@ -75,21 +75,21 @@ private static List modules(String modules) { } private static PackageNamePattern inclusive(String pattern, List targetModules) { - return new PackageNamePattern( Kind.INCLUSIVE, pattern, targetModules ); + return new PackageNamePattern(Kind.INCLUSIVE, pattern, targetModules); } private static PackageNamePattern exclusive(String pattern) { - return new PackageNamePattern( Kind.EXCLUSIVE, pattern, Collections.emptyList() ); + return new PackageNamePattern(Kind.EXCLUSIVE, pattern, Collections.emptyList()); } private PackageNamePattern(Kind kind, String pattern, List targetModules) { this.kind = kind; - this.pattern = Pattern.compile( pattern.replace( ".", "\\." ).replace( "*", ".*" ) ); + this.pattern = Pattern.compile(pattern.replace(".", "\\.").replace("*", ".*")); this.targetModules = targetModules; } - public boolean matches(String packageName ) { - return pattern.matcher( packageName ).matches(); + public boolean matches(String packageName) { + return pattern.matcher(packageName).matches(); } public Kind getKind() { diff --git a/core/src/main/java/org/moditect/model/Version.java b/core/src/main/java/org/moditect/model/Version.java index c1052ef..abbbe7d 100644 --- a/core/src/main/java/org/moditect/model/Version.java +++ b/core/src/main/java/org/moditect/model/Version.java @@ -22,42 +22,42 @@ */ public class Version { - private final int feature; - - private Version(int feature) { - this.feature = feature; - } - - public static Version valueOf(int feature) { - return new Version(feature); - } - - public static Version valueOf(Object feature) { - return new Version(Integer.parseInt(String.valueOf(feature))); - } - - public int feature() { - return feature; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof Version)) - return false; - Version version = (Version) o; - return feature == version.feature; - } - - @Override - public int hashCode() { - return Objects.hash(feature); - } - - @Override - public String toString() { - return "Version " + feature; - } + private final int feature; + + private Version(int feature) { + this.feature = feature; + } + + public static Version valueOf(int feature) { + return new Version(feature); + } + + public static Version valueOf(Object feature) { + return new Version(Integer.parseInt(String.valueOf(feature))); + } + + public int feature() { + return feature; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof Version)) + return false; + Version version = (Version) o; + return feature == version.feature; + } + + @Override + public int hashCode() { + return Objects.hash(feature); + } + + @Override + public String toString() { + return "Version " + feature; + } } diff --git a/core/src/main/java/org/moditect/spi/log/Log.java b/core/src/main/java/org/moditect/spi/log/Log.java index 1ef4a5b..3c8f6d5 100644 --- a/core/src/main/java/org/moditect/spi/log/Log.java +++ b/core/src/main/java/org/moditect/spi/log/Log.java @@ -18,7 +18,10 @@ public interface Log { public void debug(CharSequence message); + public void info(CharSequence message); + public void warn(CharSequence message); + public void error(CharSequence message); } diff --git a/core/src/test/java/org/moditect/test/AddModuleInfoTest.java b/core/src/test/java/org/moditect/test/AddModuleInfoTest.java index e2fc571..b62a2d8 100644 --- a/core/src/test/java/org/moditect/test/AddModuleInfoTest.java +++ b/core/src/test/java/org/moditect/test/AddModuleInfoTest.java @@ -49,17 +49,17 @@ */ public class AddModuleInfoTest { - private static final Path GENERATED_TEST_RESOURCES = Paths.get( "target", "generated-test-resources" ); - private static final Path GENERATED_TEST_MODULES = Paths.get( "target", "generated-test-modules" ); + private static final Path GENERATED_TEST_RESOURCES = Paths.get("target", "generated-test-resources"); + private static final Path GENERATED_TEST_MODULES = Paths.get("target", "generated-test-modules"); @Before public void prepareDirectories() throws Exception { - truncateFolder( GENERATED_TEST_RESOURCES ); - truncateFolder( GENERATED_TEST_MODULES ); + truncateFolder(GENERATED_TEST_RESOURCES); + truncateFolder(GENERATED_TEST_MODULES); } private void truncateFolder(Path folder) throws Exception { - if ( Files.exists( folder ) ) { + if (Files.exists(folder)) { Files.walkFileTree(folder, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { @@ -67,9 +67,9 @@ public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IO return super.visitFile(path, attrs); } }); - Files.deleteIfExists( folder ); + Files.deleteIfExists(folder); } - Files.createDirectory( folder ); + Files.createDirectory(folder); } @Test @@ -82,13 +82,13 @@ public void addJvmVersionModuleInfoAndRunModular() throws Exception { File.separator + "java"; ProcessBuilder builder = new ProcessBuilder( - javaBin, "--module-path", GENERATED_TEST_RESOURCES + File.separator + "example.jar", "--module", "com.example" ) - .redirectOutput( Redirect.INHERIT ); + javaBin, "--module-path", GENERATED_TEST_RESOURCES + File.separator + "example.jar", "--module", "com.example") + .redirectOutput(Redirect.INHERIT); Process process = builder.start(); process.waitFor(); - if ( process.exitValue() == 0 ) { + if (process.exitValue() == 0) { throw new AssertionError(); } @@ -96,25 +96,24 @@ public void addJvmVersionModuleInfoAndRunModular() throws Exception { "module com.example {}", "com.example.HelloWorld", "1.42.3", - Paths.get( "target", "generated-test-resources", "example.jar" ), - Paths.get( "target", "generated-test-modules" ), + Paths.get("target", "generated-test-resources", "example.jar"), + Paths.get("target", "generated-test-modules"), "9", false, - null - ) - .run(); + null) + .run(); builder = new ProcessBuilder( - javaBin, "--module-path", GENERATED_TEST_MODULES + File.separator + "example.jar", "--module", "com.example" ); + javaBin, "--module-path", GENERATED_TEST_MODULES + File.separator + "example.jar", "--module", "com.example"); process = builder.start(); process.waitFor(); - if ( process.exitValue() != 0 ) { + if (process.exitValue() != 0) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - process.getInputStream().transferTo( baos ); - process.getErrorStream().transferTo( baos ); - throw new AssertionError( baos.toString() ); + process.getInputStream().transferTo(baos); + process.getErrorStream().transferTo(baos); + throw new AssertionError(baos.toString()); } } @@ -128,80 +127,76 @@ public void addModuleInfoAndRunModular() throws Exception { File.separator + "java"; ProcessBuilder builder = new ProcessBuilder( - javaBin, "--module-path", GENERATED_TEST_RESOURCES + File.separator + "example.jar", "--module", "com.example" ) - .redirectOutput( Redirect.INHERIT ); + javaBin, "--module-path", GENERATED_TEST_RESOURCES + File.separator + "example.jar", "--module", "com.example") + .redirectOutput(Redirect.INHERIT); Process process = builder.start(); process.waitFor(); - if ( process.exitValue() == 0 ) { + if (process.exitValue() == 0) { throw new AssertionError(); } new AddModuleInfo( - "module com.example {}", - "com.example.HelloWorld", - "1.42.3", - Paths.get( "target", "generated-test-resources", "example.jar" ), - Paths.get( "target", "generated-test-modules" ), - null, - false, - null - ) - .run(); + "module com.example {}", + "com.example.HelloWorld", + "1.42.3", + Paths.get("target", "generated-test-resources", "example.jar"), + Paths.get("target", "generated-test-modules"), + null, + false, + null) + .run(); builder = new ProcessBuilder( - javaBin, "--module-path", GENERATED_TEST_MODULES + File.separator + "example.jar", "--module", "com.example" ); + javaBin, "--module-path", GENERATED_TEST_MODULES + File.separator + "example.jar", "--module", "com.example"); process = builder.start(); process.waitFor(); - if ( process.exitValue() != 0 ) { + if (process.exitValue() != 0) { throw new AssertionError(); } } private void prepareTestJar() throws Exception { Compilation compilation = Compiler.javac() - .compile( - JavaFileObjects.forSourceString( - "com.example.HelloWorld", - "package com.example;" + - "public class HelloWorld {" + - " public static void main(String... args) {" + - " System.out.println( \"Moin\" );" + - " }" + - "}" - ) - ); + .compile( + JavaFileObjects.forSourceString( + "com.example.HelloWorld", + "package com.example;" + + "public class HelloWorld {" + + " public static void main(String... args) {" + + " System.out.println( \"Moin\" );" + + " }" + + "}")); Optional classFile = compilation.generatedFile( - StandardLocation.CLASS_OUTPUT, "com/example/HelloWorld.class" - ); + StandardLocation.CLASS_OUTPUT, "com/example/HelloWorld.class"); - Path exampleJar = GENERATED_TEST_RESOURCES.resolve( "example.jar" ); + Path exampleJar = GENERATED_TEST_RESOURCES.resolve("example.jar"); Manifest manifest = new Manifest(); - manifest.getMainAttributes().put( Attributes.Name.MANIFEST_VERSION, "1.0" ); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); - JarOutputStream target = new JarOutputStream(new FileOutputStream( exampleJar.toFile() ), manifest); + JarOutputStream target = new JarOutputStream(new FileOutputStream(exampleJar.toFile()), manifest); long now = System.currentTimeMillis(); - JarEntry entry = new JarEntry( "com/" ); - entry.setTime( now ); - target.putNextEntry( entry ); + JarEntry entry = new JarEntry("com/"); + entry.setTime(now); + target.putNextEntry(entry); target.closeEntry(); - entry = new JarEntry( "com/example/" ); - entry.setTime( now ); - target.putNextEntry( entry ); + entry = new JarEntry("com/example/"); + entry.setTime(now); + target.putNextEntry(entry); target.closeEntry(); - entry = new JarEntry( "com/example/HelloWorld.class" ); - entry.setTime( now ); - target.putNextEntry( entry ); + entry = new JarEntry("com/example/HelloWorld.class"); + entry.setTime(now); + target.putNextEntry(entry); - try ( InputStream is = classFile.get().openInputStream() ) { + try (InputStream is = classFile.get().openInputStream()) { byte[] bytes = is.readAllBytes(); target.write(bytes, 0, bytes.length); } diff --git a/core/src/test/java/org/moditect/test/model/DependencePatternTest.java b/core/src/test/java/org/moditect/test/model/DependencePatternTest.java index 9c3fba9..886e87b 100644 --- a/core/src/test/java/org/moditect/test/model/DependencePatternTest.java +++ b/core/src/test/java/org/moditect/test/model/DependencePatternTest.java @@ -15,40 +15,40 @@ */ package org.moditect.test.model; -import static org.assertj.core.api.Assertions.assertThat; - import java.util.regex.Pattern; import org.junit.Test; import org.moditect.model.DependencePattern; +import static org.assertj.core.api.Assertions.assertThat; + public class DependencePatternTest { @Test public void all() { - DependencePattern pattern = DependencePattern.parsePattern( "*" ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( ".*" ).pattern() ); - assertThat( pattern.getModifiers() ).isEmpty(); + DependencePattern pattern = DependencePattern.parsePattern("*"); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile(".*").pattern()); + assertThat(pattern.getModifiers()).isEmpty(); } @Test public void noModifiers() { - DependencePattern pattern = DependencePattern.parsePattern( "java.validation" ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( "java\\.validation" ).pattern() ); - assertThat( pattern.getModifiers() ).isEmpty(); + DependencePattern pattern = DependencePattern.parsePattern("java.validation"); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile("java\\.validation").pattern()); + assertThat(pattern.getModifiers()).isEmpty(); } @Test public void oneModifier() { - DependencePattern pattern = DependencePattern.parsePattern( "static java.validation" ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( "java\\.validation" ).pattern() ); - assertThat( pattern.getModifiers() ).containsOnly( "static" ); + DependencePattern pattern = DependencePattern.parsePattern("static java.validation"); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile("java\\.validation").pattern()); + assertThat(pattern.getModifiers()).containsOnly("static"); } @Test public void twoModifiers() { - DependencePattern pattern = DependencePattern.parsePattern( "static transitive java.validation" ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( "java\\.validation" ).pattern() ); - assertThat( pattern.getModifiers() ).containsOnly( "static", "transitive" ); + DependencePattern pattern = DependencePattern.parsePattern("static transitive java.validation"); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile("java\\.validation").pattern()); + assertThat(pattern.getModifiers()).containsOnly("static", "transitive"); } } diff --git a/core/src/test/java/org/moditect/test/model/PackageNamePatternTest.java b/core/src/test/java/org/moditect/test/model/PackageNamePatternTest.java index 43bf544..c0911c4 100644 --- a/core/src/test/java/org/moditect/test/model/PackageNamePatternTest.java +++ b/core/src/test/java/org/moditect/test/model/PackageNamePatternTest.java @@ -15,71 +15,71 @@ */ package org.moditect.test.model; -import static org.assertj.core.api.Assertions.assertThat; - import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import org.moditect.model.PackageNamePattern; +import static org.assertj.core.api.Assertions.assertThat; + public class PackageNamePatternTest { @Test public void includeAll() { - PackageNamePattern pattern = PackageNamePattern.parsePattern( "*" ); - assertThat( pattern.getKind() ).isEqualTo( PackageNamePattern.Kind.INCLUSIVE ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( ".*" ).pattern() ); - assertThat( pattern.getTargetModules() ).isEmpty(); + PackageNamePattern pattern = PackageNamePattern.parsePattern("*"); + assertThat(pattern.getKind()).isEqualTo(PackageNamePattern.Kind.INCLUSIVE); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile(".*").pattern()); + assertThat(pattern.getTargetModules()).isEmpty(); } @Test public void excludeAll() { - PackageNamePattern pattern = PackageNamePattern.parsePattern( "!*" ); - assertThat( pattern.getKind() ).isEqualTo( PackageNamePattern.Kind.EXCLUSIVE ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( ".*" ).pattern() ); - assertThat( pattern.getTargetModules() ).isEmpty(); + PackageNamePattern pattern = PackageNamePattern.parsePattern("!*"); + assertThat(pattern.getKind()).isEqualTo(PackageNamePattern.Kind.EXCLUSIVE); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile(".*").pattern()); + assertThat(pattern.getTargetModules()).isEmpty(); } @Test public void qualifiedInclude() { - PackageNamePattern pattern = PackageNamePattern.parsePattern( "org.hibernate.validator.internal.util.logging to org.jboss.logging" ); - assertThat( pattern.getKind() ).isEqualTo( PackageNamePattern.Kind.INCLUSIVE ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( "org\\.hibernate\\.validator\\.internal\\.util\\.logging" ).pattern() ); - assertThat( pattern.getTargetModules() ).containsExactly( "org.jboss.logging" ); + PackageNamePattern pattern = PackageNamePattern.parsePattern("org.hibernate.validator.internal.util.logging to org.jboss.logging"); + assertThat(pattern.getKind()).isEqualTo(PackageNamePattern.Kind.INCLUSIVE); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile("org\\.hibernate\\.validator\\.internal\\.util\\.logging").pattern()); + assertThat(pattern.getTargetModules()).containsExactly("org.jboss.logging"); } @Test public void excludeWithWildcard() { - PackageNamePattern pattern = PackageNamePattern.parsePattern( "!org.hibernate.validator.internal*" ); - assertThat( pattern.getKind() ).isEqualTo( PackageNamePattern.Kind.EXCLUSIVE ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( "org\\.hibernate\\.validator\\.internal.*" ).pattern() ); - assertThat( pattern.getTargetModules() ).isEmpty(); + PackageNamePattern pattern = PackageNamePattern.parsePattern("!org.hibernate.validator.internal*"); + assertThat(pattern.getKind()).isEqualTo(PackageNamePattern.Kind.EXCLUSIVE); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile("org\\.hibernate\\.validator\\.internal.*").pattern()); + assertThat(pattern.getTargetModules()).isEmpty(); } @Test public void parsePatterns() { StringBuilder patterns = new StringBuilder(); - patterns.append( "org.hibernate.validator.internal.util.logging to org.jboss.logging;\n" ); - patterns.append( "!org.hibernate.validator.internal*;\n" ); - patterns.append( "*;\n" ); + patterns.append("org.hibernate.validator.internal.util.logging to org.jboss.logging;\n"); + patterns.append("!org.hibernate.validator.internal*;\n"); + patterns.append("*;\n"); - List patternList = PackageNamePattern.parsePatterns( patterns.toString() ); - assertThat( patternList ).hasSize( 3 ); + List patternList = PackageNamePattern.parsePatterns(patterns.toString()); + assertThat(patternList).hasSize(3); - PackageNamePattern pattern = patternList.get( 0 ); - assertThat( pattern.getKind() ).isEqualTo( PackageNamePattern.Kind.INCLUSIVE ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( "org\\.hibernate\\.validator\\.internal\\.util\\.logging" ).pattern() ); - assertThat( pattern.getTargetModules() ).containsExactly( "org.jboss.logging" ); + PackageNamePattern pattern = patternList.get(0); + assertThat(pattern.getKind()).isEqualTo(PackageNamePattern.Kind.INCLUSIVE); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile("org\\.hibernate\\.validator\\.internal\\.util\\.logging").pattern()); + assertThat(pattern.getTargetModules()).containsExactly("org.jboss.logging"); - pattern = patternList.get( 1 ); - assertThat( pattern.getKind() ).isEqualTo( PackageNamePattern.Kind.EXCLUSIVE ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( "org\\.hibernate\\.validator\\.internal.*" ).pattern() ); - assertThat( pattern.getTargetModules() ).isEmpty(); + pattern = patternList.get(1); + assertThat(pattern.getKind()).isEqualTo(PackageNamePattern.Kind.EXCLUSIVE); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile("org\\.hibernate\\.validator\\.internal.*").pattern()); + assertThat(pattern.getTargetModules()).isEmpty(); - pattern = patternList.get( 2 ); - assertThat( pattern.getKind() ).isEqualTo( PackageNamePattern.Kind.INCLUSIVE ); - assertThat( pattern.getPattern().pattern() ).isEqualTo( Pattern.compile( ".*" ).pattern() ); - assertThat( pattern.getTargetModules() ).isEmpty(); + pattern = patternList.get(2); + assertThat(pattern.getKind()).isEqualTo(PackageNamePattern.Kind.INCLUSIVE); + assertThat(pattern.getPattern().pattern()).isEqualTo(Pattern.compile(".*").pattern()); + assertThat(pattern.getTargetModules()).isEmpty(); } } diff --git a/etc/eclipse-formatter-config.xml b/etc/eclipse-formatter-config.xml new file mode 100644 index 0000000..8a207ab --- /dev/null +++ b/etc/eclipse-formatter-config.xml @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/integrationtest/hibernate-validator/src/main/java/com/example/ValidationTest.java b/integrationtest/hibernate-validator/src/main/java/com/example/ValidationTest.java index dabe0d3..9a7c988 100644 --- a/integrationtest/hibernate-validator/src/main/java/com/example/ValidationTest.java +++ b/integrationtest/hibernate-validator/src/main/java/com/example/ValidationTest.java @@ -28,16 +28,16 @@ */ public class ValidationTest { - public static void main(String[] args) { - Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - Set> violations = validator.validate( new Customer() ); + public static void main(String[] args) { + Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); + Set> violations = validator.validate(new Customer()); - System.out.println( violations ); - } + System.out.println(violations); + } - public static class Customer { + public static class Customer { - @NotNull - private String name = null; - } + @NotNull + private String name = null; + } } diff --git a/integrationtest/undertow/src/main/java/com/example/HelloWorldServer.java b/integrationtest/undertow/src/main/java/com/example/HelloWorldServer.java index a0498b8..852f463 100644 --- a/integrationtest/undertow/src/main/java/com/example/HelloWorldServer.java +++ b/integrationtest/undertow/src/main/java/com/example/HelloWorldServer.java @@ -25,15 +25,15 @@ public class HelloWorldServer { public static void main(final String[] args) { Undertow server = Undertow.builder() - .addHttpListener( 8080, "0.0.0.0" ) - .setHandler( exchange -> { - String name = exchange.getQueryParameters() - .getOrDefault( "name", new ArrayDeque<>( Collections.singleton( "nameless stranger" ) ) ) - .getFirst(); - exchange.getResponseHeaders().put( Headers.CONTENT_TYPE, "text/plain" ); - exchange.getResponseSender().send( "Hello, " + name + "!" ); - } ) - .build(); + .addHttpListener(8080, "0.0.0.0") + .setHandler(exchange -> { + String name = exchange.getQueryParameters() + .getOrDefault("name", new ArrayDeque<>(Collections.singleton("nameless stranger"))) + .getFirst(); + exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); + exchange.getResponseSender().send("Hello, " + name + "!"); + }) + .build(); server.start(); } diff --git a/integrationtest/vert.x/src/main/java/com/example/HelloWorldServer.java b/integrationtest/vert.x/src/main/java/com/example/HelloWorldServer.java index 5f47330..aec952e 100644 --- a/integrationtest/vert.x/src/main/java/com/example/HelloWorldServer.java +++ b/integrationtest/vert.x/src/main/java/com/example/HelloWorldServer.java @@ -21,6 +21,6 @@ public class HelloWorldServer { public static void main(final String[] args) { Vertx vertx = Vertx.vertx(); - vertx.deployVerticle( HelloWorldVerticle.class.getName() ); + vertx.deployVerticle(HelloWorldVerticle.class.getName()); } } diff --git a/integrationtest/vert.x/src/main/java/com/example/HelloWorldVerticle.java b/integrationtest/vert.x/src/main/java/com/example/HelloWorldVerticle.java index b7cad3f..20968de 100644 --- a/integrationtest/vert.x/src/main/java/com/example/HelloWorldVerticle.java +++ b/integrationtest/vert.x/src/main/java/com/example/HelloWorldVerticle.java @@ -25,17 +25,17 @@ public class HelloWorldVerticle extends AbstractVerticle { @Override public void start(Future future) { vertx.createHttpServer() - .requestHandler(r -> { - String name = Optional.ofNullable( r.getParam( "name" ) ).orElse( "nameless stranger" ); - r.response().end ( "Hello, " + name + "!" ); - }) - .listen( 8080, result -> { - if ( result.succeeded() ) { - future.complete(); - } - else { - future.fail(result.cause()); - } - } ); + .requestHandler(r -> { + String name = Optional.ofNullable(r.getParam("name")).orElse("nameless stranger"); + r.response().end("Hello, " + name + "!"); + }) + .listen(8080, result -> { + if (result.succeeded()) { + future.complete(); + } + else { + future.fail(result.cause()); + } + }); } } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/add/AddModuleInfoMojo.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/add/AddModuleInfoMojo.java index 13b5aac..9796d88 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/add/AddModuleInfoMojo.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/add/AddModuleInfoMojo.java @@ -54,11 +54,9 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; - import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; - import org.moditect.commands.AddModuleInfo; import org.moditect.internal.compiler.ModuleInfoCompiler; import org.moditect.mavenplugin.add.model.MainModuleConfiguration; @@ -78,7 +76,7 @@ public class AddModuleInfoMojo extends AbstractMojo { private static final String MODULE_INFO_CLASS = "module-info.class"; - private static final Pattern VERSIONED_MODULE_INFO = Pattern.compile( "META-INF/versions/\\d+/" + MODULE_INFO_CLASS ); + private static final Pattern VERSIONED_MODULE_INFO = Pattern.compile("META-INF/versions/\\d+/" + MODULE_INFO_CLASS); @Component private RepositorySystem repoSystem; @@ -142,20 +140,20 @@ public class AddModuleInfoMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { - // Check if this plugin should be skipped - if (skip) { - getLog().debug("Mojo 'add-module-info' skipped by configuration"); - return; - } - // Don't try to run this plugin, when packaging type is 'pom' - // (may be better to only run it on specific packaging types, like 'jar') - if (project.getModel().getPackaging().equalsIgnoreCase("pom")) { - getLog().debug("Mojo 'add-module-info' not executed on packaging type '"+project.getModel().getPackaging()+"'"); - return; - } + // Check if this plugin should be skipped + if (skip) { + getLog().debug("Mojo 'add-module-info' skipped by configuration"); + return; + } + // Don't try to run this plugin, when packaging type is 'pom' + // (may be better to only run it on specific packaging types, like 'jar') + if (project.getModel().getPackaging().equalsIgnoreCase("pom")) { + getLog().debug("Mojo 'add-module-info' not executed on packaging type '" + project.getModel().getPackaging() + "'"); + return; + } if (exclusions != null) { - ArtifactFilter scopeFilter = new ScopeArtifactFilter("compile+runtime"); + ArtifactFilter scopeFilter = new ScopeArtifactFilter("compile+runtime"); ArtifactFilter exclusionFilter = new ExclusionArtifactFilter(exclusions); project.setArtifactFilter(new AndArtifactFilter(Arrays.asList(scopeFilter, exclusionFilter))); } @@ -164,87 +162,86 @@ public void execute() throws MojoExecutionException, MojoFailureException { createDirectories(); - ArtifactResolutionHelper artifactResolutionHelper = new ArtifactResolutionHelper( repoSystem, repoSession, remoteRepos ); + ArtifactResolutionHelper artifactResolutionHelper = new ArtifactResolutionHelper(repoSystem, repoSession, remoteRepos); ModuleInfoGenerator moduleInfoGenerator = new ModuleInfoGenerator( - project, repoSystem, repoSession, remoteRepos, artifactResolutionHelper, jdepsExtraArgs, getLog(), workingDirectory, new File( workingDirectory, "generated-sources" ) - ); + project, repoSystem, repoSession, remoteRepos, artifactResolutionHelper, jdepsExtraArgs, getLog(), workingDirectory, + new File(workingDirectory, "generated-sources")); - resolveArtifactsToBeModularized( artifactResolutionHelper ); + resolveArtifactsToBeModularized(artifactResolutionHelper); - Map assignedNamesByModule = getAssignedModuleNamesByModule( artifactResolutionHelper ); + Map assignedNamesByModule = getAssignedModuleNamesByModule(artifactResolutionHelper); Map modularizedJars = new HashMap<>(); - if ( modules != null ) { - for ( ModuleConfiguration moduleConfiguration : modules ) { - Path inputFile = getInputFile( moduleConfiguration, artifactResolutionHelper ); - if ( isModularJar( inputFile ) ) { + if (modules != null) { + for (ModuleConfiguration moduleConfiguration : modules) { + Path inputFile = getInputFile(moduleConfiguration, artifactResolutionHelper); + if (isModularJar(inputFile)) { String message = "File " + inputFile.getFileName() + " is already modular"; - if ( failOnWarning ) { - throw new MojoExecutionException( message ); - } else { - getLog().warn( message ); + if (failOnWarning) { + throw new MojoExecutionException(message); + } + else { + getLog().warn(message); continue; } } - String moduleInfoSource = getModuleInfoSource( inputFile, moduleConfiguration, moduleInfoGenerator, assignedNamesByModule, modularizedJars ); + String moduleInfoSource = getModuleInfoSource(inputFile, moduleConfiguration, moduleInfoGenerator, assignedNamesByModule, modularizedJars); AddModuleInfo addModuleInfo = new AddModuleInfo( - moduleInfoSource, - moduleConfiguration.getMainClass(), - getVersion( moduleConfiguration ), - inputFile, - outputPath, - jvmVersion, - overwriteExistingFiles, - InstantConverter.convert(outputTimestamp) - ); + moduleInfoSource, + moduleConfiguration.getMainClass(), + getVersion(moduleConfiguration), + inputFile, + outputPath, + jvmVersion, + overwriteExistingFiles, + InstantConverter.convert(outputTimestamp)); addModuleInfo.run(); - if ( moduleConfiguration.getArtifact() != null ) { + if (moduleConfiguration.getArtifact() != null) { modularizedJars.put( - new ArtifactIdentifier( moduleConfiguration.getResolvedArtifact() ), - outputPath.resolve( inputFile.getFileName() ) - ); + new ArtifactIdentifier(moduleConfiguration.getResolvedArtifact()), + outputPath.resolve(inputFile.getFileName())); } } } - if ( module != null ) { - Path inputJar = buildDirectory.toPath().resolve( project.getModel().getBuild().getFinalName() + ".jar" ); - if ( !Files.exists( inputJar ) ) { - throw new MojoExecutionException( "Couldn't find file " + inputJar + ". Run this goal for the project's JAR only after the maven-jar-plugin." ); + if (module != null) { + Path inputJar = buildDirectory.toPath().resolve(project.getModel().getBuild().getFinalName() + ".jar"); + if (!Files.exists(inputJar)) { + throw new MojoExecutionException("Couldn't find file " + inputJar + ". Run this goal for the project's JAR only after the maven-jar-plugin."); } - if ( isModularJar( inputJar ) ) { + if (isModularJar(inputJar)) { String message = "File " + inputJar.getFileName() + " is already modular"; - if ( failOnWarning ) { - throw new MojoExecutionException( message ); - } else { - getLog().warn( message ); + if (failOnWarning) { + throw new MojoExecutionException(message); + } + else { + getLog().warn(message); return; } } AddModuleInfo addModuleInfo = new AddModuleInfo( - getModuleInfoSource( inputJar, module, moduleInfoGenerator, assignedNamesByModule, modularizedJars ), + getModuleInfoSource(inputJar, module, moduleInfoGenerator, assignedNamesByModule, modularizedJars), module.getMainClass(), version, inputJar, outputPath, jvmVersion, overwriteExistingFiles, - InstantConverter.convert(outputTimestamp) - ); + InstantConverter.convert(outputTimestamp)); addModuleInfo.run(); try { - Files.copy( outputPath.resolve( inputJar.getFileName() ), inputJar, StandardCopyOption.REPLACE_EXISTING ); + Files.copy(outputPath.resolve(inputJar.getFileName()), inputJar, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { - throw new RuntimeException( "Couldn't replace " + inputJar + " with modularized version", e ); + throw new RuntimeException("Couldn't replace " + inputJar + " with modularized version", e); } } } @@ -255,17 +252,18 @@ project, repoSystem, repoSession, remoteRepos, artifactResolutionHelper, jdepsEx * one "/META-INF/version/\\d+/module-info.class" entry. */ private boolean isModularJar(Path jarPath) { - try( JarFile jarFile = new JarFile( jarPath.toFile() ) ) { + try (JarFile jarFile = new JarFile(jarPath.toFile())) { Enumeration entries = jarFile.entries(); - while ( entries.hasMoreElements() ) { + while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); - if ( entryName.equals( MODULE_INFO_CLASS ) || VERSIONED_MODULE_INFO.matcher( entryName ).matches() ) { + if (entryName.equals(MODULE_INFO_CLASS) || VERSIONED_MODULE_INFO.matcher(entryName).matches()) { return true; } } - } catch ( IOException ioe ) { - throw new IllegalStateException( "Unexpected error when reading " + jarPath.getFileName() ); + } + catch (IOException ioe) { + throw new IllegalStateException("Unexpected error when reading " + jarPath.getFileName()); } return false; } @@ -275,71 +273,70 @@ private boolean isModularJar(Path jarPath) { * to obtain it from the project dependencies. */ private void resolveArtifactsToBeModularized(ArtifactResolutionHelper artifactResolutionHelper) throws MojoExecutionException { - if ( modules == null ) { + if (modules == null) { return; } - for ( ModuleConfiguration moduleConfiguration : modules ) { + for (ModuleConfiguration moduleConfiguration : modules) { ArtifactConfiguration artifact = moduleConfiguration.getArtifact(); - if ( artifact != null ) { - if ( artifact.getVersion() == null ) { - artifact.setVersion( determineVersion( artifact ) ); + if (artifact != null) { + if (artifact.getVersion() == null) { + artifact.setVersion(determineVersion(artifact)); } - moduleConfiguration.setResolvedArtifact( artifactResolutionHelper.resolveArtifact( artifact ) ); + moduleConfiguration.setResolvedArtifact(artifactResolutionHelper.resolveArtifact(artifact)); } } } private String determineVersion(ArtifactConfiguration artifact) throws MojoExecutionException { Optional resolvedDependency = project.getArtifacts() - .stream() - .filter( a -> { - return Objects.equals( a.getGroupId(), artifact.getGroupId() ) && - Objects.equals( a.getArtifactId(), artifact.getArtifactId() ) && - Objects.equals( a.getClassifier(), artifact.getClassifier() ) && - Objects.equals( a.getType(), artifact.getType() ); - } ) - .findFirst(); - - if ( resolvedDependency.isPresent() ) { + .stream() + .filter(a -> { + return Objects.equals(a.getGroupId(), artifact.getGroupId()) && + Objects.equals(a.getArtifactId(), artifact.getArtifactId()) && + Objects.equals(a.getClassifier(), artifact.getClassifier()) && + Objects.equals(a.getType(), artifact.getType()); + }) + .findFirst(); + + if (resolvedDependency.isPresent()) { return resolvedDependency.get().getVersion(); } - if ( project.getDependencyManagement() != null ) { + if (project.getDependencyManagement() != null) { Optional managed = project.getDependencyManagement() .getDependencies() .stream() - .filter( d -> { - return Objects.equals( d.getGroupId(), artifact.getGroupId() ) && - Objects.equals( d.getArtifactId(), artifact.getArtifactId() ) && - Objects.equals( d.getClassifier(), artifact.getClassifier() ) && - Objects.equals( d.getType(), artifact.getType() ); - } ) + .filter(d -> { + return Objects.equals(d.getGroupId(), artifact.getGroupId()) && + Objects.equals(d.getArtifactId(), artifact.getArtifactId()) && + Objects.equals(d.getClassifier(), artifact.getClassifier()) && + Objects.equals(d.getType(), artifact.getType()); + }) .findFirst(); - if ( managed.isPresent() ) { + if (managed.isPresent()) { return managed.get().getVersion(); } } throw new MojoExecutionException( "A version must be given for artifact " + artifact.toDependencyString() + - ". Either specify one explicitly, add it to the project dependencies" + - " or add it to the project's dependency management." - ); + ". Either specify one explicitly, add it to the project dependencies" + + " or add it to the project's dependency management."); } private String getVersion(ModuleConfiguration moduleConfiguration) { - if ( moduleConfiguration.getVersion() != null ) { + if (moduleConfiguration.getVersion() != null) { return moduleConfiguration.getVersion(); } - else if ( moduleConfiguration.getArtifact() != null ) { + else if (moduleConfiguration.getArtifact() != null) { return moduleConfiguration.getArtifact().getVersion(); } // TODO try to derive version from file name? - else if ( moduleConfiguration.getFile() != null ) { + else if (moduleConfiguration.getFile() != null) { return null; } else { @@ -348,109 +345,108 @@ else if ( moduleConfiguration.getFile() != null ) { } private Path getInputFile(ModuleConfiguration moduleConfiguration, ArtifactResolutionHelper artifactResolutionHelper) throws MojoExecutionException { - if ( moduleConfiguration.getFile() != null ) { - if ( moduleConfiguration.getArtifact() != null ) { - throw new MojoExecutionException( "Only one of 'file' and 'artifact' may be specified, but both are given for" - + moduleConfiguration.getArtifact().toDependencyString() ); + if (moduleConfiguration.getFile() != null) { + if (moduleConfiguration.getArtifact() != null) { + throw new MojoExecutionException("Only one of 'file' and 'artifact' may be specified, but both are given for" + + moduleConfiguration.getArtifact().toDependencyString()); } else { return moduleConfiguration.getFile().toPath(); } } - else if ( moduleConfiguration.getArtifact() != null ) { + else if (moduleConfiguration.getArtifact() != null) { return moduleConfiguration.getResolvedArtifact().getFile().toPath(); } else { - throw new MojoExecutionException( "One of 'file' and 'artifact' must be specified" ); + throw new MojoExecutionException("One of 'file' and 'artifact' must be specified"); } } - private String getModuleInfoSource(Path inputFile, ModuleConfiguration moduleConfiguration, ModuleInfoGenerator moduleInfoGenerator, Map assignedNamesByModule, Map modularizedJars) throws MojoExecutionException { - if ( moduleConfiguration.getModuleInfo() != null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() == null ) { + private String getModuleInfoSource(Path inputFile, ModuleConfiguration moduleConfiguration, ModuleInfoGenerator moduleInfoGenerator, + Map assignedNamesByModule, Map modularizedJars) + throws MojoExecutionException { + if (moduleConfiguration.getModuleInfo() != null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() == null) { GeneratedModuleInfo generatedModuleInfo; - if ( moduleConfiguration.getArtifact() != null ) { + if (moduleConfiguration.getArtifact() != null) { generatedModuleInfo = moduleInfoGenerator.generateModuleInfo( moduleConfiguration.getArtifact(), moduleConfiguration.getAdditionalDependencies(), moduleConfiguration.getModuleInfo(), assignedNamesByModule, - modularizedJars - ); + modularizedJars); } else { generatedModuleInfo = moduleInfoGenerator.generateModuleInfo( moduleConfiguration.getFile().toPath(), moduleConfiguration.getAdditionalDependencies(), moduleConfiguration.getModuleInfo(), - assignedNamesByModule - ); + assignedNamesByModule); } - return getLines( generatedModuleInfo.getPath() ); + return getLines(generatedModuleInfo.getPath()); } - else if ( moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() != null && moduleConfiguration.getModuleInfoFile() == null ) { + else if (moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() != null && moduleConfiguration.getModuleInfoFile() == null) { return moduleConfiguration.getModuleInfoSource(); } - else if ( moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() != null ) { - return getLines( moduleConfiguration.getModuleInfoFile().toPath() ); + else if (moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() != null) { + return getLines(moduleConfiguration.getModuleInfoFile().toPath()); } else { - throw new MojoExecutionException( "Either 'moduleInfo' or 'moduleInfoFile' or 'moduleInfoSource' must be specified for " + inputFile); + throw new MojoExecutionException("Either 'moduleInfo' or 'moduleInfoFile' or 'moduleInfoSource' must be specified for " + inputFile); } } - private String getModuleInfoSource(Path inputFile, MainModuleConfiguration moduleConfiguration, ModuleInfoGenerator moduleInfoGenerator, Map assignedNamesByModule, Map modularizedJars) throws MojoExecutionException { - if ( moduleConfiguration.getModuleInfo() != null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() == null ) { + private String getModuleInfoSource(Path inputFile, MainModuleConfiguration moduleConfiguration, ModuleInfoGenerator moduleInfoGenerator, + Map assignedNamesByModule, Map modularizedJars) + throws MojoExecutionException { + if (moduleConfiguration.getModuleInfo() != null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() == null) { Set dependencies = project.getArtifacts().stream() - .map( d -> new DependencyDescriptor( - d.getFile().toPath(), - d.isOptional(), - getAssignedModuleName( assignedNamesByModule, d ) - ) - ) - .collect( Collectors.toSet() ); + .map(d -> new DependencyDescriptor( + d.getFile().toPath(), + d.isOptional(), + getAssignedModuleName(assignedNamesByModule, d))) + .collect(Collectors.toSet()); GeneratedModuleInfo generatedModuleInfo = moduleInfoGenerator.generateModuleInfo( inputFile, dependencies, - moduleConfiguration.getModuleInfo() - ); + moduleConfiguration.getModuleInfo()); - return getLines( generatedModuleInfo.getPath() ); + return getLines(generatedModuleInfo.getPath()); } - else if ( moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() != null && moduleConfiguration.getModuleInfoFile() == null ) { + else if (moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() != null && moduleConfiguration.getModuleInfoFile() == null) { return moduleConfiguration.getModuleInfoSource(); } - else if ( moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() != null ) { - return getLines( moduleConfiguration.getModuleInfoFile().toPath() ); + else if (moduleConfiguration.getModuleInfo() == null && moduleConfiguration.getModuleInfoSource() == null && moduleConfiguration.getModuleInfoFile() != null) { + return getLines(moduleConfiguration.getModuleInfoFile().toPath()); } else { - throw new MojoExecutionException( "Either 'moduleInfo' or 'moduleInfoFile' or 'moduleInfoSource' must be specified for ." ); + throw new MojoExecutionException("Either 'moduleInfo' or 'moduleInfoFile' or 'moduleInfoSource' must be specified for ."); } } private String getLines(Path file) throws MojoExecutionException { try { - return new String(Files.readAllBytes( file ) ); + return new String(Files.readAllBytes(file)); } catch (IOException e) { - throw new MojoExecutionException( "Couldn't read file " + file ); + throw new MojoExecutionException("Couldn't read file " + file); } } private void createDirectories() { - if ( !workingDirectory.exists() ) { + if (!workingDirectory.exists()) { workingDirectory.mkdirs(); } - File internalGeneratedSourcesDir = new File(workingDirectory, "generated-sources" ); - if ( !internalGeneratedSourcesDir.exists() ) { + File internalGeneratedSourcesDir = new File(workingDirectory, "generated-sources"); + if (!internalGeneratedSourcesDir.exists()) { internalGeneratedSourcesDir.mkdirs(); } - if ( !outputDirectory.exists() ) { + if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } } @@ -458,29 +454,28 @@ private void createDirectories() { private Map getAssignedModuleNamesByModule(ArtifactResolutionHelper artifactResolutionHelper) throws MojoExecutionException { Map assignedNamesByModule = new HashMap<>(); - if ( modules == null ) { + if (modules == null) { return assignedNamesByModule; } - for ( ModuleConfiguration configuredModule : modules ) { + for (ModuleConfiguration configuredModule : modules) { String assignedName; - if ( configuredModule.getModuleInfo() != null ) { + if (configuredModule.getModuleInfo() != null) { assignedName = configuredModule.getModuleInfo().getName(); } - else if ( configuredModule.getModuleInfoFile() != null ) { - assignedName = ModuleInfoCompiler.parseModuleInfo( configuredModule.getModuleInfoFile().toPath() ).getNameAsString(); + else if (configuredModule.getModuleInfoFile() != null) { + assignedName = ModuleInfoCompiler.parseModuleInfo(configuredModule.getModuleInfoFile().toPath()).getNameAsString(); } else { - assignedName = ModuleInfoCompiler.parseModuleInfo( configuredModule.getModuleInfoSource() ).getNameAsString(); + assignedName = ModuleInfoCompiler.parseModuleInfo(configuredModule.getModuleInfoSource()).getNameAsString(); } // TODO handle file case; although file is unlikely to be used together with others - if ( configuredModule.getArtifact() != null ) { + if (configuredModule.getArtifact() != null) { assignedNamesByModule.put( - new ArtifactIdentifier( configuredModule.getResolvedArtifact() ), - assignedName - ); + new ArtifactIdentifier(configuredModule.getResolvedArtifact()), + assignedName); } } @@ -488,13 +483,15 @@ else if ( configuredModule.getModuleInfoFile() != null ) { } private String getAssignedModuleName(Map assignedNamesByModule, Artifact artifact) { - for ( Entry assignedNameByModule : assignedNamesByModule.entrySet() ) { + for (Entry assignedNameByModule : assignedNamesByModule.entrySet()) { // ignoring the version; the resolved artifact could have a different version then the one used // in this modularization build - if ( assignedNameByModule.getKey().getGroupId().equals( artifact.getGroupId() ) && - assignedNameByModule.getKey().getArtifactId().equals( artifact.getArtifactId() ) && - ( artifact.getClassifier() == null && assignedNameByModule.getKey().getClassifier().equals("") || assignedNameByModule.getKey().getClassifier().equals( artifact.getClassifier() ) ) && - assignedNameByModule.getKey().getExtension().equals( artifact.getType() ) ) { + if (assignedNameByModule.getKey().getGroupId().equals(artifact.getGroupId()) && + assignedNameByModule.getKey().getArtifactId().equals(artifact.getArtifactId()) && + (artifact.getClassifier() == null && assignedNameByModule.getKey().getClassifier().equals("") + || assignedNameByModule.getKey().getClassifier().equals(artifact.getClassifier())) + && + assignedNameByModule.getKey().getExtension().equals(artifact.getType())) { return assignedNameByModule.getValue(); } } @@ -502,44 +499,44 @@ private String getAssignedModuleName(Map assignedNam return null; } - private static class InstantConverter { - private static final Instant DATE_MIN = Instant.parse( "1980-01-01T00:00:02Z" ); - private static final Instant DATE_MAX = Instant.parse( "2099-12-31T23:59:59Z" ); + private static final Instant DATE_MIN = Instant.parse("1980-01-01T00:00:02Z"); + private static final Instant DATE_MAX = Instant.parse("2099-12-31T23:59:59Z"); public static Instant convert(String value) { - if ( value == null ) { + if (value == null) { return null; } // Number representing seconds since the epoch - if ( !value.isEmpty() && isNumeric( value ) ) { - return Instant.ofEpochSecond( Long.parseLong( value.trim() ) ); + if (!value.isEmpty() && isNumeric(value)) { + return Instant.ofEpochSecond(Long.parseLong(value.trim())); } try { // Parse the date in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'. - final Instant date = OffsetDateTime.parse( value ) - .withOffsetSameInstant( ZoneOffset.UTC ).truncatedTo( ChronoUnit.SECONDS ).toInstant(); + final Instant date = OffsetDateTime.parse(value) + .withOffsetSameInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS).toInstant(); - if ( date.isBefore( DATE_MIN ) || date.isAfter( DATE_MAX ) ) { - throw new IllegalArgumentException( "'" + date + "' is not within the valid range " - + DATE_MIN + " to " + DATE_MAX ); + if (date.isBefore(DATE_MIN) || date.isAfter(DATE_MAX)) { + throw new IllegalArgumentException("'" + date + "' is not within the valid range " + + DATE_MIN + " to " + DATE_MAX); } return date; } - catch ( DateTimeParseException pe ) { - throw new IllegalArgumentException( "Invalid project.build.outputTimestamp value '" + value + "'", - pe ); + catch (DateTimeParseException pe) { + throw new IllegalArgumentException("Invalid project.build.outputTimestamp value '" + value + "'", + pe); } } - private static boolean isNumeric( String str ) { + private static boolean isNumeric(String str) { try { - Long.parseLong( str.trim() ); + Long.parseLong(str.trim()); return true; - } catch( NumberFormatException e ) { + } + catch (NumberFormatException e) { return false; } } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/add/model/ModuleConfiguration.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/add/model/ModuleConfiguration.java index 5969f12..68fa281 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/add/model/ModuleConfiguration.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/add/model/ModuleConfiguration.java @@ -107,9 +107,9 @@ public void setVersion(String version) { } public Artifact getResolvedArtifact() { - if ( resolvedArtifact == null ) { - throw new IllegalStateException( "Artifact must be resolved first" ); - } + if (resolvedArtifact == null) { + throw new IllegalStateException("Artifact must be resolved first"); + } return resolvedArtifact; } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/common/model/ArtifactConfiguration.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/common/model/ArtifactConfiguration.java index a64e619..9041924 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/common/model/ArtifactConfiguration.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/common/model/ArtifactConfiguration.java @@ -76,7 +76,8 @@ public void setType(String type) { @Override public String toString() { - return "ArtifactConfiguration [groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + ", classifier=" + classifier + ", type=" + type + "]"; + return "ArtifactConfiguration [groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + ", classifier=" + classifier + ", type=" + type + + "]"; } public void setDependencyString(String dependencyString) { @@ -84,17 +85,17 @@ public void setDependencyString(String dependencyString) { } public String toDependencyString() { - if ( this.dependencyString != null ) { + if (this.dependencyString != null) { return dependencyString; } String dependencyString = groupId + ":" + artifactId + ":" + version; - if ( classifier != null ) { + if (classifier != null) { dependencyString += ":" + classifier; } - if ( type != null ) { + if (type != null) { dependencyString += ":" + type; } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/CompileScopeDependencySelector.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/CompileScopeDependencySelector.java index 9d54d6b..f83aefa 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/CompileScopeDependencySelector.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/CompileScopeDependencySelector.java @@ -36,21 +36,21 @@ public class CompileScopeDependencySelector implements DependencySelector { private boolean level1 = true; - private DependencySelector delegate = new ScopeDependencySelector( "test" ).deriveChildSelector( new MockDependencyCollectionContext() ); + private DependencySelector delegate = new ScopeDependencySelector("test").deriveChildSelector(new MockDependencyCollectionContext()); @Override public boolean selectDependency(Dependency dependency) { - return delegate.selectDependency( dependency ); + return delegate.selectDependency(dependency); } @Override public DependencySelector deriveChildSelector(DependencyCollectionContext context) { - if ( level1 ) { + if (level1) { level1 = false; return this; } else { - return new ScopeDependencySelector( "test", "provided" ).deriveChildSelector( new MockDependencyCollectionContext() ); + return new ScopeDependencySelector("test", "provided").deriveChildSelector(new MockDependencyCollectionContext()); } } @@ -70,7 +70,7 @@ public Artifact getArtifact() { @Override public Dependency getDependency() { - return new Dependency( new DefaultArtifact( "com.example:example:1.0" ), null ); + return new Dependency(new DefaultArtifact("com.example:example:1.0"), null); } @Override diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/GenerateModuleInfoMojo.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/GenerateModuleInfoMojo.java index d42a459..3c5141e 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/GenerateModuleInfoMojo.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/GenerateModuleInfoMojo.java @@ -49,7 +49,7 @@ public class GenerateModuleInfoMojo extends AbstractMojo { @Component private ArtifactHandlerManager artifactHandlerManager; - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; @Parameter(defaultValue = "${project}", readonly = true) @@ -58,10 +58,10 @@ public class GenerateModuleInfoMojo extends AbstractMojo { @Component private RepositorySystem repoSystem; - @Parameter( defaultValue = "${repositorySystemSession}", readonly = true, required = true ) + @Parameter(defaultValue = "${repositorySystemSession}", readonly = true, required = true) private RepositorySystemSession repoSession; - @Parameter( defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true) private List remoteRepos; @Parameter(readonly = true, defaultValue = "${project.build.directory}/moditect") @@ -96,46 +96,43 @@ public class GenerateModuleInfoMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { - // Check if this plugin should be skipped - if (skip) { - getLog().debug("Mojo 'generate-module-info' skipped by configuration"); - return; - } - // Don't try to run this plugin, when packaging type is 'pom' - // (may be better to only run it on specific packaging types, like 'jar') - if (project.getModel().getPackaging().equalsIgnoreCase("pom")) { - getLog().debug("Mojo 'generate-module-info' not executed on packaging type '"+project.getModel().getPackaging()+"'"); - return; - } - - createDirectories(); - - ArtifactResolutionHelper artifactResolutionHelper = new ArtifactResolutionHelper( repoSystem, repoSession, remoteRepos ); + // Check if this plugin should be skipped + if (skip) { + getLog().debug("Mojo 'generate-module-info' skipped by configuration"); + return; + } + // Don't try to run this plugin, when packaging type is 'pom' + // (may be better to only run it on specific packaging types, like 'jar') + if (project.getModel().getPackaging().equalsIgnoreCase("pom")) { + getLog().debug("Mojo 'generate-module-info' not executed on packaging type '" + project.getModel().getPackaging() + "'"); + return; + } + + createDirectories(); + + ArtifactResolutionHelper artifactResolutionHelper = new ArtifactResolutionHelper(repoSystem, repoSession, remoteRepos); ModuleInfoGenerator moduleInfoGenerator = new ModuleInfoGenerator( - project, repoSystem, repoSession, remoteRepos, artifactResolutionHelper, jdepsExtraArgs, getLog(), workingDirectory, outputDirectory - ); + project, repoSystem, repoSession, remoteRepos, artifactResolutionHelper, jdepsExtraArgs, getLog(), workingDirectory, outputDirectory); - Map assignedNamesByModule = getAssignedModuleNamesByModule( artifactResolutionHelper ); + Map assignedNamesByModule = getAssignedModuleNamesByModule(artifactResolutionHelper); - if ( artifactOverride != null ) { + if (artifactOverride != null) { ModuleConfiguration moduleConfiguration = getModuleConfigurationFromOverrides(); moduleInfoGenerator.generateModuleInfo( moduleConfiguration.getArtifact(), moduleConfiguration.getAdditionalDependencies(), moduleConfiguration.getModuleInfo(), assignedNamesByModule, - Collections.emptyMap() - ); + Collections.emptyMap()); } else { - for ( ModuleConfiguration moduleConfiguration : modules ) { + for (ModuleConfiguration moduleConfiguration : modules) { moduleInfoGenerator.generateModuleInfo( moduleConfiguration.getArtifact(), moduleConfiguration.getAdditionalDependencies(), moduleConfiguration.getModuleInfo(), assignedNamesByModule, - Collections.emptyMap() - ); + Collections.emptyMap()); } } } @@ -143,11 +140,10 @@ project, repoSystem, repoSession, remoteRepos, artifactResolutionHelper, jdepsEx private Map getAssignedModuleNamesByModule(ArtifactResolutionHelper artifactResolutionHelper) throws MojoExecutionException { Map assignedNamesByModule = new HashMap<>(); - for ( ModuleConfiguration configuredModule : modules ) { + for (ModuleConfiguration configuredModule : modules) { assignedNamesByModule.put( - new ArtifactIdentifier( artifactResolutionHelper.resolveArtifact( configuredModule.getArtifact() ) ), - configuredModule.getModuleInfo().getName() - ); + new ArtifactIdentifier(artifactResolutionHelper.resolveArtifact(configuredModule.getArtifact())), + configuredModule.getModuleInfo().getName()); } return assignedNamesByModule; @@ -156,31 +152,31 @@ private Map getAssignedModuleNamesByModule(ArtifactR private ModuleConfiguration getModuleConfigurationFromOverrides() { ModuleConfiguration moduleConfiguration = new ModuleConfiguration(); - moduleConfiguration.setArtifact( new ArtifactConfiguration( artifactOverride ) ); - moduleConfiguration.setModuleInfo( new ModuleInfoConfiguration() ); - moduleConfiguration.getModuleInfo().setName( moduleNameOverride ); + moduleConfiguration.setArtifact(new ArtifactConfiguration(artifactOverride)); + moduleConfiguration.setModuleInfo(new ModuleInfoConfiguration()); + moduleConfiguration.getModuleInfo().setName(moduleNameOverride); - if ( additionalDependenciesOverride != null ) { - for ( String additionalDependency : additionalDependenciesOverride.split( "\\," ) ) { - moduleConfiguration.getAdditionalDependencies().add( new ArtifactConfiguration( additionalDependency ) ); + if (additionalDependenciesOverride != null) { + for (String additionalDependency : additionalDependenciesOverride.split("\\,")) { + moduleConfiguration.getAdditionalDependencies().add(new ArtifactConfiguration(additionalDependency)); } } - if ( exportExcludesOverride != null ) { - moduleConfiguration.getModuleInfo().setExports( exportExcludesOverride ); + if (exportExcludesOverride != null) { + moduleConfiguration.getModuleInfo().setExports(exportExcludesOverride); } - moduleConfiguration.getModuleInfo().setAddServiceUses( addServiceUsesOverride ); + moduleConfiguration.getModuleInfo().setAddServiceUses(addServiceUsesOverride); return moduleConfiguration; } private void createDirectories() { - if ( !workingDirectory.exists() ) { + if (!workingDirectory.exists()) { workingDirectory.mkdirs(); } - if ( !outputDirectory.exists() ) { + if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/ModuleInfoGenerator.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/ModuleInfoGenerator.java index f07bc48..44a4df4 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/ModuleInfoGenerator.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/ModuleInfoGenerator.java @@ -62,7 +62,8 @@ public class ModuleInfoGenerator { private final File outputDirectory; public ModuleInfoGenerator(MavenProject project, RepositorySystem repoSystem, RepositorySystemSession repoSession, - List remoteRepos, ArtifactResolutionHelper artifactResolutionHelper, List jdepsExtraArgs, Log log, File workingDirectory, File outputDirectory) { + List remoteRepos, ArtifactResolutionHelper artifactResolutionHelper, List jdepsExtraArgs, Log log, + File workingDirectory, File outputDirectory) { this.project = project; this.repoSystem = repoSystem; this.repoSession = repoSession; @@ -74,62 +75,68 @@ public ModuleInfoGenerator(MavenProject project, RepositorySystem repoSystem, Re this.outputDirectory = outputDirectory; } - public GeneratedModuleInfo generateModuleInfo(ArtifactConfiguration artifact, List additionalDependencies, ModuleInfoConfiguration moduleInfo, Map assignedNamesByModule, Map modularizedJars) throws MojoExecutionException { - log.debug( "Adding module descriptor to artifact " + artifact.toDependencyString() ); + public GeneratedModuleInfo generateModuleInfo(ArtifactConfiguration artifact, List additionalDependencies, ModuleInfoConfiguration moduleInfo, + Map assignedNamesByModule, Map modularizedJars) + throws MojoExecutionException { + log.debug("Adding module descriptor to artifact " + artifact.toDependencyString()); Artifact inputArtifact = artifactResolutionHelper.resolveArtifact(artifact); - Set dependencies = getDependencies( inputArtifact, assignedNamesByModule, modularizedJars ); + Set dependencies = getDependencies(inputArtifact, assignedNamesByModule, modularizedJars); - for( ArtifactConfiguration further : additionalDependencies ) { - Artifact furtherArtifact = artifactResolutionHelper.resolveArtifact( further ); - Path modularized = getModularizedJar( modularizedJars, new ArtifactIdentifier( further.getGroupId(), further.getArtifactId(), further.getVersion(), further.getType(), further.getClassifier() ) ); - dependencies.add( new DependencyDescriptor( modularized != null ? modularized : furtherArtifact.getFile().toPath(), false, null ) ); + for (ArtifactConfiguration further : additionalDependencies) { + Artifact furtherArtifact = artifactResolutionHelper.resolveArtifact(further); + Path modularized = getModularizedJar(modularizedJars, + new ArtifactIdentifier(further.getGroupId(), further.getArtifactId(), further.getVersion(), further.getType(), further.getClassifier())); + dependencies.add(new DependencyDescriptor(modularized != null ? modularized : furtherArtifact.getFile().toPath(), false, null)); } - return generateModuleInfo( inputArtifact.getFile().toPath(), dependencies, moduleInfo ); + return generateModuleInfo(inputArtifact.getFile().toPath(), dependencies, moduleInfo); } - public GeneratedModuleInfo generateModuleInfo(Path inputJar, List additionalDependencies, ModuleInfoConfiguration moduleInfo, Map assignedNamesByModule) throws MojoExecutionException { + public GeneratedModuleInfo generateModuleInfo(Path inputJar, List additionalDependencies, ModuleInfoConfiguration moduleInfo, + Map assignedNamesByModule) + throws MojoExecutionException { Set dependencies = new HashSet<>(); - for( ArtifactConfiguration further : additionalDependencies ) { - Artifact furtherArtifact = artifactResolutionHelper.resolveArtifact( further ); - dependencies.add( new DependencyDescriptor( furtherArtifact.getFile().toPath(), false, null ) ); + for (ArtifactConfiguration further : additionalDependencies) { + Artifact furtherArtifact = artifactResolutionHelper.resolveArtifact(further); + dependencies.add(new DependencyDescriptor(furtherArtifact.getFile().toPath(), false, null)); } - return generateModuleInfo( inputJar, dependencies, moduleInfo ); + return generateModuleInfo(inputJar, dependencies, moduleInfo); } - public GeneratedModuleInfo generateModuleInfo(Path inputJar, Set dependencies, ModuleInfoConfiguration moduleInfo) throws MojoExecutionException { + public GeneratedModuleInfo generateModuleInfo(Path inputJar, Set dependencies, ModuleInfoConfiguration moduleInfo) + throws MojoExecutionException { Set opensResources; - if ( moduleInfo.getOpensResources() != null ) { - opensResources = Arrays.stream( moduleInfo.getOpensResources().split( ";" ) ) - .map( String::trim ) - .collect( Collectors.toSet() ); + if (moduleInfo.getOpensResources() != null) { + opensResources = Arrays.stream(moduleInfo.getOpensResources().split(";")) + .map(String::trim) + .collect(Collectors.toSet()); } else { opensResources = Collections.emptySet(); } - + Set uses; - if ( moduleInfo.getUses() != null ) { - uses = Arrays.stream( moduleInfo.getUses().split( ";" ) ) - .map( String::trim ) - .collect( Collectors.toSet() ); + if (moduleInfo.getUses() != null) { + uses = Arrays.stream(moduleInfo.getUses().split(";")) + .map(String::trim) + .collect(Collectors.toSet()); } else { uses = Collections.emptySet(); } - + Set provides; - if ( moduleInfo.getProvides() != null ) { - provides = Arrays.stream( moduleInfo.getProvides().split( ";" ) ) - .map( String::trim ) - .collect( Collectors.toSet() ); + if (moduleInfo.getProvides() != null) { + provides = Arrays.stream(moduleInfo.getProvides().split(";")) + .map(String::trim) + .collect(Collectors.toSet()); } else { provides = Collections.emptySet(); @@ -140,9 +147,9 @@ public GeneratedModuleInfo generateModuleInfo(Path inputJar, Set getDependencies(Artifact inputArtifact, Map assignedNamesByModule, Map modularizedJars) throws MojoExecutionException { + private Set getDependencies(Artifact inputArtifact, Map assignedNamesByModule, + Map modularizedJars) + throws MojoExecutionException { Set dependencies = new LinkedHashSet<>(); - for ( DependencyNode dependency : artifactResolutionHelper.getCompilationDependencies( inputArtifact ) ) { + for (DependencyNode dependency : artifactResolutionHelper.getCompilationDependencies(inputArtifact)) { Artifact artifact = dependency.getDependency().getArtifact(); // use the version of the dependency as used within the current project's build, if present - String versionFromProject = getVersionFromProject( artifact ); - if ( versionFromProject != null ) { - artifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifact.getExtension(), versionFromProject ); + String versionFromProject = getVersionFromProject(artifact); + if (versionFromProject != null) { + artifact = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifact.getExtension(), versionFromProject); } - Artifact resolvedDependency = artifactResolutionHelper.resolveArtifact( artifact ); - String assignedModuleName = getAssignedModuleName( assignedNamesByModule, new ArtifactIdentifier( resolvedDependency ) ); - Path modularized = getModularizedJar( modularizedJars, new ArtifactIdentifier( resolvedDependency ) ); + Artifact resolvedDependency = artifactResolutionHelper.resolveArtifact(artifact); + String assignedModuleName = getAssignedModuleName(assignedNamesByModule, new ArtifactIdentifier(resolvedDependency)); + Path modularized = getModularizedJar(modularizedJars, new ArtifactIdentifier(resolvedDependency)); dependencies.add( new DependencyDescriptor( modularized != null ? modularized : resolvedDependency.getFile().toPath(), dependency.getDependency().isOptional(), - assignedModuleName - ) - ); + assignedModuleName)); } return dependencies; } private String getAssignedModuleName(Map assignedNamesByModule, ArtifactIdentifier artifactIdentifier) { - for ( Entry assignedNameByModule : assignedNamesByModule.entrySet() ) { + for (Entry assignedNameByModule : assignedNamesByModule.entrySet()) { // ignoring the version; the resolved artifact could have a different version then the one used // in this modularization build - if ( assignedNameByModule.getKey().getGroupId().equals( artifactIdentifier.getGroupId() ) && - assignedNameByModule.getKey().getArtifactId().equals( artifactIdentifier.getArtifactId() ) && - assignedNameByModule.getKey().getClassifier().equals( artifactIdentifier.getClassifier() ) && - assignedNameByModule.getKey().getExtension().equals( artifactIdentifier.getExtension() ) ) { + if (assignedNameByModule.getKey().getGroupId().equals(artifactIdentifier.getGroupId()) && + assignedNameByModule.getKey().getArtifactId().equals(artifactIdentifier.getArtifactId()) && + assignedNameByModule.getKey().getClassifier().equals(artifactIdentifier.getClassifier()) && + assignedNameByModule.getKey().getExtension().equals(artifactIdentifier.getExtension())) { return assignedNameByModule.getValue(); } } @@ -199,13 +205,13 @@ private String getAssignedModuleName(Map assignedNam } private Path getModularizedJar(Map modularizedJars, ArtifactIdentifier artifactIdentifier) { - for ( Entry assignedNameByModule : modularizedJars.entrySet() ) { + for (Entry assignedNameByModule : modularizedJars.entrySet()) { // ignoring the version; the resolved artifact could have a different version than the one used // in this modularization build - if ( assignedNameByModule.getKey().getGroupId().equals( artifactIdentifier.getGroupId() ) && - assignedNameByModule.getKey().getArtifactId().equals( artifactIdentifier.getArtifactId() ) && - areEqualClassifiers( assignedNameByModule.getKey().getClassifier(), artifactIdentifier.getClassifier() ) && - assignedNameByModule.getKey().getExtension().equals( artifactIdentifier.getExtension() ) ) { + if (assignedNameByModule.getKey().getGroupId().equals(artifactIdentifier.getGroupId()) && + assignedNameByModule.getKey().getArtifactId().equals(artifactIdentifier.getArtifactId()) && + areEqualClassifiers(assignedNameByModule.getKey().getClassifier(), artifactIdentifier.getClassifier()) && + assignedNameByModule.getKey().getExtension().equals(artifactIdentifier.getExtension())) { return assignedNameByModule.getValue(); } } @@ -215,32 +221,32 @@ private Path getModularizedJar(Map modularizedJars, Ar private String getVersionFromProject(Artifact artifact) throws MojoExecutionException { Optional resolvedDependency = project.getArtifacts() - .stream() - .filter( a -> { - return Objects.equals( a.getGroupId(), artifact.getGroupId() ) && - Objects.equals( a.getArtifactId(), artifact.getArtifactId() ) && - areEqualClassifiers( a.getClassifier(), artifact.getClassifier() ) && - Objects.equals( a.getType(), artifact.getExtension() ); - } ) - .findFirst(); - - if ( resolvedDependency.isPresent() ) { + .stream() + .filter(a -> { + return Objects.equals(a.getGroupId(), artifact.getGroupId()) && + Objects.equals(a.getArtifactId(), artifact.getArtifactId()) && + areEqualClassifiers(a.getClassifier(), artifact.getClassifier()) && + Objects.equals(a.getType(), artifact.getExtension()); + }) + .findFirst(); + + if (resolvedDependency.isPresent()) { return resolvedDependency.get().getVersion(); } - if ( project.getDependencyManagement() != null ) { + if (project.getDependencyManagement() != null) { Optional managed = project.getDependencyManagement() .getDependencies() .stream() - .filter( d -> { - return Objects.equals( d.getGroupId(), artifact.getGroupId() ) && - Objects.equals( d.getArtifactId(), artifact.getArtifactId() ) && - areEqualClassifiers( d.getClassifier(), artifact.getClassifier() ) && - Objects.equals( d.getType(), artifact.getExtension() ); - } ) + .filter(d -> { + return Objects.equals(d.getGroupId(), artifact.getGroupId()) && + Objects.equals(d.getArtifactId(), artifact.getArtifactId()) && + areEqualClassifiers(d.getClassifier(), artifact.getClassifier()) && + Objects.equals(d.getType(), artifact.getExtension()); + }) .findFirst(); - if ( managed.isPresent() ) { + if (managed.isPresent()) { return managed.get().getVersion(); } } @@ -249,13 +255,13 @@ private String getVersionFromProject(Artifact artifact) throws MojoExecutionExce } private boolean areEqualClassifiers(String classifier1, String classifier2) { - if ( classifier1 != null && classifier1.isEmpty() ) { + if (classifier1 != null && classifier1.isEmpty()) { classifier1 = null; } - if ( classifier2 != null && classifier2.isEmpty() ) { + if (classifier2 != null && classifier2.isEmpty()) { classifier2 = null; } - return Objects.equals( classifier1, classifier2 ); + return Objects.equals(classifier1, classifier2); } } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/model/ArtifactIdentifier.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/model/ArtifactIdentifier.java index 3a8e21b..a927002 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/model/ArtifactIdentifier.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/generate/model/ArtifactIdentifier.java @@ -91,27 +91,32 @@ public boolean equals(Object obj) { if (artifactId == null) { if (other.artifactId != null) return false; - } else if (!artifactId.equals(other.artifactId)) + } + else if (!artifactId.equals(other.artifactId)) return false; if (classifier == null) { if (other.classifier != null) return false; - } else if (!classifier.equals(other.classifier)) + } + else if (!classifier.equals(other.classifier)) return false; if (extension == null) { if (other.extension != null) return false; - } else if (!extension.equals(other.extension)) + } + else if (!extension.equals(other.extension)) return false; if (groupId == null) { if (other.groupId != null) return false; - } else if (!groupId.equals(other.groupId)) + } + else if (!groupId.equals(other.groupId)) return false; if (version == null) { if (other.version != null) return false; - } else if (!version.equals(other.version)) + } + else if (!version.equals(other.version)) return false; return true; } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/image/CreateRuntimeImageMojo.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/image/CreateRuntimeImageMojo.java index f5d4885..980b0a8 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/image/CreateRuntimeImageMojo.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/image/CreateRuntimeImageMojo.java @@ -28,7 +28,6 @@ import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; @@ -39,16 +38,14 @@ import org.apache.maven.toolchain.ToolchainManager; import org.moditect.commands.CreateRuntimeImage; import org.moditect.mavenplugin.image.model.Launcher; -import org.moditect.mavenplugin.util.MojoLog; import org.moditect.mavenplugin.util.DependencyHelper; +import org.moditect.mavenplugin.util.MojoLog; import org.moditect.model.JarInclusionPolicy; /** * @author Gunnar Morling */ -@Mojo(name = "create-runtime-image", - defaultPhase = LifecyclePhase.PACKAGE, - requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) +@Mojo(name = "create-runtime-image", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class CreateRuntimeImageMojo extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true) @@ -57,7 +54,7 @@ public class CreateRuntimeImageMojo extends AbstractMojo { @Component private ToolchainManager toolchainManager; - @Parameter( defaultValue = "${session}", readonly = true ) + @Parameter(defaultValue = "${session}", readonly = true) private MavenSession mavenSession; @Parameter @@ -90,17 +87,17 @@ public class CreateRuntimeImageMojo extends AbstractMojo { @Parameter(property = "ignoreSigningInformation", defaultValue = "false") private boolean ignoreSigningInformation; -// @Parameter(property = "moditect.artifact") -// private String artifactOverride; -// -// @Parameter(property = "moditect.additionalDependencies") -// private String additionalDependenciesOverride; -// -// @Parameter(property = "moditect.moduleName") -// private String moduleNameOverride; -// -// @Parameter(property = "moditect.exportExcludes") -// private String exportExcludesOverride; + // @Parameter(property = "moditect.artifact") + // private String artifactOverride; + // + // @Parameter(property = "moditect.additionalDependencies") + // private String additionalDependenciesOverride; + // + // @Parameter(property = "moditect.moduleName") + // private String moduleNameOverride; + // + // @Parameter(property = "moditect.exportExcludes") + // private String exportExcludesOverride; @Parameter(defaultValue = "false") private boolean noHeaderFiles; @@ -116,32 +113,32 @@ public void execute() throws MojoExecutionException { Path jmodsDir = getJModsDir(); Set effectiveModulePath = this.modulePath.stream() - .map( File::toPath ) - .collect( Collectors.toSet() ); + .map(File::toPath) + .collect(Collectors.toSet()); - effectiveModulePath.add( jmodsDir ); + effectiveModulePath.add(jmodsDir); CreateRuntimeImage createRuntimeImage = new CreateRuntimeImage( - effectiveModulePath, - modules, - jarInclusionPolicy, - DependencyHelper.getDirectAndTransitiveDependencies(project), - project.getArtifact().getFile().toPath(), - launcher != null ? launcher.getName() : null, - launcher != null ? launcher.getModule() : null, - outputDirectory.toPath(), - compression, - stripDebug, - ignoreSigningInformation, - getExcludeResourcesPatterns(), - new MojoLog(getLog()), - noHeaderFiles, - noManPages, - bindServices - ); + effectiveModulePath, + modules, + jarInclusionPolicy, + DependencyHelper.getDirectAndTransitiveDependencies(project), + project.getArtifact().getFile().toPath(), + launcher != null ? launcher.getName() : null, + launcher != null ? launcher.getModule() : null, + outputDirectory.toPath(), + compression, + stripDebug, + ignoreSigningInformation, + getExcludeResourcesPatterns(), + new MojoLog(getLog()), + noHeaderFiles, + noManPages, + bindServices); try { createRuntimeImage.run(); - } catch (IOException ex) { + } + catch (IOException ex) { getLog().error(ex); throw new MojoExecutionException("Error creating runtime image", ex); } @@ -154,54 +151,54 @@ public void execute() throws MojoExecutionException { * will be used. */ private Path getJModsDir() throws MojoExecutionException { - if ( baseJdk != null ) { - List toolChains = toolchainManager.getToolchains( mavenSession, "jdk", getToolChainRequirements( baseJdk ) ); - if ( toolChains.isEmpty() ) { - throw new MojoExecutionException( "Found no tool chain of type 'jdk' and matching requirements '" + baseJdk + "'" ); + if (baseJdk != null) { + List toolChains = toolchainManager.getToolchains(mavenSession, "jdk", getToolChainRequirements(baseJdk)); + if (toolChains.isEmpty()) { + throw new MojoExecutionException("Found no tool chain of type 'jdk' and matching requirements '" + baseJdk + "'"); } - else if ( toolChains.size() > 1 ) { - throw new MojoExecutionException( "Found more than one tool chain of type 'jdk' and matching requirements '" + baseJdk + "'" ); + else if (toolChains.size() > 1) { + throw new MojoExecutionException("Found more than one tool chain of type 'jdk' and matching requirements '" + baseJdk + "'"); } else { - Toolchain toolchain = toolChains.get( 0 ); + Toolchain toolchain = toolChains.get(0); - String javac = toolchain.findTool( "javac" ); + String javac = toolchain.findTool("javac"); // #63; when building on Linux / OS X but creating a Windows runtime image // the tool lookup must be for javac.exe explicitly (as the toolchain mechanism // itself won't append the suffix if not running this build on Windows if (javac == null) { - javac = toolchain.findTool( "javac.exe" ); + javac = toolchain.findTool("javac.exe"); } if (javac == null) { - throw new MojoExecutionException ("Couldn't locate toolchain directory" ); + throw new MojoExecutionException("Couldn't locate toolchain directory"); } - return new File( javac ) + return new File(javac) .toPath() .getParent() .getParent() - .resolve( "jmods" ); + .resolve("jmods"); } } else { - String javaHome = System.getProperty( "java.home" ); - return new File( javaHome ).toPath().resolve( "jmods" ); + String javaHome = System.getProperty("java.home"); + return new File(javaHome).toPath().resolve("jmods"); } } private Map getToolChainRequirements(String baseJdk) throws MojoExecutionException { Map toolChainRequirements = new HashMap<>(); - String[] requirements = baseJdk.split( "," ); + String[] requirements = baseJdk.split(","); for (String requirement : requirements) { String[] keyAndValue = requirement.split("="); - if ( keyAndValue.length != 2 ) { + if (keyAndValue.length != 2) { throw new MojoExecutionException( "Toolchain requirements must be given in the form 'key1=value1,key2=value2,...'." + - "Given value '" + baseJdk + "' doesn't match this pattern." ); + "Given value '" + baseJdk + "' doesn't match this pattern."); } - toolChainRequirements.put( keyAndValue[0].trim(), keyAndValue[1].trim() ); + toolChainRequirements.put(keyAndValue[0].trim(), keyAndValue[1].trim()); } return toolChainRequirements; diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/modulelist/GenerateModuleListMojo.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/modulelist/GenerateModuleListMojo.java index 7123e6e..f755fc0 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/modulelist/GenerateModuleListMojo.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/modulelist/GenerateModuleListMojo.java @@ -15,6 +15,8 @@ */ package org.moditect.mavenplugin.modulelist; +import java.io.File; + import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -27,51 +29,47 @@ import org.moditect.mavenplugin.util.MojoLog; import org.moditect.model.Version; -import java.io.File; - -@Mojo(name = "list-application-image-modules", - defaultPhase = LifecyclePhase.PACKAGE, - requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME -) +@Mojo(name = "list-application-image-modules", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class GenerateModuleListMojo extends AbstractMojo { - @Parameter(defaultValue = "${project}", readonly = true) - protected MavenProject project; + @Parameter(defaultValue = "${project}", readonly = true) + protected MavenProject project; - @Parameter(property = "moditect.jvmVersion") - private Integer jvmVersion; + @Parameter(property = "moditect.jvmVersion") + private Integer jvmVersion; - @Override - public void execute() throws MojoExecutionException { - GenerateModuleList generateModuleList = new GenerateModuleList( - new File(project.getBuild().getOutputDirectory()).toPath(), - // project.getArtifact().getFile().toPath(), - DependencyHelper.getDirectAndTransitiveDependencies(project), - determineJvmVersion(), - new MojoLog(getLog())); - try { - generateModuleList.run(); - } catch (RuntimeException ex) { - getLog().error(ex); - throw new MojoExecutionException("Error generating module list", ex); - } - } + @Override + public void execute() throws MojoExecutionException { + GenerateModuleList generateModuleList = new GenerateModuleList( + new File(project.getBuild().getOutputDirectory()).toPath(), + // project.getArtifact().getFile().toPath(), + DependencyHelper.getDirectAndTransitiveDependencies(project), + determineJvmVersion(), + new MojoLog(getLog())); + try { + generateModuleList.run(); + } + catch (RuntimeException ex) { + getLog().error(ex); + throw new MojoExecutionException("Error generating module list", ex); + } + } - private Version determineJvmVersion() { - if (jvmVersion != null) { - return Version.valueOf(jvmVersion); - } + private Version determineJvmVersion() { + if (jvmVersion != null) { + return Version.valueOf(jvmVersion); + } - Object rawVersion = project.getProperties().get("maven.compiler.release"); - if (rawVersion != null) { - return Version.valueOf(rawVersion); - } + Object rawVersion = project.getProperties().get("maven.compiler.release"); + if (rawVersion != null) { + return Version.valueOf(rawVersion); + } - rawVersion = project.getProperties().get("maven.compiler.target"); - if (rawVersion != null) { - return Version.valueOf(rawVersion); - } + rawVersion = project.getProperties().get("maven.compiler.target"); + if (rawVersion != null) { + return Version.valueOf(rawVersion); + } - throw new IllegalStateException("Couldn't determine target version, please specify the 'targetVersion' configuration property"); - } + throw new IllegalStateException("Couldn't determine target version, please specify the 'targetVersion' configuration property"); + } } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/util/ArtifactResolutionHelper.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/util/ArtifactResolutionHelper.java index 88d2a1f..cbb6a4b 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/util/ArtifactResolutionHelper.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/util/ArtifactResolutionHelper.java @@ -47,7 +47,7 @@ public class ArtifactResolutionHelper { private List remoteRepos; public ArtifactResolutionHelper(RepositorySystem repoSystem, RepositorySystemSession repoSession, - List remoteRepos) { + List remoteRepos) { this.repoSystem = repoSystem; this.repoSession = repoSession; this.remoteRepos = remoteRepos; @@ -60,21 +60,19 @@ public Artifact resolveArtifact(ArtifactConfiguration artifact) throws MojoExecu artifact.getArtifactId(), artifact.getClassifier(), artifact.getType() != null ? artifact.getType() : "jar", - artifact.getVersion() - ) - ); + artifact.getVersion())); } public Artifact resolveArtifact(Artifact inputArtifact) throws MojoExecutionException { ArtifactRequest request = new ArtifactRequest(); - request.setArtifact( inputArtifact ); - request.setRepositories( remoteRepos ); + request.setArtifact(inputArtifact); + request.setRepositories(remoteRepos); try { - return repoSystem.resolveArtifact( repoSession, request ).getArtifact(); + return repoSystem.resolveArtifact(repoSession, request).getArtifact(); } catch (ArtifactResolutionException e) { - throw new MojoExecutionException( e.getMessage(), e ); + throw new MojoExecutionException(e.getMessage(), e); } } @@ -85,30 +83,28 @@ public Artifact resolveArtifact(Artifact inputArtifact) throws MojoExecutionExce */ public List getCompilationDependencies(Artifact inputArtifact) throws MojoExecutionException { try { - CollectRequest collectRequest = new CollectRequest( new Dependency( inputArtifact, "compile" ), remoteRepos ); + CollectRequest collectRequest = new CollectRequest(new Dependency(inputArtifact, "compile"), remoteRepos); DefaultRepositorySystemSession sessionWithProvided = MavenRepositorySystemUtils.newSession(); sessionWithProvided.setDependencySelector( new AndDependencySelector( - new CompileScopeDependencySelector(), - new OptionalDependencySelector(), - new ExclusionDependencySelector() - ) - ); - sessionWithProvided.setLocalRepositoryManager( repoSession.getLocalRepositoryManager() ); + new CompileScopeDependencySelector(), + new OptionalDependencySelector(), + new ExclusionDependencySelector())); + sessionWithProvided.setLocalRepositoryManager(repoSession.getLocalRepositoryManager()); - CollectResult collectResult = repoSystem.collectDependencies( sessionWithProvided, collectRequest ); + CollectResult collectResult = repoSystem.collectDependencies(sessionWithProvided, collectRequest); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); - collectResult.getRoot().accept( nlg ); + collectResult.getRoot().accept(nlg); List dependencies = nlg.getNodes(); // remove the input artifact itself Iterator it = dependencies.iterator(); - while ( it.hasNext() ) { + while (it.hasNext()) { DependencyNode next = it.next(); - if ( next.getDependency() == collectRequest.getRoot() ) { + if (next.getDependency() == collectRequest.getRoot()) { it.remove(); } } @@ -116,7 +112,7 @@ public List getCompilationDependencies(Artifact inputArtifact) t return dependencies; } catch (DependencyCollectionException e) { - throw new MojoExecutionException( "Couldn't collect dependencies of artifact " + inputArtifact, e ); + throw new MojoExecutionException("Couldn't collect dependencies of artifact " + inputArtifact, e); } } } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/util/DependencyHelper.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/util/DependencyHelper.java index 80109b5..acfb115 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/util/DependencyHelper.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/util/DependencyHelper.java @@ -15,19 +15,19 @@ */ package org.moditect.mavenplugin.util; -import org.apache.maven.project.MavenProject; - import java.nio.file.Path; import java.util.Set; import java.util.stream.Collectors; +import org.apache.maven.project.MavenProject; + public class DependencyHelper { - public static Set getDirectAndTransitiveDependencies(MavenProject project) { - return project.getArtifacts() - .stream() - .map(a -> a.getFile().toPath()) - .collect(Collectors.toSet()); - } + public static Set getDirectAndTransitiveDependencies(MavenProject project) { + return project.getArtifacts() + .stream() + .map(a -> a.getFile().toPath()) + .collect(Collectors.toSet()); + } } diff --git a/maven-plugin/src/main/java/org/moditect/mavenplugin/util/MojoLog.java b/maven-plugin/src/main/java/org/moditect/mavenplugin/util/MojoLog.java index a200c8a..9b22406 100644 --- a/maven-plugin/src/main/java/org/moditect/mavenplugin/util/MojoLog.java +++ b/maven-plugin/src/main/java/org/moditect/mavenplugin/util/MojoLog.java @@ -32,21 +32,21 @@ public MojoLog(org.apache.maven.plugin.logging.Log delegate) { @Override public void debug(CharSequence message) { - delegate.debug( message ); + delegate.debug(message); } @Override public void info(CharSequence message) { - delegate.info( message ); + delegate.info(message); } @Override public void warn(CharSequence message) { - delegate.warn( message ); + delegate.warn(message); } @Override public void error(CharSequence message) { - delegate.error( message ); + delegate.error(message); } } diff --git a/parent/pom.xml b/parent/pom.xml index 9a1020d..9ebc2ad 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -24,7 +24,7 @@ org.moditect moditect-org-parent - 1.0.0.Final + 1.3.1.Final @@ -45,19 +45,9 @@ 3.8.7 ${java.version} ${java.version} - 3.2.0 - 3.11.0 - 3.5.0 - 3.1.0 - 3.1.0 - 3.5.0 - 3.3.0 - 4.1 - 1.6.13 - 3.3.0 - 3.2.1 3.0.0-M4 - 2.15.0 + + ${git.commit.author.time}