diff --git a/pom.xml b/pom.xml index b69c505f..c02b5279 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - + - 4.0.0 - maven-plugins org.apache.maven.plugins - 37 + maven-plugins + 39 @@ -34,10 +32,26 @@ maven-plugin Apache Maven Shade Plugin - - Repackages the project classes together with their dependencies into a single uber-jar, optionally renaming classes - or removing unused classes. - + Repackages the project classes together with their dependencies into a single uber-jar, optionally renaming classes + or removing unused classes. + + + + Trask Stalnaker + + + Anthony Dahanne + + + Fabiano Cipriano de Oliveira + + + Markus Karg + + + Torsten Curdt + + ${mavenVersion} @@ -46,8 +60,8 @@ scm:git:https://gitbox.apache.org/repos/asf/maven-shade-plugin.git scm:git:https://gitbox.apache.org/repos/asf/maven-shade-plugin.git - https://github.com/apache/maven-shade-plugin/tree/${project.scm.tag} HEAD + https://github.com/apache/maven-shade-plugin/tree/${project.scm.tag} jira @@ -74,24 +88,6 @@ 2022-10-21T20:02:58Z - - - Trask Stalnaker - - - Anthony Dahanne - - - Fabiano Cipriano de Oliveira - - - Markus Karg - - - Torsten Curdt - - - @@ -280,7 +276,7 @@ src/it/projects/MSHADE-182/src/main/resources/META-INF/services/relocateme.Service src/it/projects/MSHADE-390-sisu-index/** - + org.apache.maven.plugins @@ -362,23 +358,24 @@ org.codehaus.mojo mrm-maven-plugin 1.5.0 - - - - start - stop - - - src/it/mrm/repository - target/mock-repo + target/mock-repo + + + + + start + stop + + + diff --git a/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java b/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java index 16f20d9c..3d14fd21 100644 --- a/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java +++ b/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade; + +import javax.inject.Named; +import javax.inject.Singleton; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; @@ -51,9 +53,6 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipException; -import javax.inject.Named; -import javax.inject.Singleton; - import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.multimap.HashSetValuedHashMap; import org.apache.maven.plugin.MojoExecutionException; @@ -77,90 +76,73 @@ */ @Singleton @Named -public class DefaultShader - implements Shader -{ +public class DefaultShader implements Shader { private static final int BUFFER_SIZE = 32 * 1024; private final Logger logger; - public DefaultShader() - { - this( LoggerFactory.getLogger( DefaultShader.class ) ); + public DefaultShader() { + this(LoggerFactory.getLogger(DefaultShader.class)); } - public DefaultShader( final Logger logger ) - { - this.logger = Objects.requireNonNull( logger ); + public DefaultShader(final Logger logger) { + this.logger = Objects.requireNonNull(logger); } - public void shade( ShadeRequest shadeRequest ) - throws IOException, MojoExecutionException - { + public void shade(ShadeRequest shadeRequest) throws IOException, MojoExecutionException { Set resources = new HashSet<>(); ManifestResourceTransformer manifestTransformer = null; - List transformers = - new ArrayList<>( shadeRequest.getResourceTransformers() ); - for ( Iterator it = transformers.iterator(); it.hasNext(); ) - { + List transformers = new ArrayList<>(shadeRequest.getResourceTransformers()); + for (Iterator it = transformers.iterator(); it.hasNext(); ) { ResourceTransformer transformer = it.next(); - if ( transformer instanceof ManifestResourceTransformer ) - { + if (transformer instanceof ManifestResourceTransformer) { manifestTransformer = (ManifestResourceTransformer) transformer; it.remove(); } } - final DefaultPackageMapper packageMapper = new DefaultPackageMapper( shadeRequest.getRelocators() ); + final DefaultPackageMapper packageMapper = new DefaultPackageMapper(shadeRequest.getRelocators()); // noinspection ResultOfMethodCallIgnored shadeRequest.getUberJar().getParentFile().mkdirs(); - try ( JarOutputStream out = - new JarOutputStream( new BufferedOutputStream( - new CachingOutputStream( shadeRequest.getUberJar() ) ) ) ) - { - goThroughAllJarEntriesForManifestTransformer( shadeRequest, resources, manifestTransformer, out ); + try (JarOutputStream out = + new JarOutputStream(new BufferedOutputStream(new CachingOutputStream(shadeRequest.getUberJar())))) { + goThroughAllJarEntriesForManifestTransformer(shadeRequest, resources, manifestTransformer, out); // CHECKSTYLE_OFF: MagicNumber - MultiValuedMap duplicates = new HashSetValuedHashMap<>( 10000, 3 ); + MultiValuedMap duplicates = new HashSetValuedHashMap<>(10000, 3); // CHECKSTYLE_ON: MagicNumber - shadeJars( shadeRequest, resources, transformers, out, duplicates, packageMapper ); + shadeJars(shadeRequest, resources, transformers, out, duplicates, packageMapper); // CHECKSTYLE_OFF: MagicNumber - MultiValuedMap, String> overlapping = new HashSetValuedHashMap<>( 20, 15 ); + MultiValuedMap, String> overlapping = new HashSetValuedHashMap<>(20, 15); // CHECKSTYLE_ON: MagicNumber - for ( String clazz : duplicates.keySet() ) - { - Collection jarz = duplicates.get( clazz ); - if ( jarz.size() > 1 ) - { - overlapping.put( jarz, clazz ); + for (String clazz : duplicates.keySet()) { + Collection jarz = duplicates.get(clazz); + if (jarz.size() > 1) { + overlapping.put(jarz, clazz); } } // Log a summary of duplicates - logSummaryOfDuplicates( overlapping ); + logSummaryOfDuplicates(overlapping); - if ( overlapping.keySet().size() > 0 ) - { + if (overlapping.keySet().size() > 0) { showOverlappingWarning(); } - for ( ResourceTransformer transformer : transformers ) - { - if ( transformer.hasTransformedResource() ) - { - transformer.modifyOutputStream( out ); + for (ResourceTransformer transformer : transformers) { + if (transformer.hasTransformedResource()) { + transformer.modifyOutputStream(out); } } } - for ( Filter filter : shadeRequest.getFilters() ) - { + for (Filter filter : shadeRequest.getFilters()) { filter.finished(); } } @@ -168,455 +150,411 @@ public void shade( ShadeRequest shadeRequest ) /** * {@link InputStream} that can peek ahead at zip header bytes. */ - private static class ZipHeaderPeekInputStream extends PushbackInputStream - { + private static class ZipHeaderPeekInputStream extends PushbackInputStream { private static final byte[] ZIP_HEADER = new byte[] {0x50, 0x4b, 0x03, 0x04}; private static final int HEADER_LEN = 4; - protected ZipHeaderPeekInputStream( InputStream in ) - { - super( in, HEADER_LEN ); + protected ZipHeaderPeekInputStream(InputStream in) { + super(in, HEADER_LEN); } - public boolean hasZipHeader() throws IOException - { + public boolean hasZipHeader() throws IOException { final byte[] header = new byte[HEADER_LEN]; - int len = super.read( header, 0, HEADER_LEN ); - if ( len != -1 ) - { - super.unread( header, 0, len ); + int len = super.read(header, 0, HEADER_LEN); + if (len != -1) { + super.unread(header, 0, len); } - return Arrays.equals( header, ZIP_HEADER ); + return Arrays.equals(header, ZIP_HEADER); } } /** * Data holder for CRC and Size. */ - private static class CrcAndSize - { + private static class CrcAndSize { private final CRC32 crc = new CRC32(); private long size; - CrcAndSize( InputStream inputStream ) throws IOException - { - load( inputStream ); + CrcAndSize(InputStream inputStream) throws IOException { + load(inputStream); } - private void load( InputStream inputStream ) throws IOException - { + private void load(InputStream inputStream) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; - while ( ( bytesRead = inputStream.read( buffer ) ) != -1 ) - { - this.crc.update( buffer, 0, bytesRead ); + while ((bytesRead = inputStream.read(buffer)) != -1) { + this.crc.update(buffer, 0, bytesRead); this.size += bytesRead; } } - public void setupStoredEntry( JarEntry entry ) - { - entry.setSize( this.size ); - entry.setCompressedSize( this.size ); - entry.setCrc( this.crc.getValue() ); - entry.setMethod( ZipEntry.STORED ); + public void setupStoredEntry(JarEntry entry) { + entry.setSize(this.size); + entry.setCompressedSize(this.size); + entry.setCrc(this.crc.getValue()); + entry.setMethod(ZipEntry.STORED); } } - private void shadeJars( ShadeRequest shadeRequest, Set resources, List transformers, - JarOutputStream jos, MultiValuedMap duplicates, - DefaultPackageMapper packageMapper ) - throws IOException - { - for ( File jar : shadeRequest.getJars() ) - { - - logger.debug( "Processing JAR " + jar ); - - List jarFilters = getFilters( jar, shadeRequest.getFilters() ); - if ( jar.isDirectory() ) - { - shadeDir( shadeRequest, resources, transformers, packageMapper, jos, duplicates, - jar, jar, "", jarFilters ); - } - else - { - shadeJar( shadeRequest, resources, transformers, packageMapper, jos, duplicates, - jar, jarFilters ); + private void shadeJars( + ShadeRequest shadeRequest, + Set resources, + List transformers, + JarOutputStream jos, + MultiValuedMap duplicates, + DefaultPackageMapper packageMapper) + throws IOException { + for (File jar : shadeRequest.getJars()) { + + logger.debug("Processing JAR " + jar); + + List jarFilters = getFilters(jar, shadeRequest.getFilters()); + if (jar.isDirectory()) { + shadeDir( + shadeRequest, + resources, + transformers, + packageMapper, + jos, + duplicates, + jar, + jar, + "", + jarFilters); + } else { + shadeJar(shadeRequest, resources, transformers, packageMapper, jos, duplicates, jar, jarFilters); } } } - private void shadeDir( ShadeRequest shadeRequest, Set resources, - List transformers, DefaultPackageMapper packageMapper, - JarOutputStream jos, MultiValuedMap duplicates, - File jar, File current, String prefix, List jarFilters ) throws IOException - { + private void shadeDir( + ShadeRequest shadeRequest, + Set resources, + List transformers, + DefaultPackageMapper packageMapper, + JarOutputStream jos, + MultiValuedMap duplicates, + File jar, + File current, + String prefix, + List jarFilters) + throws IOException { final File[] children = current.listFiles(); - if ( children == null ) - { + if (children == null) { return; } - for ( final File file : children ) - { - final String name = prefix + file.getName(); - if ( file.isDirectory() ) - { - try - { + for (final File file : children) { + final String name = prefix + file.getName(); + if (file.isDirectory()) { + try { shadeDir( - shadeRequest, resources, transformers, packageMapper, jos, - duplicates, jar, file, - prefix + file.getName() + '/', jarFilters ); + shadeRequest, + resources, + transformers, + packageMapper, + jos, + duplicates, + jar, + file, + prefix + file.getName() + '/', + jarFilters); continue; - } - catch ( Exception e ) - { - throw new IOException( - String.format( "Problem shading JAR %s entry %s: %s", current, name, e ), e ); + } catch (Exception e) { + throw new IOException(String.format("Problem shading JAR %s entry %s: %s", current, name, e), e); } } - if ( isFiltered( jarFilters, name ) || isExcludedEntry( name ) ) - { + if (isFiltered(jarFilters, name) || isExcludedEntry(name)) { continue; } - try - { + try { shadeJarEntry( - shadeRequest, resources, transformers, packageMapper, jos, duplicates, jar, - new Callable() - { + shadeRequest, + resources, + transformers, + packageMapper, + jos, + duplicates, + jar, + new Callable() { @Override - public InputStream call() throws Exception - { - return new FileInputStream( file ); + public InputStream call() throws Exception { + return new FileInputStream(file); } - }, name, file.lastModified(), -1 /*ignore*/ ); - } - catch ( Exception e ) - { - throw new IOException( String.format( "Problem shading JAR %s entry %s: %s", current, name, e ), - e ); + }, + name, + file.lastModified(), + -1 /*ignore*/); + } catch (Exception e) { + throw new IOException(String.format("Problem shading JAR %s entry %s: %s", current, name, e), e); } } } - private void shadeJar( ShadeRequest shadeRequest, Set resources, - List transformers, DefaultPackageMapper packageMapper, - JarOutputStream jos, MultiValuedMap duplicates, - File jar, List jarFilters ) throws IOException - { - try ( JarFile jarFile = newJarFile( jar ) ) - { - - for ( Enumeration j = jarFile.entries(); j.hasMoreElements(); ) - { + private void shadeJar( + ShadeRequest shadeRequest, + Set resources, + List transformers, + DefaultPackageMapper packageMapper, + JarOutputStream jos, + MultiValuedMap duplicates, + File jar, + List jarFilters) + throws IOException { + try (JarFile jarFile = newJarFile(jar)) { + + for (Enumeration j = jarFile.entries(); j.hasMoreElements(); ) { final JarEntry entry = j.nextElement(); String name = entry.getName(); - if ( entry.isDirectory() || isFiltered( jarFilters, name ) || isExcludedEntry( name ) ) - { + if (entry.isDirectory() || isFiltered(jarFilters, name) || isExcludedEntry(name)) { continue; } - try - { + try { shadeJarEntry( - shadeRequest, resources, transformers, packageMapper, jos, duplicates, jar, - new Callable() - { + shadeRequest, + resources, + transformers, + packageMapper, + jos, + duplicates, + jar, + new Callable() { @Override - public InputStream call() throws Exception - { - return jarFile.getInputStream( entry ); + public InputStream call() throws Exception { + return jarFile.getInputStream(entry); } - }, name, entry.getTime(), entry.getMethod() ); - } - catch ( Exception e ) - { - throw new IOException( String.format( "Problem shading JAR %s entry %s: %s", jar, name, e ), - e ); + }, + name, + entry.getTime(), + entry.getMethod()); + } catch (Exception e) { + throw new IOException(String.format("Problem shading JAR %s entry %s: %s", jar, name, e), e); } } - } } - private boolean isExcludedEntry( final String name ) - { - if ( "META-INF/INDEX.LIST".equals( name ) ) - { + private boolean isExcludedEntry(final String name) { + if ("META-INF/INDEX.LIST".equals(name)) { // we cannot allow the jar indexes to be copied over or the // jar is useless. Ideally, we could create a new one // later return true; } - if ( "module-info.class".equals( name ) ) - { - logger.warn( "Discovered module-info.class. " - + "Shading will break its strong encapsulation." ); + if ("module-info.class".equals(name)) { + logger.warn("Discovered module-info.class. " + "Shading will break its strong encapsulation."); return true; } return false; } - private void shadeJarEntry( ShadeRequest shadeRequest, Set resources, - List transformers, DefaultPackageMapper packageMapper, - JarOutputStream jos, MultiValuedMap duplicates, File jar, - Callable inputProvider, String name, long time, int method ) - throws Exception - { - try ( InputStream in = inputProvider.call() ) - { - String mappedName = packageMapper.map( name, true, false ); - - int idx = mappedName.lastIndexOf( '/' ); - if ( idx != -1 ) - { + private void shadeJarEntry( + ShadeRequest shadeRequest, + Set resources, + List transformers, + DefaultPackageMapper packageMapper, + JarOutputStream jos, + MultiValuedMap duplicates, + File jar, + Callable inputProvider, + String name, + long time, + int method) + throws Exception { + try (InputStream in = inputProvider.call()) { + String mappedName = packageMapper.map(name, true, false); + + int idx = mappedName.lastIndexOf('/'); + if (idx != -1) { // make sure dirs are created - String dir = mappedName.substring( 0, idx ); - if ( !resources.contains( dir ) ) - { - addDirectory( resources, jos, dir, time ); + String dir = mappedName.substring(0, idx); + if (!resources.contains(dir)) { + addDirectory(resources, jos, dir, time); } } - duplicates.put( name, jar ); - if ( name.endsWith( ".class" ) ) - { - addRemappedClass( jos, jar, name, time, in, packageMapper ); - } - else if ( shadeRequest.isShadeSourcesContent() && name.endsWith( ".java" ) ) - { + duplicates.put(name, jar); + if (name.endsWith(".class")) { + addRemappedClass(jos, jar, name, time, in, packageMapper); + } else if (shadeRequest.isShadeSourcesContent() && name.endsWith(".java")) { // Avoid duplicates - if ( resources.contains( mappedName ) ) - { + if (resources.contains(mappedName)) { return; } - addJavaSource( resources, jos, mappedName, time, in, shadeRequest.getRelocators() ); - } - else - { - if ( !resourceTransformed( transformers, mappedName, in, shadeRequest.getRelocators(), - time ) ) - { + addJavaSource(resources, jos, mappedName, time, in, shadeRequest.getRelocators()); + } else { + if (!resourceTransformed(transformers, mappedName, in, shadeRequest.getRelocators(), time)) { // Avoid duplicates that aren't accounted for by the resource transformers - if ( resources.contains( mappedName ) ) - { - logger.debug( "We have a duplicate " + name + " in " + jar ); + if (resources.contains(mappedName)) { + logger.debug("We have a duplicate " + name + " in " + jar); return; } - addResource( resources, jos, mappedName, inputProvider, time, method ); - } - else - { - duplicates.removeMapping( name, jar ); + addResource(resources, jos, mappedName, inputProvider, time, method); + } else { + duplicates.removeMapping(name, jar); } } } } - private void goThroughAllJarEntriesForManifestTransformer( ShadeRequest shadeRequest, Set resources, - ManifestResourceTransformer manifestTransformer, - JarOutputStream jos ) - throws IOException - { - if ( manifestTransformer != null ) - { - for ( File jar : shadeRequest.getJars() ) - { - try ( JarFile jarFile = newJarFile( jar ) ) - { - for ( Enumeration en = jarFile.entries(); en.hasMoreElements(); ) - { + private void goThroughAllJarEntriesForManifestTransformer( + ShadeRequest shadeRequest, + Set resources, + ManifestResourceTransformer manifestTransformer, + JarOutputStream jos) + throws IOException { + if (manifestTransformer != null) { + for (File jar : shadeRequest.getJars()) { + try (JarFile jarFile = newJarFile(jar)) { + for (Enumeration en = jarFile.entries(); en.hasMoreElements(); ) { JarEntry entry = en.nextElement(); String resource = entry.getName(); - if ( manifestTransformer.canTransformResource( resource ) ) - { - resources.add( resource ); - try ( InputStream inputStream = jarFile.getInputStream( entry ) ) - { - manifestTransformer.processResource( resource, inputStream, - shadeRequest.getRelocators(), entry.getTime() ); + if (manifestTransformer.canTransformResource(resource)) { + resources.add(resource); + try (InputStream inputStream = jarFile.getInputStream(entry)) { + manifestTransformer.processResource( + resource, inputStream, shadeRequest.getRelocators(), entry.getTime()); } break; } } } } - if ( manifestTransformer.hasTransformedResource() ) - { - manifestTransformer.modifyOutputStream( jos ); + if (manifestTransformer.hasTransformedResource()) { + manifestTransformer.modifyOutputStream(jos); } } } - private void showOverlappingWarning() - { - logger.warn( "maven-shade-plugin has detected that some files are" ); - logger.warn( "present in two or more JARs. When this happens, only one" ); - logger.warn( "single version of the file is copied to the uber jar." ); - logger.warn( "Usually this is not harmful and you can skip these warnings," ); - logger.warn( "otherwise try to manually exclude artifacts based on" ); - logger.warn( "mvn dependency:tree -Ddetail=true and the above output." ); - logger.warn( "See https://maven.apache.org/plugins/maven-shade-plugin/" ); + private void showOverlappingWarning() { + logger.warn("maven-shade-plugin has detected that some files are"); + logger.warn("present in two or more JARs. When this happens, only one"); + logger.warn("single version of the file is copied to the uber jar."); + logger.warn("Usually this is not harmful and you can skip these warnings,"); + logger.warn("otherwise try to manually exclude artifacts based on"); + logger.warn("mvn dependency:tree -Ddetail=true and the above output."); + logger.warn("See https://maven.apache.org/plugins/maven-shade-plugin/"); } - private void logSummaryOfDuplicates( MultiValuedMap, String> overlapping ) - { - for ( Collection jarz : overlapping.keySet() ) - { + private void logSummaryOfDuplicates(MultiValuedMap, String> overlapping) { + for (Collection jarz : overlapping.keySet()) { List jarzS = new ArrayList<>(); - for ( File jjar : jarz ) - { - jarzS.add( jjar.getName() ); + for (File jjar : jarz) { + jarzS.add(jjar.getName()); } - Collections.sort( jarzS ); // deterministic messages to be able to compare outputs (useful on CI) + Collections.sort(jarzS); // deterministic messages to be able to compare outputs (useful on CI) List classes = new LinkedList<>(); List resources = new LinkedList<>(); - for ( String name : overlapping.get( jarz ) ) - { - if ( name.endsWith( ".class" ) ) - { - classes.add( name.replace( ".class", "" ).replace( "/", "." ) ); - } - else - { - resources.add( name ); + for (String name : overlapping.get(jarz)) { + if (name.endsWith(".class")) { + classes.add(name.replace(".class", "").replace("/", ".")); + } else { + resources.add(name); } } - //CHECKSTYLE_OFF: LineLength + // CHECKSTYLE_OFF: LineLength final Collection overlaps = new ArrayList<>(); - if ( !classes.isEmpty() ) - { - if ( resources.size() == 1 ) - { - overlaps.add( "class" ); - } - else - { - overlaps.add( "classes" ); + if (!classes.isEmpty()) { + if (resources.size() == 1) { + overlaps.add("class"); + } else { + overlaps.add("classes"); } } - if ( !resources.isEmpty() ) - { - if ( resources.size() == 1 ) - { - overlaps.add( "resource" ); - } - else - { - overlaps.add( "resources" ); + if (!resources.isEmpty()) { + if (resources.size() == 1) { + overlaps.add("resource"); + } else { + overlaps.add("resources"); } } - final List all = new ArrayList<>( classes.size() + resources.size() ); - all.addAll( classes ); - all.addAll( resources ); + final List all = new ArrayList<>(classes.size() + resources.size()); + all.addAll(classes); + all.addAll(resources); - logger.warn( - String.join( ", ", jarzS ) + " define " + all.size() - + " overlapping " + String.join( " and ", overlaps ) + ": " ); - //CHECKSTYLE_ON: LineLength + logger.warn(String.join(", ", jarzS) + " define " + all.size() + " overlapping " + + String.join(" and ", overlaps) + ": "); + // CHECKSTYLE_ON: LineLength - Collections.sort( all ); + Collections.sort(all); int max = 10; - for ( int i = 0; i < Math.min( max, all.size() ); i++ ) - { - logger.warn( " - " + all.get( i ) ); + for (int i = 0; i < Math.min(max, all.size()); i++) { + logger.warn(" - " + all.get(i)); } - if ( all.size() > max ) - { - logger.warn( " - " + ( all.size() - max ) + " more..." ); + if (all.size() > max) { + logger.warn(" - " + (all.size() - max) + " more..."); } - } } - private JarFile newJarFile( File jar ) - throws IOException - { - try - { - return new JarFile( jar ); - } - catch ( ZipException zex ) - { + private JarFile newJarFile(File jar) throws IOException { + try { + return new JarFile(jar); + } catch (ZipException zex) { // JarFile is not very verbose and doesn't tell the user which file it was // so we will create a new Exception instead - throw new ZipException( "error in opening zip file " + jar ); + throw new ZipException("error in opening zip file " + jar); } } - private List getFilters( File jar, List filters ) - { + private List getFilters(File jar, List filters) { List list = new ArrayList<>(); - for ( Filter filter : filters ) - { - if ( filter.canFilter( jar ) ) - { - list.add( filter ); + for (Filter filter : filters) { + if (filter.canFilter(jar)) { + list.add(filter); } - } return list; } - private void addDirectory( Set resources, JarOutputStream jos, String name, long time ) - throws IOException - { - if ( name.lastIndexOf( '/' ) > 0 ) - { - String parent = name.substring( 0, name.lastIndexOf( '/' ) ); - if ( !resources.contains( parent ) ) - { - addDirectory( resources, jos, parent, time ); + private void addDirectory(Set resources, JarOutputStream jos, String name, long time) throws IOException { + if (name.lastIndexOf('/') > 0) { + String parent = name.substring(0, name.lastIndexOf('/')); + if (!resources.contains(parent)) { + addDirectory(resources, jos, parent, time); } } // directory entries must end in "/" - JarEntry entry = new JarEntry( name + "/" ); - entry.setTime( time ); - jos.putNextEntry( entry ); + JarEntry entry = new JarEntry(name + "/"); + entry.setTime(time); + jos.putNextEntry(entry); - resources.add( name ); + resources.add(name); } - private void addRemappedClass( JarOutputStream jos, File jar, String name, - long time, InputStream is, DefaultPackageMapper packageMapper ) - throws IOException, MojoExecutionException - { - if ( packageMapper.relocators.isEmpty() ) - { - try - { - JarEntry entry = new JarEntry( name ); - entry.setTime( time ); - jos.putNextEntry( entry ); - IOUtil.copy( is, jos ); - } - catch ( ZipException e ) - { - logger.debug( "We have a duplicate " + name + " in " + jar ); + private void addRemappedClass( + JarOutputStream jos, File jar, String name, long time, InputStream is, DefaultPackageMapper packageMapper) + throws IOException, MojoExecutionException { + if (packageMapper.relocators.isEmpty()) { + try { + JarEntry entry = new JarEntry(name); + entry.setTime(time); + jos.putNextEntry(entry); + IOUtil.copy(is, jos); + } catch (ZipException e) { + logger.debug("We have a duplicate " + name + " in " + jar); } return; @@ -625,66 +563,54 @@ private void addRemappedClass( JarOutputStream jos, File jar, String name, // Keep the original class, in case nothing was relocated by ShadeClassRemapper. This avoids binary // differences between classes, simply because they were rewritten and only details like constant pool or // stack map frames are slightly different. - byte[] originalClass = IOUtil.toByteArray( is ); + byte[] originalClass = IOUtil.toByteArray(is); - ClassReader cr = new ClassReader( new ByteArrayInputStream( originalClass ) ); + ClassReader cr = new ClassReader(new ByteArrayInputStream(originalClass)); // We don't pass the ClassReader here. This forces the ClassWriter to rebuild the constant pool. // Copying the original constant pool should be avoided because it would keep references // to the original class names. This is not a problem at runtime (because these entries in the // constant pool are never used), but confuses some tools such as Felix' maven-bundle-plugin // that use the constant pool to determine the dependencies of a class. - ClassWriter cw = new ClassWriter( 0 ); + ClassWriter cw = new ClassWriter(0); - final String pkg = name.substring( 0, name.lastIndexOf( '/' ) + 1 ); - final ShadeClassRemapper cv = new ShadeClassRemapper( cw, pkg, packageMapper ); + final String pkg = name.substring(0, name.lastIndexOf('/') + 1); + final ShadeClassRemapper cv = new ShadeClassRemapper(cw, pkg, packageMapper); - try - { - cr.accept( cv, ClassReader.EXPAND_FRAMES ); - } - catch ( Throwable ise ) - { - throw new MojoExecutionException( "Error in ASM processing class " + name, ise ); + try { + cr.accept(cv, ClassReader.EXPAND_FRAMES); + } catch (Throwable ise) { + throw new MojoExecutionException("Error in ASM processing class " + name, ise); } // If nothing was relocated by ShadeClassRemapper, write the original class, otherwise the transformed one final byte[] renamedClass; - if ( cv.remapped ) - { - logger.debug( "Rewrote class bytecode: " + name ); + if (cv.remapped) { + logger.debug("Rewrote class bytecode: " + name); renamedClass = cw.toByteArray(); - } - else - { - logger.debug( "Keeping original class bytecode: " + name ); + } else { + logger.debug("Keeping original class bytecode: " + name); renamedClass = originalClass; } // Need to take the .class off for remapping evaluation - String mappedName = packageMapper.map( name.substring( 0, name.indexOf( '.' ) ), true, false ); + String mappedName = packageMapper.map(name.substring(0, name.indexOf('.')), true, false); - try - { + try { // Now we put it back on so the class file is written out with the right extension. - JarEntry entry = new JarEntry( mappedName + ".class" ); - entry.setTime( time ); - jos.putNextEntry( entry ); + JarEntry entry = new JarEntry(mappedName + ".class"); + entry.setTime(time); + jos.putNextEntry(entry); - jos.write( renamedClass ); - } - catch ( ZipException e ) - { - logger.debug( "We have a duplicate " + mappedName + " in " + jar ); + jos.write(renamedClass); + } catch (ZipException e) { + logger.debug("We have a duplicate " + mappedName + " in " + jar); } } - private boolean isFiltered( List filters, String name ) - { - for ( Filter filter : filters ) - { - if ( filter.isFiltered( name ) ) - { + private boolean isFiltered(List filters, String name) { + for (Filter filter : filters) { + if (filter.isFiltered(name)) { return true; } } @@ -692,25 +618,24 @@ private boolean isFiltered( List filters, String name ) return false; } - private boolean resourceTransformed( List resourceTransformers, String name, InputStream is, - List relocators, long time ) - throws IOException - { + private boolean resourceTransformed( + List resourceTransformers, + String name, + InputStream is, + List relocators, + long time) + throws IOException { boolean resourceTransformed = false; - for ( ResourceTransformer transformer : resourceTransformers ) - { - if ( transformer.canTransformResource( name ) ) - { - logger.debug( "Transforming " + name + " using " + transformer.getClass().getName() ); + for (ResourceTransformer transformer : resourceTransformers) { + if (transformer.canTransformResource(name)) { + logger.debug("Transforming " + name + " using " + + transformer.getClass().getName()); - if ( transformer instanceof ReproducibleResourceTransformer ) - { - ( (ReproducibleResourceTransformer) transformer ).processResource( name, is, relocators, time ); - } - else - { - transformer.processResource( name, is, relocators ); + if (transformer instanceof ReproducibleResourceTransformer) { + ((ReproducibleResourceTransformer) transformer).processResource(name, is, relocators, time); + } else { + transformer.processResource(name, is, relocators); } resourceTransformed = true; @@ -721,61 +646,58 @@ private boolean resourceTransformed( List resourceTransform return resourceTransformed; } - private void addJavaSource( Set resources, JarOutputStream jos, String name, long time, InputStream is, - List relocators ) - throws IOException - { - JarEntry entry = new JarEntry( name ); - entry.setTime( time ); - jos.putNextEntry( entry ); + private void addJavaSource( + Set resources, + JarOutputStream jos, + String name, + long time, + InputStream is, + List relocators) + throws IOException { + JarEntry entry = new JarEntry(name); + entry.setTime(time); + jos.putNextEntry(entry); - String sourceContent = IOUtil.toString( new InputStreamReader( is, StandardCharsets.UTF_8 ) ); + String sourceContent = IOUtil.toString(new InputStreamReader(is, StandardCharsets.UTF_8)); - for ( Relocator relocator : relocators ) - { - sourceContent = relocator.applyToSourceContent( sourceContent ); + for (Relocator relocator : relocators) { + sourceContent = relocator.applyToSourceContent(sourceContent); } - final Writer writer = new OutputStreamWriter( jos, StandardCharsets.UTF_8 ); - writer.write( sourceContent ); + final Writer writer = new OutputStreamWriter(jos, StandardCharsets.UTF_8); + writer.write(sourceContent); writer.flush(); - resources.add( name ); + resources.add(name); } - private void addResource( Set resources, JarOutputStream jos, String name, Callable input, - long time, int method ) throws Exception - { - ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( input.call() ); - try - { - final JarEntry entry = new JarEntry( name ); + private void addResource( + Set resources, JarOutputStream jos, String name, Callable input, long time, int method) + throws Exception { + ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(input.call()); + try { + final JarEntry entry = new JarEntry(name); // We should not change compressed level of uncompressed entries, otherwise JVM can't load these nested jars - if ( inputStream.hasZipHeader() && method == ZipEntry.STORED ) - { - new CrcAndSize( inputStream ).setupStoredEntry( entry ); + if (inputStream.hasZipHeader() && method == ZipEntry.STORED) { + new CrcAndSize(inputStream).setupStoredEntry(entry); inputStream.close(); - inputStream = new ZipHeaderPeekInputStream( input.call() ); + inputStream = new ZipHeaderPeekInputStream(input.call()); } + entry.setTime(time); - entry.setTime( time ); - - jos.putNextEntry( entry ); + jos.putNextEntry(entry); - IOUtil.copy( inputStream, jos ); + IOUtil.copy(inputStream, jos); - resources.add( name ); - } - finally - { + resources.add(name); + } finally { inputStream.close(); } } - private interface PackageMapper - { + private interface PackageMapper { /** * Map an entity name according to the mapping rules known to this package mapper * @@ -784,49 +706,41 @@ private interface PackageMapper * @param mapPackages map "dotty" names like qualified Java class or package names, e.g. {@code com.acme.Foo}? * @return mapped entity name, e.g. {@code org/apache/acme/Foo} or {@code org.apache.acme.Foo} */ - String map( String entityName, boolean mapPaths, boolean mapPackages ); + String map(String entityName, boolean mapPaths, boolean mapPackages); } /** * A package mapper based on a list of {@link Relocator}s */ - private static class DefaultPackageMapper implements PackageMapper - { - private static final Pattern CLASS_PATTERN = Pattern.compile( "(\\[*)?L(.+);" ); + private static class DefaultPackageMapper implements PackageMapper { + private static final Pattern CLASS_PATTERN = Pattern.compile("(\\[*)?L(.+);"); private final List relocators; - private DefaultPackageMapper( final List relocators ) - { + private DefaultPackageMapper(final List relocators) { this.relocators = relocators; } @Override - public String map( String entityName, boolean mapPaths, final boolean mapPackages ) - { + public String map(String entityName, boolean mapPaths, final boolean mapPackages) { String value = entityName; String prefix = ""; String suffix = ""; - Matcher m = CLASS_PATTERN.matcher( entityName ); - if ( m.matches() ) - { - prefix = m.group( 1 ) + "L"; + Matcher m = CLASS_PATTERN.matcher(entityName); + if (m.matches()) { + prefix = m.group(1) + "L"; suffix = ";"; - entityName = m.group( 2 ); + entityName = m.group(2); } - for ( Relocator r : relocators ) - { - if ( mapPackages && r.canRelocateClass( entityName ) ) - { - value = prefix + r.relocateClass( entityName ) + suffix; + for (Relocator r : relocators) { + if (mapPackages && r.canRelocateClass(entityName)) { + value = prefix + r.relocateClass(entityName) + suffix; break; - } - else if ( mapPaths && r.canRelocatePath( entityName ) ) - { - value = prefix + r.relocatePath( entityName ) + suffix; + } else if (mapPaths && r.canRelocatePath(entityName)) { + value = prefix + r.relocatePath(entityName) + suffix; break; } } @@ -834,21 +748,16 @@ else if ( mapPaths && r.canRelocatePath( entityName ) ) } } - private static class LazyInitRemapper extends Remapper - { + private static class LazyInitRemapper extends Remapper { private PackageMapper relocators; @Override - public Object mapValue( Object object ) - { - return object instanceof String - ? relocators.map( (String) object, true, true ) - : super.mapValue( object ); + public Object mapValue(Object object) { + return object instanceof String ? relocators.map((String) object, true, true) : super.mapValue(object); } @Override - public String map( String name ) - { + public String map(String name) { // NOTE: Before the factoring out duplicate code from 'private String map(String, boolean)', this method did // the same as 'mapValue', except for not trying to replace "dotty" package-like patterns (only "slashy" // path-like ones). The refactoring retains this difference. But actually, all unit and integration tests @@ -857,7 +766,7 @@ public String map( String name ) // TODO: Analyse if this case is really necessary and has any special meaning or avoids any known problems. // If not, then simplify DefaultShader.PackageMapper.map to only have the String parameter and assume // both boolean ones to always be true. - return relocators.map( name, true, false ); + return relocators.map(name, true, false); } } @@ -871,45 +780,39 @@ public String map( String name ) // since multithreading is not faster in this processing it would be more than sufficient if // caring of this 2 objects per class allocation (but keep in mind the visitor will allocate way more ;)). // Last point which makes it done this way as of now is that perf seems not impacted at all. - private static class ShadeClassRemapper extends ClassRemapper implements PackageMapper - { + private static class ShadeClassRemapper extends ClassRemapper implements PackageMapper { private final String pkg; private final PackageMapper packageMapper; private boolean remapped; - ShadeClassRemapper( final ClassVisitor classVisitor, final String pkg, - final DefaultPackageMapper packageMapper ) - { - super( classVisitor, new LazyInitRemapper() /* can't be init in the constructor with "this" */ ); + ShadeClassRemapper( + final ClassVisitor classVisitor, final String pkg, final DefaultPackageMapper packageMapper) { + super(classVisitor, new LazyInitRemapper() /* can't be init in the constructor with "this" */); this.pkg = pkg; this.packageMapper = packageMapper; // use this to enrich relocators impl with "remapped" logic - LazyInitRemapper.class.cast( remapper ).relocators = this; + LazyInitRemapper.class.cast(remapper).relocators = this; } @Override - public void visitSource( final String source, final String debug ) - { - if ( source == null ) - { - super.visitSource( null, debug ); + public void visitSource(final String source, final String debug) { + if (source == null) { + super.visitSource(null, debug); return; } final String fqSource = pkg + source; - final String mappedSource = map( fqSource, true, false ); - final String filename = mappedSource.substring( mappedSource.lastIndexOf( '/' ) + 1 ); - super.visitSource( filename, debug ); + final String mappedSource = map(fqSource, true, false); + final String filename = mappedSource.substring(mappedSource.lastIndexOf('/') + 1); + super.visitSource(filename, debug); } @Override - public String map( final String entityName, boolean mapPaths, final boolean mapPackages ) - { - final String mapped = packageMapper.map( entityName, true, mapPackages ); - if ( !remapped ) - { - remapped = !mapped.equals( entityName ); + public String map(final String entityName, boolean mapPaths, final boolean mapPackages) { + final String mapped = packageMapper.map(entityName, true, mapPackages); + if (!remapped) { + remapped = !mapped.equals(entityName); } return mapped; } diff --git a/src/main/java/org/apache/maven/plugins/shade/ShadeRequest.java b/src/main/java/org/apache/maven/plugins/shade/ShadeRequest.java index 7d1376a2..c7781452 100644 --- a/src/main/java/org/apache/maven/plugins/shade/ShadeRequest.java +++ b/src/main/java/org/apache/maven/plugins/shade/ShadeRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,21 +16,21 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.filter.Filter; -import org.apache.maven.plugins.shade.relocation.Relocator; -import org.apache.maven.plugins.shade.resource.ResourceTransformer; +package org.apache.maven.plugins.shade; import java.io.File; import java.util.List; import java.util.Set; +import org.apache.maven.plugins.shade.filter.Filter; +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.apache.maven.plugins.shade.resource.ResourceTransformer; + /** * Parameter object used to pass multitude of args to Shader.shade() * @since 2.0 */ -public class ShadeRequest -{ +public class ShadeRequest { private Set jars; @@ -46,8 +44,7 @@ public class ShadeRequest private boolean shadeSourcesContent; - public Set getJars() - { + public Set getJars() { return jars; } @@ -56,13 +53,11 @@ public Set getJars() * * @param jars The jars. */ - public void setJars( Set jars ) - { + public void setJars(Set jars) { this.jars = jars; } - public File getUberJar() - { + public File getUberJar() { return uberJar; } @@ -71,13 +66,11 @@ public File getUberJar() * * @param uberJar The ueberJar file. */ - public void setUberJar( File uberJar ) - { + public void setUberJar(File uberJar) { this.uberJar = uberJar; } - public List getFilters() - { + public List getFilters() { return filters; } @@ -86,13 +79,11 @@ public List getFilters() * * @param filters The filters */ - public void setFilters( List filters ) - { + public void setFilters(List filters) { this.filters = filters; } - public List getRelocators() - { + public List getRelocators() { return relocators; } @@ -101,13 +92,11 @@ public List getRelocators() * * @param relocators The relocators. */ - public void setRelocators( List relocators ) - { + public void setRelocators(List relocators) { this.relocators = relocators; } - public List getResourceTransformers() - { + public List getResourceTransformers() { return resourceTransformers; } @@ -116,13 +105,11 @@ public List getResourceTransformers() * * @param resourceTransformers List of resourceTransformers. */ - public void setResourceTransformers( List resourceTransformers ) - { + public void setResourceTransformers(List resourceTransformers) { this.resourceTransformers = resourceTransformers; } - public boolean isShadeSourcesContent() - { + public boolean isShadeSourcesContent() { return shadeSourcesContent; } @@ -133,8 +120,7 @@ public boolean isShadeSourcesContent() * * @param shadeSourcesContent {@code true} or {@code false}. */ - public void setShadeSourcesContent( boolean shadeSourcesContent ) - { + public void setShadeSourcesContent(boolean shadeSourcesContent) { this.shadeSourcesContent = shadeSourcesContent; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/Shader.java b/src/main/java/org/apache/maven/plugins/shade/Shader.java index b93a7a5c..35d6fcf6 100644 --- a/src/main/java/org/apache/maven/plugins/shade/Shader.java +++ b/src/main/java/org/apache/maven/plugins/shade/Shader.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade; import java.io.IOException; @@ -26,8 +25,7 @@ /** * Interface that defines the process of shading. */ -public interface Shader -{ +public interface Shader { /** * Perform a shading operation. * @@ -35,6 +33,5 @@ public interface Shader * @throws IOException for IO errors reading the thing * @throws MojoExecutionException for anything else that goes wrong. */ - void shade( ShadeRequest shadeRequest ) - throws IOException, MojoExecutionException; + void shade(ShadeRequest shadeRequest) throws IOException, MojoExecutionException; } diff --git a/src/main/java/org/apache/maven/plugins/shade/ShadingResult.java b/src/main/java/org/apache/maven/plugins/shade/ShadingResult.java index 9278bc30..b5350130 100644 --- a/src/main/java/org/apache/maven/plugins/shade/ShadingResult.java +++ b/src/main/java/org/apache/maven/plugins/shade/ShadingResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade; /** * @author Jason van Zyl */ -public class ShadingResult -{ +public class ShadingResult { // no op // olamy: what this class ?? } diff --git a/src/main/java/org/apache/maven/plugins/shade/filter/Filter.java b/src/main/java/org/apache/maven/plugins/shade/filter/Filter.java index 930d49b9..e1070800 100644 --- a/src/main/java/org/apache/maven/plugins/shade/filter/Filter.java +++ b/src/main/java/org/apache/maven/plugins/shade/filter/Filter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,25 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.filter; import java.io.File; /** * @author David Blevins */ -public interface Filter -{ +public interface Filter { /** * @param jar The jar file. * @return true if we can filter false otherwise. */ - boolean canFilter( File jar ); + boolean canFilter(File jar); /** * @param classFile The classFile. * @return true if the file has been filtered false otherwise. */ - boolean isFiltered( String classFile ); + boolean isFiltered(String classFile); /** * If we are finished. diff --git a/src/main/java/org/apache/maven/plugins/shade/filter/MinijarFilter.java b/src/main/java/org/apache/maven/plugins/shade/filter/MinijarFilter.java index 0ce1c875..8ab1ed3b 100644 --- a/src/main/java/org/apache/maven/plugins/shade/filter/MinijarFilter.java +++ b/src/main/java/org/apache/maven/plugins/shade/filter/MinijarFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,16 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; -import org.vafer.jdependency.Clazz; -import org.vafer.jdependency.Clazzpath; -import org.vafer.jdependency.ClazzpathUnit; - -import static java.nio.charset.StandardCharsets.UTF_8; +package org.apache.maven.plugins.shade.filter; import java.io.BufferedReader; import java.io.File; @@ -44,12 +33,20 @@ import java.util.jar.JarFile; import java.util.zip.ZipException; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.project.MavenProject; +import org.vafer.jdependency.Clazz; +import org.vafer.jdependency.Clazzpath; +import org.vafer.jdependency.ClazzpathUnit; + +import static java.nio.charset.StandardCharsets.UTF_8; + /** * A filter that prevents the inclusion of classes not required in the final jar. */ -public class MinijarFilter - implements Filter -{ +public class MinijarFilter implements Filter { private Log log; @@ -59,11 +56,10 @@ public class MinijarFilter private int classesRemoved; - //[MSHADE-209] This is introduced only for testing purposes which shows + // [MSHADE-209] This is introduced only for testing purposes which shows // there is something wrong with the design of this class. (SoC?) // unfortunately i don't have a better idea at the moment. - MinijarFilter( int classesKept, int classesRemoved, Log log ) - { + MinijarFilter(int classesKept, int classesRemoved, Log log) { this.classesKept = classesKept; this.classesRemoved = classesRemoved; this.log = log; @@ -74,10 +70,8 @@ public class MinijarFilter * @param log {@link Log} * @throws IOException in case of error. */ - public MinijarFilter( MavenProject project, Log log ) - throws IOException - { - this( project, log, Collections.emptyList(), Collections.emptySet() ); + public MinijarFilter(MavenProject project, Log log) throws IOException { + this(project, log, Collections.emptyList(), Collections.emptySet()); } /** @@ -86,10 +80,8 @@ public MinijarFilter( MavenProject project, Log log ) * @param entryPoints * @throws IOException in case of error. */ - public MinijarFilter( MavenProject project, Log log, Set entryPoints ) - throws IOException - { - this( project, log, Collections.emptyList(), entryPoints ); + public MinijarFilter(MavenProject project, Log log, Set entryPoints) throws IOException { + this(project, log, Collections.emptyList(), entryPoints); } /** @@ -100,289 +92,225 @@ public MinijarFilter( MavenProject project, Log log, Set entryPoints ) * @throws IOException in case of errors. * @since 1.6 */ - public MinijarFilter( MavenProject project, Log log, List simpleFilters, Set entryPoints ) - throws IOException - { - this.log = log; + public MinijarFilter(MavenProject project, Log log, List simpleFilters, Set entryPoints) + throws IOException { + this.log = log; - File artifactFile = project.getArtifact().getFile(); + File artifactFile = project.getArtifact().getFile(); - if ( artifactFile != null ) - { - Clazzpath cp = new Clazzpath(); + if (artifactFile != null) { + Clazzpath cp = new Clazzpath(); - ClazzpathUnit artifactUnit = cp.addClazzpathUnit( new FileInputStream( artifactFile ), project.toString() ); + ClazzpathUnit artifactUnit = cp.addClazzpathUnit(new FileInputStream(artifactFile), project.toString()); - for ( Artifact dependency : project.getArtifacts() ) - { - addDependencyToClasspath( cp, dependency ); + for (Artifact dependency : project.getArtifacts()) { + addDependencyToClasspath(cp, dependency); } removable = cp.getClazzes(); - if ( removable.remove( new Clazz( "module-info" ) ) ) - { - log.warn( "Removing module-info from " + artifactFile.getName() ); - } - removePackages( artifactUnit ); - if ( entryPoints.isEmpty() ) - { - removable.removeAll( artifactUnit.getClazzes() ); - removable.removeAll( artifactUnit.getTransitiveDependencies() ); + if (removable.remove(new Clazz("module-info"))) { + log.warn("Removing module-info from " + artifactFile.getName()); } - else - { + removePackages(artifactUnit); + if (entryPoints.isEmpty()) { + removable.removeAll(artifactUnit.getClazzes()); + removable.removeAll(artifactUnit.getTransitiveDependencies()); + } else { Set artifactUnitClazzes = artifactUnit.getClazzes(); Set entryPointsToKeep = new HashSet<>(); - for ( String entryPoint : entryPoints ) - { + for (String entryPoint : entryPoints) { Clazz entryPointFound = null; - for ( Clazz clazz : artifactUnitClazzes ) - { - if ( clazz.getName().equals( entryPoint ) ) - { + for (Clazz clazz : artifactUnitClazzes) { + if (clazz.getName().equals(entryPoint)) { entryPointFound = clazz; break; } } - if ( entryPointFound != null ) - { - entryPointsToKeep.add( entryPointFound ); + if (entryPointFound != null) { + entryPointsToKeep.add(entryPointFound); } } - removable.removeAll( entryPointsToKeep ); - if ( entryPointsToKeep.isEmpty() ) - { - removable.removeAll( artifactUnit.getTransitiveDependencies() ); - } - else - { - for ( Clazz entryPoint : entryPointsToKeep ) - { - removable.removeAll( entryPoint.getTransitiveDependencies() ); + removable.removeAll(entryPointsToKeep); + if (entryPointsToKeep.isEmpty()) { + removable.removeAll(artifactUnit.getTransitiveDependencies()); + } else { + for (Clazz entryPoint : entryPointsToKeep) { + removable.removeAll(entryPoint.getTransitiveDependencies()); } } } - removeSpecificallyIncludedClasses( project, - simpleFilters == null ? Collections.emptyList() : simpleFilters ); - removeServices( project, cp ); + removeSpecificallyIncludedClasses( + project, simpleFilters == null ? Collections.emptyList() : simpleFilters); + removeServices(project, cp); } } - private void removeServices( final MavenProject project, final Clazzpath cp ) - { + private void removeServices(final MavenProject project, final Clazzpath cp) { boolean repeatScan; - do - { + do { repeatScan = false; final Set neededClasses = cp.getClazzes(); - neededClasses.removeAll( removable ); - try - { + neededClasses.removeAll(removable); + try { // getRuntimeClasspathElements returns a list of // - the build output directory // - all the paths to the dependencies' jars // We thereby need to ignore the build directory because we don't want // to remove anything from it, as it's the starting point of the // minification process. - for ( final String fileName : project.getRuntimeClasspathElements() ) - { - if ( new File( fileName ).isDirectory() ) - { - repeatScan |= removeServicesFromDir( cp, neededClasses, fileName ); - } - else - { - repeatScan |= removeServicesFromJar( cp, neededClasses, fileName ); + for (final String fileName : project.getRuntimeClasspathElements()) { + if (new File(fileName).isDirectory()) { + repeatScan |= removeServicesFromDir(cp, neededClasses, fileName); + } else { + repeatScan |= removeServicesFromJar(cp, neededClasses, fileName); } } + } catch (final DependencyResolutionRequiredException e) { + log.warn(e.getMessage()); } - catch ( final DependencyResolutionRequiredException e ) - { - log.warn( e.getMessage() ); - } - } - while ( repeatScan ); + } while (repeatScan); } - private boolean removeServicesFromDir( Clazzpath cp, Set neededClasses, String fileName ) - { - final File servicesDir = new File( fileName, "META-INF/services/" ); - if ( !servicesDir.isDirectory() ) - { + private boolean removeServicesFromDir(Clazzpath cp, Set neededClasses, String fileName) { + final File servicesDir = new File(fileName, "META-INF/services/"); + if (!servicesDir.isDirectory()) { return false; } final File[] serviceProviderConfigFiles = servicesDir.listFiles(); - if ( serviceProviderConfigFiles == null || serviceProviderConfigFiles.length == 0 ) - { + if (serviceProviderConfigFiles == null || serviceProviderConfigFiles.length == 0) { return false; } boolean repeatScan = false; - for ( File serviceProviderConfigFile : serviceProviderConfigFiles ) - { + for (File serviceProviderConfigFile : serviceProviderConfigFiles) { final String serviceClassName = serviceProviderConfigFile.getName(); - final boolean isNeededClass = neededClasses.contains( cp.getClazz( serviceClassName ) ); - if ( !isNeededClass ) - { + final boolean isNeededClass = neededClasses.contains(cp.getClazz(serviceClassName)); + if (!isNeededClass) { continue; } - try ( final BufferedReader configFileReader = new BufferedReader( - new InputStreamReader( new FileInputStream( serviceProviderConfigFile ), UTF_8 ) ) ) - { + try (BufferedReader configFileReader = + new BufferedReader(new InputStreamReader(new FileInputStream(serviceProviderConfigFile), UTF_8))) { // check whether the found classes use services in turn - repeatScan |= scanServiceProviderConfigFile( cp, configFileReader ); - } - catch ( final IOException e ) - { - log.warn( e.getMessage() ); + repeatScan |= scanServiceProviderConfigFile(cp, configFileReader); + } catch (final IOException e) { + log.warn(e.getMessage()); } } return repeatScan; } - private boolean removeServicesFromJar( Clazzpath cp, Set neededClasses, String fileName ) - { + private boolean removeServicesFromJar(Clazzpath cp, Set neededClasses, String fileName) { boolean repeatScan = false; - try ( final JarFile jar = new JarFile( fileName ) ) - { - for ( final Enumeration entries = jar.entries(); entries.hasMoreElements(); ) - { + try (JarFile jar = new JarFile(fileName)) { + for (final Enumeration entries = jar.entries(); entries.hasMoreElements(); ) { final JarEntry jarEntry = entries.nextElement(); - if ( jarEntry.isDirectory() || !jarEntry.getName().startsWith( "META-INF/services/" ) ) - { + if (jarEntry.isDirectory() || !jarEntry.getName().startsWith("META-INF/services/")) { continue; } - final String serviceClassName = jarEntry.getName().substring( "META-INF/services/".length() ); - final boolean isNeededClass = neededClasses.contains( cp.getClazz( serviceClassName ) ); - if ( !isNeededClass ) - { + final String serviceClassName = jarEntry.getName().substring("META-INF/services/".length()); + final boolean isNeededClass = neededClasses.contains(cp.getClazz(serviceClassName)); + if (!isNeededClass) { continue; } - try ( final BufferedReader configFileReader = new BufferedReader( - new InputStreamReader( jar.getInputStream( jarEntry ), UTF_8 ) ) ) - { + try (BufferedReader configFileReader = + new BufferedReader(new InputStreamReader(jar.getInputStream(jarEntry), UTF_8))) { // check whether the found classes use services in turn - repeatScan = scanServiceProviderConfigFile( cp, configFileReader ); - } - catch ( final IOException e ) - { - log.warn( e.getMessage() ); + repeatScan = scanServiceProviderConfigFile(cp, configFileReader); + } catch (final IOException e) { + log.warn(e.getMessage()); } } - } - catch ( final IOException e ) - { - log.warn( "Not a JAR file candidate. Ignoring classpath element '" + fileName + "' (" + e + ")." ); + } catch (final IOException e) { + log.warn("Not a JAR file candidate. Ignoring classpath element '" + fileName + "' (" + e + ")."); } return repeatScan; } - private boolean scanServiceProviderConfigFile( Clazzpath cp, BufferedReader configFileReader ) throws IOException - { + private boolean scanServiceProviderConfigFile(Clazzpath cp, BufferedReader configFileReader) throws IOException { boolean serviceClassFound = false; - for ( String line = configFileReader.readLine(); line != null; line = configFileReader.readLine() ) - { - final String className = line.split( "#", 2 )[0].trim(); - if ( className.isEmpty() ) - { + for (String line = configFileReader.readLine(); line != null; line = configFileReader.readLine()) { + final String className = line.split("#", 2)[0].trim(); + if (className.isEmpty()) { continue; } - final Clazz clazz = cp.getClazz( className ); - if ( clazz == null || !removable.contains( clazz ) ) - { + final Clazz clazz = cp.getClazz(className); + if (clazz == null || !removable.contains(clazz)) { continue; } - log.debug( className + " was not removed because it is a service" ); - removeClass( clazz ); + log.debug(className + " was not removed because it is a service"); + removeClass(clazz); serviceClassFound = true; } return serviceClassFound; } - private void removeClass( final Clazz clazz ) - { - removable.remove( clazz ); - removable.removeAll( clazz.getTransitiveDependencies() ); + private void removeClass(final Clazz clazz) { + removable.remove(clazz); + removable.removeAll(clazz.getTransitiveDependencies()); } - private ClazzpathUnit addDependencyToClasspath( Clazzpath cp, Artifact dependency ) - throws IOException - { + private ClazzpathUnit addDependencyToClasspath(Clazzpath cp, Artifact dependency) throws IOException { ClazzpathUnit clazzpathUnit = null; - try ( InputStream is = new FileInputStream( dependency.getFile() ) ) - { - clazzpathUnit = cp.addClazzpathUnit( is, dependency.toString() ); - } - catch ( ZipException e ) - { - log.warn( dependency.getFile() - + " could not be unpacked/read for minimization; dependency is probably malformed." ); - IOException ioe = new IOException( "Dependency " + dependency.toString() + " in file " - + dependency.getFile() + " could not be unpacked. File is probably corrupt", e ); + try (InputStream is = new FileInputStream(dependency.getFile())) { + clazzpathUnit = cp.addClazzpathUnit(is, dependency.toString()); + } catch (ZipException e) { + log.warn(dependency.getFile() + + " could not be unpacked/read for minimization; dependency is probably malformed."); + IOException ioe = new IOException( + "Dependency " + dependency.toString() + " in file " + dependency.getFile() + + " could not be unpacked. File is probably corrupt", + e); throw ioe; - } - catch ( ArrayIndexOutOfBoundsException | IllegalArgumentException e ) - { + } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) { // trap ArrayIndexOutOfBoundsExceptions caused by malformed dependency classes (MSHADE-107) - log.warn( dependency.toString() - + " could not be analyzed for minimization; dependency is probably malformed." ); + log.warn(dependency.toString() + + " could not be analyzed for minimization; dependency is probably malformed."); } return clazzpathUnit; } - private void removePackages( ClazzpathUnit artifactUnit ) - { + private void removePackages(ClazzpathUnit artifactUnit) { Set packageNames = new HashSet<>(); - removePackages( artifactUnit.getClazzes(), packageNames ); - removePackages( artifactUnit.getTransitiveDependencies(), packageNames ); + removePackages(artifactUnit.getClazzes(), packageNames); + removePackages(artifactUnit.getTransitiveDependencies(), packageNames); } - private void removePackages( Set clazzes, Set packageNames ) - { - for ( Clazz clazz : clazzes ) - { + private void removePackages(Set clazzes, Set packageNames) { + for (Clazz clazz : clazzes) { String name = clazz.getName(); - while ( name.contains( "." ) ) - { - name = name.substring( 0, name.lastIndexOf( '.' ) ); - if ( packageNames.add( name ) ) - { - removable.remove( new Clazz( name + ".package-info" ) ); + while (name.contains(".")) { + name = name.substring(0, name.lastIndexOf('.')); + if (packageNames.add(name)) { + removable.remove(new Clazz(name + ".package-info")); } } } } - private void removeSpecificallyIncludedClasses( MavenProject project, List simpleFilters ) - throws IOException - { + private void removeSpecificallyIncludedClasses(MavenProject project, List simpleFilters) + throws IOException { // remove classes specifically included in filters Clazzpath checkCp = new Clazzpath(); - for ( Artifact dependency : project.getArtifacts() ) - { + for (Artifact dependency : project.getArtifacts()) { File jar = dependency.getFile(); - for ( SimpleFilter simpleFilter : simpleFilters ) - { - if ( simpleFilter.canFilter( jar ) ) - { - ClazzpathUnit depClazzpathUnit = addDependencyToClasspath( checkCp, dependency ); - if ( depClazzpathUnit != null ) - { + for (SimpleFilter simpleFilter : simpleFilters) { + if (simpleFilter.canFilter(jar)) { + ClazzpathUnit depClazzpathUnit = addDependencyToClasspath(checkCp, dependency); + if (depClazzpathUnit != null) { Set clazzes = depClazzpathUnit.getClazzes(); - for ( final Clazz clazz : new HashSet<>( removable ) ) - { - if ( clazzes.contains( clazz ) // - && simpleFilter.isSpecificallyIncluded( clazz.getName().replace( '.', '/' ) ) ) - { - log.debug( clazz.getName() + " not removed because it was specifically included" ); - removeClass( clazz ); + for (final Clazz clazz : new HashSet<>(removable)) { + if (clazzes.contains(clazz) // + && simpleFilter.isSpecificallyIncluded( + clazz.getName().replace('.', '/'))) { + log.debug(clazz.getName() + " not removed because it was specifically included"); + removeClass(clazz); } } } @@ -392,20 +320,17 @@ private void removeSpecificallyIncludedClasses( MavenProject project, List " + classesKept + " (" + 100 * classesKept / classesTotal - + "%)" ); - } - else - { - log.info( "Minimized " + classesTotal + " -> " + classesKept ); + if (classesTotal != 0) { + log.info("Minimized " + classesTotal + " -> " + classesKept + " (" + 100 * classesKept / classesTotal + + "%)"); + } else { + log.info("Minimized " + classesTotal + " -> " + classesKept); } } } diff --git a/src/main/java/org/apache/maven/plugins/shade/filter/SimpleFilter.java b/src/main/java/org/apache/maven/plugins/shade/filter/SimpleFilter.java index 9b767196..d52c1561 100644 --- a/src/main/java/org/apache/maven/plugins/shade/filter/SimpleFilter.java +++ b/src/main/java/org/apache/maven/plugins/shade/filter/SimpleFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,15 @@ * specific language governing permissions and limitations * under the License. */ - -import org.codehaus.plexus.util.SelectorUtils; +package org.apache.maven.plugins.shade.filter; import java.io.File; -import java.util.HashSet; import java.util.Collections; +import java.util.HashSet; import java.util.Set; import org.apache.maven.plugins.shade.mojo.ArchiveFilter; +import org.codehaus.plexus.util.SelectorUtils; /** * @author David Blevins @@ -35,9 +33,7 @@ * @author kama * */ -public class SimpleFilter - implements Filter -{ +public class SimpleFilter implements Filter { private Set jars; @@ -54,18 +50,16 @@ public class SimpleFilter * @param excludes set of excludes. */ @Deprecated - public SimpleFilter( Set jars, Set includes, Set excludes ) - { - this( jars, includes, excludes, true ); + public SimpleFilter(Set jars, Set includes, Set excludes) { + this(jars, includes, excludes, true); } /** * @param jars set of {@link File}s. * @param archiveFilter set of {@link ArchiveFilter}s. */ - public SimpleFilter( final Set jars, final ArchiveFilter archiveFilter ) - { - this( jars, archiveFilter.getIncludes(), archiveFilter.getExcludes(), archiveFilter.getExcludeDefaults() ); + public SimpleFilter(final Set jars, final ArchiveFilter archiveFilter) { + this(jars, archiveFilter.getIncludes(), archiveFilter.getExcludes(), archiveFilter.getExcludeDefaults()); } /** @@ -74,72 +68,63 @@ public SimpleFilter( final Set jars, final ArchiveFilter archiveFilter ) * @param excludes set of excludes. * @param excludeDefaults whether to exclude default includes once includes are provided explicitly. */ - private SimpleFilter( final Set jars, final Set includes, final Set excludes, - final boolean excludeDefaults ) - { - this.jars = ( jars != null ) ? Collections.unmodifiableSet( jars ) : Collections.emptySet(); - this.includes = normalizePatterns( includes ); - this.excludes = normalizePatterns( excludes ); + private SimpleFilter( + final Set jars, + final Set includes, + final Set excludes, + final boolean excludeDefaults) { + this.jars = (jars != null) ? Collections.unmodifiableSet(jars) : Collections.emptySet(); + this.includes = normalizePatterns(includes); + this.excludes = normalizePatterns(excludes); this.excludeDefaults = excludeDefaults; } /** {@inheritDoc} */ - public boolean canFilter( File jar ) - { - return jars.contains( jar ); + public boolean canFilter(File jar) { + return jars.contains(jar); } /** {@inheritDoc} */ - public boolean isFiltered( String classFile ) - { - String path = normalizePath( classFile ); + public boolean isFiltered(String classFile) { + String path = normalizePath(classFile); - return !( ( !excludeDefaults || isIncluded( path ) ) && !isExcluded( path ) ); + return !((!excludeDefaults || isIncluded(path)) && !isExcluded(path)); } /** * @param classFile The class file. * @return true if included false otherwise. */ - public boolean isSpecificallyIncluded( String classFile ) - { - if ( includes == null || includes.isEmpty() ) - { + public boolean isSpecificallyIncluded(String classFile) { + if (includes == null || includes.isEmpty()) { return false; } - String path = normalizePath( classFile ); + String path = normalizePath(classFile); - return isIncluded( path ); + return isIncluded(path); } - private boolean isIncluded( String classFile ) - { - if ( includes == null || includes.isEmpty() ) - { + private boolean isIncluded(String classFile) { + if (includes == null || includes.isEmpty()) { return true; } - return matchPaths( includes, classFile ); + return matchPaths(includes, classFile); } - private boolean isExcluded( String classFile ) - { - if ( excludes == null || excludes.isEmpty() ) - { + private boolean isExcluded(String classFile) { + if (excludes == null || excludes.isEmpty()) { return false; } - return matchPaths( excludes, classFile ); + return matchPaths(excludes, classFile); } - private boolean matchPaths( Set patterns, String classFile ) - { - for ( String pattern : patterns ) - { + private boolean matchPaths(Set patterns, String classFile) { + for (String pattern : patterns) { - if ( SelectorUtils.matchPath( pattern, classFile ) ) - { + if (SelectorUtils.matchPath(pattern, classFile)) { return true; } } @@ -147,27 +132,22 @@ private boolean matchPaths( Set patterns, String classFile ) return false; } - private String normalizePath( String path ) - { - return ( path != null ) ? path.replace( File.separatorChar == '/' ? '\\' : '/', File.separatorChar ) : null; + private String normalizePath(String path) { + return (path != null) ? path.replace(File.separatorChar == '/' ? '\\' : '/', File.separatorChar) : null; } - private Set normalizePatterns( Set patterns ) - { + private Set normalizePatterns(Set patterns) { Set result = new HashSet<>(); - if ( patterns != null ) - { - for ( String pattern : patterns ) - { - pattern = normalizePath( pattern ); + if (patterns != null) { + for (String pattern : patterns) { + pattern = normalizePath(pattern); - if ( pattern.endsWith( File.separator ) ) - { + if (pattern.endsWith(File.separator)) { pattern += "**"; } - result.add( pattern ); + result.add(pattern); } } @@ -175,7 +155,5 @@ private Set normalizePatterns( Set patterns ) } /** {@inheritDoc} */ - public void finished() - { - } + public void finished() {} } diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/ArchiveFilter.java b/src/main/java/org/apache/maven/plugins/shade/mojo/ArchiveFilter.java index 8c8b5d1e..54293452 100644 --- a/src/main/java/org/apache/maven/plugins/shade/mojo/ArchiveFilter.java +++ b/src/main/java/org/apache/maven/plugins/shade/mojo/ArchiveFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; import java.util.Set; /** * @author David Blevins */ -public class ArchiveFilter -{ +public class ArchiveFilter { private String artifact; private Set includes; @@ -34,23 +32,19 @@ public class ArchiveFilter private boolean excludeDefaults = true; - public String getArtifact() - { + public String getArtifact() { return artifact; } - public Set getIncludes() - { + public Set getIncludes() { return includes; } - public Set getExcludes() - { + public Set getExcludes() { return excludes; } - public boolean getExcludeDefaults() - { + public boolean getExcludeDefaults() { return excludeDefaults; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactId.java b/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactId.java index 8351f9f3..3699c5bc 100644 --- a/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactId.java +++ b/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactId.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Dependency; @@ -26,8 +25,7 @@ /** * @author Benjamin Bentmann */ -class ArtifactId -{ +class ArtifactId { private final String groupId; @@ -37,81 +35,65 @@ class ArtifactId private final String classifier; - ArtifactId( Dependency dependency ) - { - this( dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), dependency.getClassifier() ); + ArtifactId(Dependency dependency) { + this(dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), dependency.getClassifier()); } - ArtifactId( Artifact artifact ) - { - this( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(), artifact.getClassifier() ); + ArtifactId(Artifact artifact) { + this(artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(), artifact.getClassifier()); } - ArtifactId( String groupId, String artifactId, String type, String classifier ) - { - this.groupId = ( groupId != null ) ? groupId : ""; - this.artifactId = ( artifactId != null ) ? artifactId : ""; - this.type = ( type != null ) ? type : ""; - this.classifier = ( classifier != null ) ? classifier : ""; + ArtifactId(String groupId, String artifactId, String type, String classifier) { + this.groupId = (groupId != null) ? groupId : ""; + this.artifactId = (artifactId != null) ? artifactId : ""; + this.type = (type != null) ? type : ""; + this.classifier = (classifier != null) ? classifier : ""; } - ArtifactId( String id ) - { + ArtifactId(String id) { String[] tokens = new String[0]; - if ( id != null && id.length() > 0 ) - { - tokens = id.split( ":", -1 ); + if (id != null && id.length() > 0) { + tokens = id.split(":", -1); } - groupId = ( tokens.length > 0 ) ? tokens[0] : ""; - artifactId = ( tokens.length > 1 ) ? tokens[1] : "*"; - type = ( tokens.length > 3 ) ? tokens[2] : "*"; - classifier = ( tokens.length > 3 ) ? tokens[3] : ( ( tokens.length > 2 ) ? tokens[2] : "*" ); + groupId = (tokens.length > 0) ? tokens[0] : ""; + artifactId = (tokens.length > 1) ? tokens[1] : "*"; + type = (tokens.length > 3) ? tokens[2] : "*"; + classifier = (tokens.length > 3) ? tokens[3] : ((tokens.length > 2) ? tokens[2] : "*"); } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getType() - { + public String getType() { return type; } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public boolean matches( ArtifactId pattern ) - { - if ( pattern == null ) - { + public boolean matches(ArtifactId pattern) { + if (pattern == null) { return false; } - if ( !match( getGroupId(), pattern.getGroupId() ) ) - { + if (!match(getGroupId(), pattern.getGroupId())) { return false; } - if ( !match( getArtifactId(), pattern.getArtifactId() ) ) - { + if (!match(getArtifactId(), pattern.getArtifactId())) { return false; } - if ( !match( getType(), pattern.getType() ) ) - { + if (!match(getType(), pattern.getType())) { return false; } - return match( getClassifier(), pattern.getClassifier() ); + return match(getClassifier(), pattern.getClassifier()); } - private boolean match( String str, String pattern ) - { - return SelectorUtils.match( pattern, str ); + private boolean match(String str, String pattern) { + return SelectorUtils.match(pattern, str); } - } diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSelector.java b/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSelector.java index d332091b..502a10c2 100644 --- a/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSelector.java +++ b/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSelector.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,79 +16,68 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; +package org.apache.maven.plugins.shade.mojo; import java.util.Collection; import java.util.HashSet; +import org.apache.maven.artifact.Artifact; + /** * @author Benjamin Bentmann */ -class ArtifactSelector -{ +class ArtifactSelector { private Collection includes; private Collection excludes; - ArtifactSelector( Artifact projectArtifact, ArtifactSet artifactSet, String groupPrefix ) - { - this( ( artifactSet != null ) ? artifactSet.getIncludes() : null, - ( artifactSet != null ) ? artifactSet.getExcludes() : null, groupPrefix ); + ArtifactSelector(Artifact projectArtifact, ArtifactSet artifactSet, String groupPrefix) { + this( + (artifactSet != null) ? artifactSet.getIncludes() : null, + (artifactSet != null) ? artifactSet.getExcludes() : null, + groupPrefix); - if ( projectArtifact != null && !this.includes.isEmpty() ) - { - this.includes.add( new ArtifactId( projectArtifact ) ); + if (projectArtifact != null && !this.includes.isEmpty()) { + this.includes.add(new ArtifactId(projectArtifact)); } } - ArtifactSelector( Collection includes, Collection excludes, String groupPrefix ) - { - this.includes = toIds( includes ); - this.excludes = toIds( excludes ); + ArtifactSelector(Collection includes, Collection excludes, String groupPrefix) { + this.includes = toIds(includes); + this.excludes = toIds(excludes); - if ( groupPrefix != null && groupPrefix.length() > 0 ) - { - this.includes.add( new ArtifactId( groupPrefix + "*", "*", "*", "*" ) ); + if (groupPrefix != null && groupPrefix.length() > 0) { + this.includes.add(new ArtifactId(groupPrefix + "*", "*", "*", "*")); } } - private static Collection toIds( Collection patterns ) - { + private static Collection toIds(Collection patterns) { Collection result = new HashSet<>(); - if ( patterns != null ) - { - for ( String pattern : patterns ) - { - result.add( new ArtifactId( pattern ) ); + if (patterns != null) { + for (String pattern : patterns) { + result.add(new ArtifactId(pattern)); } } return result; } - public boolean isSelected( Artifact artifact ) - { - return artifact != null && isSelected( new ArtifactId( artifact ) ); + public boolean isSelected(Artifact artifact) { + return artifact != null && isSelected(new ArtifactId(artifact)); } - boolean isSelected( ArtifactId id ) - { - return ( includes.isEmpty() || matches( includes, id ) ) && !matches( excludes, id ); + boolean isSelected(ArtifactId id) { + return (includes.isEmpty() || matches(includes, id)) && !matches(excludes, id); } - private boolean matches( Collection patterns, ArtifactId id ) - { - for ( ArtifactId pattern : patterns ) - { - if ( id.matches( pattern ) ) - { + private boolean matches(Collection patterns, ArtifactId id) { + for (ArtifactId pattern : patterns) { + if (id.matches(pattern)) { return true; } } return false; } - } diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSet.java b/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSet.java index 3cac6c6e..c2476e42 100644 --- a/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSet.java +++ b/src/main/java/org/apache/maven/plugins/shade/mojo/ArtifactSet.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,25 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; import java.util.Set; /** * @author Jason van Zyl */ -public class ArtifactSet -{ +public class ArtifactSet { private Set includes; private Set excludes; - public Set getIncludes() - { + public Set getIncludes() { return includes; } - public Set getExcludes() - { + public Set getExcludes() { return excludes; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/PackageRelocation.java b/src/main/java/org/apache/maven/plugins/shade/mojo/PackageRelocation.java index 9ea92a3a..5f3a05b2 100644 --- a/src/main/java/org/apache/maven/plugins/shade/mojo/PackageRelocation.java +++ b/src/main/java/org/apache/maven/plugins/shade/mojo/PackageRelocation.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; import java.util.List; @@ -25,8 +24,7 @@ * @author Jason van Zyl * @author Mauro Talevi */ -public class PackageRelocation -{ +public class PackageRelocation { private String pattern; private String shadedPattern; @@ -37,28 +35,23 @@ public class PackageRelocation private boolean rawString; - public String getPattern() - { + public String getPattern() { return pattern; } - public String getShadedPattern() - { + public String getShadedPattern() { return shadedPattern; } - public List getIncludes() - { + public List getIncludes() { return includes; } - public List getExcludes() - { + public List getExcludes() { return excludes; } - public boolean isRawString() - { + public boolean isRawString() { return rawString; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/RelativizePath.java b/src/main/java/org/apache/maven/plugins/shade/mojo/RelativizePath.java index 56123053..ee3290bf 100644 --- a/src/main/java/org/apache/maven/plugins/shade/mojo/RelativizePath.java +++ b/src/main/java/org/apache/maven/plugins/shade/mojo/RelativizePath.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; import java.io.File; import java.util.ArrayList; @@ -27,83 +26,69 @@ /** * */ -public final class RelativizePath -{ - private RelativizePath() - { +public final class RelativizePath { + private RelativizePath() { // } /** - * relativize a pathname. + * relativize a pathname. * @param thing Absolute File of something. (e.g., a parent pom) * @param relativeTo base to relativize it do. (e.g., a pom into which a relative pathname to the 'thing' is to be * installed). * @return */ - static String convertToRelativePath( File thing, File relativeTo ) - { + static String convertToRelativePath(File thing, File relativeTo) { StringBuilder relativePath; - if ( thing.getParentFile().equals( relativeTo.getParentFile() ) ) - { + if (thing.getParentFile().equals(relativeTo.getParentFile())) { return thing.getName(); // a very simple relative path. } - - List thingDirectories = RelativizePath.parentDirs( thing ); - List relativeToDirectories = RelativizePath.parentDirs( relativeTo ); - - //Get the shortest of the two paths - int length = Math.min( thingDirectories.size(), relativeToDirectories.size() ); - + + List thingDirectories = RelativizePath.parentDirs(thing); + List relativeToDirectories = RelativizePath.parentDirs(relativeTo); + + // Get the shortest of the two paths + int length = Math.min(thingDirectories.size(), relativeToDirectories.size()); + int lastCommonRoot = -1; // index of the lowest directory down from the root that the two have in common. int index; - - //Find common root - for ( index = 0; index < length; index++ ) - { - if ( thingDirectories.get( index ).equals( relativeToDirectories.get( index ) ) ) - { + + // Find common root + for (index = 0; index < length; index++) { + if (thingDirectories.get(index).equals(relativeToDirectories.get(index))) { lastCommonRoot = index; - } - else - { + } else { break; } } - if ( lastCommonRoot != -1 ) - { // possible on Windows or other multi-root cases. + if (lastCommonRoot != -1) { // possible on Windows or other multi-root cases. // Build up the relative path relativePath = new StringBuilder(); // add ..'s to get from the base up to the common point - for ( index = lastCommonRoot + 1; index < relativeToDirectories.size(); index++ ) - { - relativePath.append( "../" ); + for (index = lastCommonRoot + 1; index < relativeToDirectories.size(); index++) { + relativePath.append("../"); } - - // now add down from the common point to the actual 'thing' item. - for ( index = lastCommonRoot + 1; index < thingDirectories.size(); index++ ) - { - relativePath.append( thingDirectories.get( index ) ).append( '/' ); + + // now add down from the common point to the actual 'thing' item. + for (index = lastCommonRoot + 1; index < thingDirectories.size(); index++) { + relativePath.append(thingDirectories.get(index)).append('/'); } - relativePath.append( thing.getName() ); + relativePath.append(thing.getName()); return relativePath.toString(); } return null; } - static List parentDirs( File of ) - { + static List parentDirs(File of) { List results = new ArrayList<>(); - for ( File p = of.getParentFile() ; p != null ; p = p.getParentFile() ) - { - if ( !"".equals( p.getName() ) ) - { - results.add( p.getName() ); + for (File p = of.getParentFile(); p != null; p = p.getParentFile()) { + if (!"".equals(p.getName())) { + results.add(p.getName()); } } - - Collections.reverse( results ); + + Collections.reverse(results); return results; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java b/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java index c83d27cb..5563df79 100644 --- a/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java +++ b/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; + +import javax.inject.Inject; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Writer; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; @@ -59,23 +76,6 @@ import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; import static org.apache.maven.plugins.shade.resource.UseDependencyReducedPom.createPomReplaceTransformers; /** @@ -87,21 +87,23 @@ * @author Hiram Chirino */ // CHECKSTYLE_OFF: LineLength -@Mojo( name = "shade", defaultPhase = LifecyclePhase.PACKAGE, threadSafe = true, requiresDependencyResolution = ResolutionScope.RUNTIME ) +@Mojo( + name = "shade", + defaultPhase = LifecyclePhase.PACKAGE, + threadSafe = true, + requiresDependencyResolution = ResolutionScope.RUNTIME) // CHECKSTYLE_ON: LineLength -public class ShadeMojo - extends AbstractMojo -{ +public class ShadeMojo extends AbstractMojo { /** * The current Maven session. */ - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; /** * The current Maven project. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** @@ -146,7 +148,7 @@ public class ShadeMojo * * Note: Support for includes exists only since version 1.4. */ - @SuppressWarnings( "MismatchedReadAndWriteOfArray" ) + @SuppressWarnings("MismatchedReadAndWriteOfArray") @Parameter private PackageRelocation[] relocations; @@ -179,14 +181,14 @@ public class ShadeMojo * </filters> * */ - @SuppressWarnings( "MismatchedReadAndWriteOfArray" ) + @SuppressWarnings("MismatchedReadAndWriteOfArray") @Parameter private ArchiveFilter[] filters; /** * The destination directory for the shaded artifact. */ - @Parameter( defaultValue = "${project.build.directory}" ) + @Parameter(defaultValue = "${project.build.directory}") private File outputDirectory; /** @@ -204,7 +206,7 @@ public class ShadeMojo * If the original artifactId was "foo" then the final artifact would be something like foo-1.0.jar. So if you * change the artifactId you might have something like foo-special-1.0.jar. */ - @Parameter( defaultValue = "${project.artifactId}" ) + @Parameter(defaultValue = "${project.artifactId}") private String shadedArtifactId; /** @@ -227,7 +229,7 @@ public class ShadeMojo * directory as the shaded artifact. Unless you also specify dependencyReducedPomLocation, the plugin will create a * temporary file named dependency-reduced-pom.xml in the project basedir. */ - @Parameter( defaultValue = "true" ) + @Parameter(defaultValue = "true") private boolean createDependencyReducedPom; /** @@ -237,7 +239,7 @@ public class ShadeMojo * * @since 1.7 */ - @Parameter( defaultValue = "${basedir}/dependency-reduced-pom.xml" ) + @Parameter(defaultValue = "${basedir}/dependency-reduced-pom.xml") private File dependencyReducedPomLocation; /** @@ -247,7 +249,7 @@ public class ShadeMojo * * @since 1.7.2 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean generateUniqueDependencyReducedPom; /** @@ -256,7 +258,7 @@ public class ShadeMojo * * @since 3.3.0 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean useDependencyReducedPomInJar; /** @@ -275,7 +277,7 @@ public class ShadeMojo /** * The name of the classifier used in case the shaded artifact is attached. */ - @Parameter( defaultValue = "shaded" ) + @Parameter(defaultValue = "shaded") private String shadedClassifierName; /** @@ -305,7 +307,7 @@ public class ShadeMojo * tool creating reasonably plausible source code when navigating to a relocated library class from an IDE, * hopefully displaying source code which makes 95% sense - no more, no less. */ - @Parameter( property = "shadeSourcesContent", defaultValue = "false" ) + @Parameter(property = "shadeSourcesContent", defaultValue = "false") private boolean shadeSourcesContent; /** @@ -372,20 +374,20 @@ public class ShadeMojo * * @since 3.0 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean useBaseVersion; /** * When true, creates a shaded test-jar artifact as well. */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean shadeTestJar; /** * When true, skips the execution of this MOJO. * @since 3.3.0 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean skip; @Inject @@ -419,12 +421,9 @@ public class ShadeMojo * @throws MojoExecutionException in case of an error. */ @Override - public void execute() - throws MojoExecutionException - { - if ( skip ) - { - getLog().info( "Shading has been skipped." ); + public void execute() throws MojoExecutionException { + if (skip) { + getLog().info("Shading has been skipped."); return; } @@ -436,280 +435,255 @@ public void execute() Set testArtifacts = new LinkedHashSet<>(); Set testSourceArtifacts = new LinkedHashSet<>(); - ArtifactSelector artifactSelector = - new ArtifactSelector( project.getArtifact(), artifactSet, shadedGroupFilter ); + ArtifactSelector artifactSelector = new ArtifactSelector(project.getArtifact(), artifactSet, shadedGroupFilter); - if ( artifactSelector.isSelected( project.getArtifact() ) && !"pom".equals( project.getArtifact().getType() ) ) - { - if ( invalidMainArtifact() ) - { + if (artifactSelector.isSelected(project.getArtifact()) + && !"pom".equals(project.getArtifact().getType())) { + if (invalidMainArtifact()) { createErrorOutput(); - throw new MojoExecutionException( "Failed to create shaded artifact, " - + "project main artifact does not exist." ); + throw new MojoExecutionException( + "Failed to create shaded artifact, " + "project main artifact does not exist."); } - artifacts.add( project.getArtifact().getFile() ); + artifacts.add(project.getArtifact().getFile()); - if ( createSourcesJar ) - { + if (createSourcesJar) { File file = shadedSourcesArtifactFile(); - if ( file.isFile() ) - { - sourceArtifacts.add( file ); + if (file.isFile()) { + sourceArtifacts.add(file); } } - if ( shadeTestJar ) - { + if (shadeTestJar) { File file = shadedTestArtifactFile(); - if ( file.isFile() ) - { - testArtifacts.add( file ); + if (file.isFile()) { + testArtifacts.add(file); } } - if ( createTestSourcesJar ) - { + if (createTestSourcesJar) { File file = shadedTestSourcesArtifactFile(); - if ( file.isFile() ) - { - testSourceArtifacts.add( file ); + if (file.isFile()) { + testSourceArtifacts.add(file); } } } - processArtifactSelectors( artifacts, artifactIds, sourceArtifacts, testArtifacts, testSourceArtifacts, - artifactSelector ); + processArtifactSelectors( + artifacts, artifactIds, sourceArtifacts, testArtifacts, testSourceArtifacts, artifactSelector); - File outputJar = ( outputFile != null ) ? outputFile : shadedArtifactFileWithClassifier(); + File outputJar = (outputFile != null) ? outputFile : shadedArtifactFileWithClassifier(); File sourcesJar = shadedSourceArtifactFileWithClassifier(); File testJar = shadedTestArtifactFileWithClassifier(); File testSourcesJar = shadedTestSourceArtifactFileWithClassifier(); // Now add our extra resources - try - { + try { List filters = getFilters(); List relocators = getRelocators(); List resourceTransformers = getResourceTransformers(); - if ( createDependencyReducedPom ) - { - createDependencyReducedPom( artifactIds ); + if (createDependencyReducedPom) { + createDependencyReducedPom(artifactIds); - if ( useDependencyReducedPomInJar ) - { + if (useDependencyReducedPomInJar) { // In some cases the used implementation of the resourceTransformers is immutable. - resourceTransformers = new ArrayList<>( resourceTransformers ); - resourceTransformers.addAll( - createPomReplaceTransformers( project, dependencyReducedPomLocation ) ); + resourceTransformers = new ArrayList<>(resourceTransformers); + resourceTransformers.addAll(createPomReplaceTransformers(project, dependencyReducedPomLocation)); } } - ShadeRequest shadeRequest = shadeRequest( "jar", artifacts, outputJar, filters, relocators, - resourceTransformers ); + ShadeRequest shadeRequest = + shadeRequest("jar", artifacts, outputJar, filters, relocators, resourceTransformers); - shader.shade( shadeRequest ); + shader.shade(shadeRequest); - if ( createSourcesJar ) - { - ShadeRequest shadeSourcesRequest = - createShadeSourcesRequest( "sources-jar", sourceArtifacts, sourcesJar, filters, relocators, - resourceTransformers ); + if (createSourcesJar) { + ShadeRequest shadeSourcesRequest = createShadeSourcesRequest( + "sources-jar", sourceArtifacts, sourcesJar, filters, relocators, resourceTransformers); - shader.shade( shadeSourcesRequest ); + shader.shade(shadeSourcesRequest); } - if ( shadeTestJar ) - { + if (shadeTestJar) { ShadeRequest shadeTestRequest = - shadeRequest( "test-jar", testArtifacts, testJar, filters, relocators, resourceTransformers ); + shadeRequest("test-jar", testArtifacts, testJar, filters, relocators, resourceTransformers); - shader.shade( shadeTestRequest ); + shader.shade(shadeTestRequest); } - if ( createTestSourcesJar ) - { - ShadeRequest shadeTestSourcesRequest = - createShadeSourcesRequest( "test-sources-jar", testSourceArtifacts, testSourcesJar, filters, - relocators, resourceTransformers ); + if (createTestSourcesJar) { + ShadeRequest shadeTestSourcesRequest = createShadeSourcesRequest( + "test-sources-jar", + testSourceArtifacts, + testSourcesJar, + filters, + relocators, + resourceTransformers); - shader.shade( shadeTestSourcesRequest ); + shader.shade(shadeTestSourcesRequest); } - if ( outputFile == null ) - { + if (outputFile == null) { boolean renamed = false; // rename the output file if a specific finalName is set // but don't rename if the finalName is the // because this will be handled implicitly later - if ( finalName != null && finalName.length() > 0 // - && !finalName.equals( project.getBuild().getFinalName() ) ) - { - String finalFileName = finalName + "." + project.getArtifact().getArtifactHandler().getExtension(); - File finalFile = new File( outputDirectory, finalFileName ); - replaceFile( finalFile, outputJar ); + if (finalName != null + && finalName.length() > 0 // + && !finalName.equals(project.getBuild().getFinalName())) { + String finalFileName = finalName + "." + + project.getArtifact().getArtifactHandler().getExtension(); + File finalFile = new File(outputDirectory, finalFileName); + replaceFile(finalFile, outputJar); outputJar = finalFile; // Also support the sources JAR - if ( createSourcesJar ) - { + if (createSourcesJar) { finalFileName = finalName + "-sources.jar"; - finalFile = new File( outputDirectory, finalFileName ); - replaceFile( finalFile, sourcesJar ); + finalFile = new File(outputDirectory, finalFileName); + replaceFile(finalFile, sourcesJar); sourcesJar = finalFile; } // Also support the test JAR - if ( shadeTestJar ) - { + if (shadeTestJar) { finalFileName = finalName + "-tests.jar"; - finalFile = new File( outputDirectory, finalFileName ); - replaceFile( finalFile, testJar ); + finalFile = new File(outputDirectory, finalFileName); + replaceFile(finalFile, testJar); testJar = finalFile; } - if ( createTestSourcesJar ) - { + if (createTestSourcesJar) { finalFileName = finalName + "-test-sources.jar"; - finalFile = new File( outputDirectory, finalFileName ); - replaceFile( finalFile, testSourcesJar ); + finalFile = new File(outputDirectory, finalFileName); + replaceFile(finalFile, testSourcesJar); testSourcesJar = finalFile; } renamed = true; } - if ( shadedArtifactAttached ) - { - getLog().info( "Attaching shaded artifact." ); - projectHelper.attachArtifact( project, project.getArtifact().getType(), shadedClassifierName, - outputJar ); - if ( createSourcesJar ) - { - projectHelper.attachArtifact( project, "java-source", shadedClassifierName + "-sources", - sourcesJar ); + if (shadedArtifactAttached) { + getLog().info("Attaching shaded artifact."); + projectHelper.attachArtifact( + project, project.getArtifact().getType(), shadedClassifierName, outputJar); + if (createSourcesJar) { + projectHelper.attachArtifact( + project, "java-source", shadedClassifierName + "-sources", sourcesJar); } - if ( shadeTestJar ) - { - projectHelper.attachArtifact( project, "test-jar", shadedClassifierName + "-tests", - testJar ); + if (shadeTestJar) { + projectHelper.attachArtifact(project, "test-jar", shadedClassifierName + "-tests", testJar); } - if ( createTestSourcesJar ) - { - projectHelper.attachArtifact( project, "java-source", - shadedClassifierName + "-test-sources", testSourcesJar ); + if (createTestSourcesJar) { + projectHelper.attachArtifact( + project, "java-source", shadedClassifierName + "-test-sources", testSourcesJar); } - } - else if ( !renamed ) - { - getLog().info( "Replacing original artifact with shaded artifact." ); + } else if (!renamed) { + getLog().info("Replacing original artifact with shaded artifact."); File originalArtifact = project.getArtifact().getFile(); - if ( originalArtifact != null ) - { - replaceFile( originalArtifact, outputJar ); + if (originalArtifact != null) { + replaceFile(originalArtifact, outputJar); - if ( createSourcesJar ) - { - getLog().info( "Replacing original source artifact with shaded source artifact." ); + if (createSourcesJar) { + getLog().info("Replacing original source artifact with shaded source artifact."); File shadedSources = shadedSourcesArtifactFile(); - replaceFile( shadedSources, sourcesJar ); + replaceFile(shadedSources, sourcesJar); - projectHelper.attachArtifact( project, "java-source", "sources", shadedSources ); + projectHelper.attachArtifact(project, "java-source", "sources", shadedSources); } - if ( shadeTestJar ) - { - getLog().info( "Replacing original test artifact with shaded test artifact." ); + if (shadeTestJar) { + getLog().info("Replacing original test artifact with shaded test artifact."); File shadedTests = shadedTestArtifactFile(); - replaceFile( shadedTests, testJar ); + replaceFile(shadedTests, testJar); - projectHelper.attachArtifact( project, "test-jar", shadedTests ); + projectHelper.attachArtifact(project, "test-jar", shadedTests); } - if ( createTestSourcesJar ) - { - getLog().info( "Replacing original test source artifact " - + "with shaded test source artifact." ); + if (createTestSourcesJar) { + getLog().info("Replacing original test source artifact " + + "with shaded test source artifact."); File shadedTestSources = shadedTestSourcesArtifactFile(); - replaceFile( shadedTestSources, testSourcesJar ); + replaceFile(shadedTestSources, testSourcesJar); - projectHelper.attachArtifact( project, "java-source", "test-sources", - shadedTestSources ); + projectHelper.attachArtifact(project, "java-source", "test-sources", shadedTestSources); } } } } - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Error creating shaded jar: " + e.getMessage(), e ); + } catch (Exception e) { + throw new MojoExecutionException("Error creating shaded jar: " + e.getMessage(), e); } } - private void createErrorOutput() - { - getLog().error( "The project main artifact does not exist. This could have the following" ); - getLog().error( "reasons:" ); - getLog().error( "- You have invoked the goal directly from the command line. This is not" ); - getLog().error( " supported. Please add the goal to the default lifecycle via an" ); - getLog().error( " element in your POM and use \"mvn package\" to have it run." ); - getLog().error( "- You have bound the goal to a lifecycle phase before \"package\". Please" ); - getLog().error( " remove this binding from your POM such that the goal will be run in" ); - getLog().error( " the proper phase." ); - getLog().error( "- You removed the configuration of the maven-jar-plugin that produces the main artifact." ); + private void createErrorOutput() { + getLog().error("The project main artifact does not exist. This could have the following"); + getLog().error("reasons:"); + getLog().error("- You have invoked the goal directly from the command line. This is not"); + getLog().error(" supported. Please add the goal to the default lifecycle via an"); + getLog().error(" element in your POM and use \"mvn package\" to have it run."); + getLog().error("- You have bound the goal to a lifecycle phase before \"package\". Please"); + getLog().error(" remove this binding from your POM such that the goal will be run in"); + getLog().error(" the proper phase."); + getLog().error("- You removed the configuration of the maven-jar-plugin that produces the main artifact."); } - private ShadeRequest shadeRequest( String shade, Set artifacts, File outputJar, List filters, - List relocators, List resourceTransformers ) - { + private ShadeRequest shadeRequest( + String shade, + Set artifacts, + File outputJar, + List filters, + List relocators, + List resourceTransformers) { ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( artifacts ); - shadeRequest.setUberJar( outputJar ); - shadeRequest.setFilters( filters ); - shadeRequest.setRelocators( relocators ); - shadeRequest.setResourceTransformers( toResourceTransformers( shade, resourceTransformers ) ); + shadeRequest.setJars(artifacts); + shadeRequest.setUberJar(outputJar); + shadeRequest.setFilters(filters); + shadeRequest.setRelocators(relocators); + shadeRequest.setResourceTransformers(toResourceTransformers(shade, resourceTransformers)); return shadeRequest; } - private ShadeRequest createShadeSourcesRequest( String shade, Set testArtifacts, File testJar, - List filters, List relocators, - List resourceTransformers ) - { + private ShadeRequest createShadeSourcesRequest( + String shade, + Set testArtifacts, + File testJar, + List filters, + List relocators, + List resourceTransformers) { ShadeRequest shadeSourcesRequest = - shadeRequest( shade, testArtifacts, testJar, filters, relocators, resourceTransformers ); - shadeSourcesRequest.setShadeSourcesContent( shadeSourcesContent ); + shadeRequest(shade, testArtifacts, testJar, filters, relocators, resourceTransformers); + shadeSourcesRequest.setShadeSourcesContent(shadeSourcesContent); return shadeSourcesRequest; } - private void setupHintedShader() - throws MojoExecutionException - { - if ( shaderHint != null ) - { - shader = shaders.get( shaderHint ); + private void setupHintedShader() throws MojoExecutionException { + if (shaderHint != null) { + shader = shaders.get(shaderHint); - if ( shader == null ) - { + if (shader == null) { throw new MojoExecutionException( - "unable to lookup own Shader implementation with hint: '" + shaderHint + "'" - ); + "unable to lookup own Shader implementation with hint: '" + shaderHint + "'"); } } } - private void processArtifactSelectors( Set artifacts, Set artifactIds, Set sourceArtifacts, - Set testArtifacts, Set testSourceArtifacts, - ArtifactSelector artifactSelector ) - { + private void processArtifactSelectors( + Set artifacts, + Set artifactIds, + Set sourceArtifacts, + Set testArtifacts, + Set testSourceArtifacts, + ArtifactSelector artifactSelector) { List excludedArtifacts = new ArrayList<>(); List pomArtifacts = new ArrayList<>(); @@ -717,389 +691,313 @@ private void processArtifactSelectors( Set artifacts, Set artifact List emptyTestArtifacts = new ArrayList<>(); List emptyTestSourceArtifacts = new ArrayList<>(); - for ( Artifact artifact : project.getArtifacts() ) - { - if ( !artifactSelector.isSelected( artifact ) ) - { - excludedArtifacts.add( artifact.getId() ); + for (Artifact artifact : project.getArtifacts()) { + if (!artifactSelector.isSelected(artifact)) { + excludedArtifacts.add(artifact.getId()); continue; } - if ( "pom".equals( artifact.getType() ) ) - { - pomArtifacts.add( artifact.getId() ); + if ("pom".equals(artifact.getType())) { + pomArtifacts.add(artifact.getId()); continue; } - getLog().info( "Including " + artifact.getId() + " in the shaded jar." ); + getLog().info("Including " + artifact.getId() + " in the shaded jar."); - artifacts.add( artifact.getFile() ); - artifactIds.add( getId( artifact ) ); + artifacts.add(artifact.getFile()); + artifactIds.add(getId(artifact)); - if ( createSourcesJar ) - { - File file = resolveArtifactForClassifier( artifact, "sources" ); - if ( file != null ) - { - if ( file.length() > 0 ) - { - sourceArtifacts.add( file ); - } - else - { - emptySourceArtifacts.add( artifact.getArtifactId() ); + if (createSourcesJar) { + File file = resolveArtifactForClassifier(artifact, "sources"); + if (file != null) { + if (file.length() > 0) { + sourceArtifacts.add(file); + } else { + emptySourceArtifacts.add(artifact.getArtifactId()); } } } - if ( shadeTestJar ) - { - File file = resolveArtifactForClassifier( artifact, "tests" ); - if ( file != null ) - { - if ( file.length() > 0 ) - { - testArtifacts.add( file ); - } - else - { - emptyTestArtifacts.add( artifact.getId() ); + if (shadeTestJar) { + File file = resolveArtifactForClassifier(artifact, "tests"); + if (file != null) { + if (file.length() > 0) { + testArtifacts.add(file); + } else { + emptyTestArtifacts.add(artifact.getId()); } } } - if ( createTestSourcesJar ) - { - File file = resolveArtifactForClassifier( artifact, "test-sources" ); - if ( file != null ) - { - testSourceArtifacts.add( file ); - } - else - { - emptyTestSourceArtifacts.add( artifact.getId() ); + if (createTestSourcesJar) { + File file = resolveArtifactForClassifier(artifact, "test-sources"); + if (file != null) { + testSourceArtifacts.add(file); + } else { + emptyTestSourceArtifacts.add(artifact.getId()); } } } - for ( String artifactId : excludedArtifacts ) - { - getLog().info( "Excluding " + artifactId + " from the shaded jar." ); + for (String artifactId : excludedArtifacts) { + getLog().info("Excluding " + artifactId + " from the shaded jar."); } - for ( String artifactId : pomArtifacts ) - { - getLog().info( "Skipping pom dependency " + artifactId + " in the shaded jar." ); + for (String artifactId : pomArtifacts) { + getLog().info("Skipping pom dependency " + artifactId + " in the shaded jar."); } - for ( String artifactId : emptySourceArtifacts ) - { - getLog().warn( "Skipping empty source jar " + artifactId + "." ); + for (String artifactId : emptySourceArtifacts) { + getLog().warn("Skipping empty source jar " + artifactId + "."); } - for ( String artifactId : emptyTestArtifacts ) - { - getLog().warn( "Skipping empty test jar " + artifactId + "." ); + for (String artifactId : emptyTestArtifacts) { + getLog().warn("Skipping empty test jar " + artifactId + "."); } - for ( String artifactId : emptyTestSourceArtifacts ) - { - getLog().warn( "Skipping empty test source jar " + artifactId + "." ); + for (String artifactId : emptyTestSourceArtifacts) { + getLog().warn("Skipping empty test source jar " + artifactId + "."); } } - private boolean invalidMainArtifact() - { - return project.getArtifact().getFile() == null || !project.getArtifact().getFile().isFile(); + private boolean invalidMainArtifact() { + return project.getArtifact().getFile() == null + || !project.getArtifact().getFile().isFile(); } - private void replaceFile( File oldFile, File newFile ) - throws MojoExecutionException - { - getLog().info( "Replacing " + oldFile + " with " + newFile ); + private void replaceFile(File oldFile, File newFile) throws MojoExecutionException { + getLog().info("Replacing " + oldFile + " with " + newFile); - File origFile = new File( outputDirectory, "original-" + oldFile.getName() ); - if ( oldFile.exists() && !oldFile.renameTo( origFile ) ) - { + File origFile = new File(outputDirectory, "original-" + oldFile.getName()); + if (oldFile.exists() && !oldFile.renameTo(origFile)) { // try a gc to see if an unclosed stream needs garbage collecting System.gc(); System.gc(); - if ( !oldFile.renameTo( origFile ) ) - { + if (!oldFile.renameTo(origFile)) { // Still didn't work. We'll do a copy - try - { - copyFiles( oldFile, origFile ); - } - catch ( IOException ex ) - { + try { + copyFiles(oldFile, origFile); + } catch (IOException ex) { // kind of ignorable here. We're just trying to save the original - getLog().warn( ex ); + getLog().warn(ex); } } } - if ( !newFile.renameTo( oldFile ) ) - { + if (!newFile.renameTo(oldFile)) { // try a gc to see if an unclosed stream needs garbage collecting System.gc(); System.gc(); - if ( !newFile.renameTo( oldFile ) ) - { + if (!newFile.renameTo(oldFile)) { // Still didn't work. We'll do a copy - try - { - copyFiles( newFile, oldFile ); - } - catch ( IOException ex ) - { - throw new MojoExecutionException( "Could not replace original artifact with shaded artifact!", ex ); + try { + copyFiles(newFile, oldFile); + } catch (IOException ex) { + throw new MojoExecutionException("Could not replace original artifact with shaded artifact!", ex); } } } } - private void copyFiles( File source, File target ) - throws IOException - { - try ( InputStream in = Files.newInputStream( source.toPath() ); - OutputStream out = Files.newOutputStream( target.toPath() ) ) - { - IOUtil.copy( in, out ); + private void copyFiles(File source, File target) throws IOException { + try (InputStream in = Files.newInputStream(source.toPath()); + OutputStream out = Files.newOutputStream(target.toPath())) { + IOUtil.copy(in, out); } } - private File resolveArtifactForClassifier( Artifact artifact, String classifier ) - { - org.eclipse.aether.artifact.Artifact coordinate = RepositoryUtils.toArtifact( - new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersionRange(), - artifact.getScope(), artifact.getType(), classifier, artifact.getArtifactHandler(), - artifact.isOptional() - ) - ); + private File resolveArtifactForClassifier(Artifact artifact, String classifier) { + org.eclipse.aether.artifact.Artifact coordinate = RepositoryUtils.toArtifact(new DefaultArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersionRange(), + artifact.getScope(), + artifact.getType(), + classifier, + artifact.getArtifactHandler(), + artifact.isOptional())); - ArtifactRequest request = new ArtifactRequest( coordinate, - RepositoryUtils.toRepos( project.getRemoteArtifactRepositories() ), "shade" ); + ArtifactRequest request = new ArtifactRequest( + coordinate, RepositoryUtils.toRepos(project.getRemoteArtifactRepositories()), "shade"); Artifact resolvedArtifact; - try - { - ArtifactResult result = repositorySystem.resolveArtifact( session.getRepositorySession(), request ); - resolvedArtifact = RepositoryUtils.toArtifact( result.getArtifact() ); - } - catch ( ArtifactResolutionException e ) - { - getLog().warn( "Could not get " + classifier + " for " + artifact ); + try { + ArtifactResult result = repositorySystem.resolveArtifact(session.getRepositorySession(), request); + resolvedArtifact = RepositoryUtils.toArtifact(result.getArtifact()); + } catch (ArtifactResolutionException e) { + getLog().warn("Could not get " + classifier + " for " + artifact); return null; } - if ( resolvedArtifact.isResolved() ) - { + if (resolvedArtifact.isResolved()) { return resolvedArtifact.getFile(); } return null; } - private List getRelocators() - { + private List getRelocators() { List relocators = new ArrayList<>(); - if ( relocations == null ) - { + if (relocations == null) { return relocators; } - for ( PackageRelocation r : relocations ) - { - relocators.add( new SimpleRelocator( r.getPattern(), r.getShadedPattern(), r.getIncludes(), r.getExcludes(), - r.isRawString() ) ); + for (PackageRelocation r : relocations) { + relocators.add(new SimpleRelocator( + r.getPattern(), r.getShadedPattern(), r.getIncludes(), r.getExcludes(), r.isRawString())); } return relocators; } - private List getResourceTransformers() - { - if ( transformers == null ) - { + private List getResourceTransformers() { + if (transformers == null) { return Collections.emptyList(); } - return Arrays.asList( transformers ); + return Arrays.asList(transformers); } - private List getFilters() - throws MojoExecutionException - { + private List getFilters() throws MojoExecutionException { List filters = new ArrayList<>(); List simpleFilters = new ArrayList<>(); - if ( this.filters != null && this.filters.length > 0 ) - { + if (this.filters != null && this.filters.length > 0) { Map artifacts = new HashMap<>(); - artifacts.put( project.getArtifact(), new ArtifactId( project.getArtifact() ) ); + artifacts.put(project.getArtifact(), new ArtifactId(project.getArtifact())); - for ( Artifact artifact : project.getArtifacts() ) - { - artifacts.put( artifact, new ArtifactId( artifact ) ); + for (Artifact artifact : project.getArtifacts()) { + artifacts.put(artifact, new ArtifactId(artifact)); } - for ( ArchiveFilter filter : this.filters ) - { - ArtifactId pattern = new ArtifactId( filter.getArtifact() ); + for (ArchiveFilter filter : this.filters) { + ArtifactId pattern = new ArtifactId(filter.getArtifact()); Set jars = new HashSet<>(); - for ( Map.Entry entry : artifacts.entrySet() ) - { - if ( entry.getValue().matches( pattern ) ) - { + for (Map.Entry entry : artifacts.entrySet()) { + if (entry.getValue().matches(pattern)) { Artifact artifact = entry.getKey(); - jars.add( artifact.getFile() ); + jars.add(artifact.getFile()); - if ( createSourcesJar ) - { - File file = resolveArtifactForClassifier( artifact, "sources" ); - if ( file != null ) - { - jars.add( file ); + if (createSourcesJar) { + File file = resolveArtifactForClassifier(artifact, "sources"); + if (file != null) { + jars.add(file); } } - if ( shadeTestJar ) - { - File file = resolveArtifactForClassifier( artifact, "tests" ); - if ( file != null ) - { - jars.add( file ); + if (shadeTestJar) { + File file = resolveArtifactForClassifier(artifact, "tests"); + if (file != null) { + jars.add(file); } } } } - if ( jars.isEmpty() ) - { - getLog().info( "No artifact matching filter " + filter.getArtifact() ); + if (jars.isEmpty()) { + getLog().info("No artifact matching filter " + filter.getArtifact()); continue; } - simpleFilters.add( new SimpleFilter( jars, filter ) ); + simpleFilters.add(new SimpleFilter(jars, filter)); } } - filters.addAll( simpleFilters ); + filters.addAll(simpleFilters); - if ( minimizeJar ) - { - if ( entryPoints == null ) - { + if (minimizeJar) { + if (entryPoints == null) { entryPoints = new HashSet<>(); } - getLog().info( "Minimizing jar " + project.getArtifact() - + ( entryPoints.isEmpty() ? "" : " with entry points" ) ); + getLog().info("Minimizing jar " + project.getArtifact() + + (entryPoints.isEmpty() ? "" : " with entry points")); - try - { - filters.add( new MinijarFilter( project, getLog(), simpleFilters, entryPoints ) ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Failed to analyze class dependencies", e ); + try { + filters.add(new MinijarFilter(project, getLog(), simpleFilters, entryPoints)); + } catch (IOException e) { + throw new MojoExecutionException("Failed to analyze class dependencies", e); } } return filters; } - private File shadedArtifactFileWithClassifier() - { + private File shadedArtifactFileWithClassifier() { Artifact artifact = project.getArtifact(); final String shadedName = shadedArtifactId + "-" + artifact.getVersion() + "-" + shadedClassifierName + "." - + artifact.getArtifactHandler().getExtension(); - return new File( outputDirectory, shadedName ); + + artifact.getArtifactHandler().getExtension(); + return new File(outputDirectory, shadedName); } - private File shadedSourceArtifactFileWithClassifier() - { - return shadedArtifactFileWithClassifier( "sources" ); + private File shadedSourceArtifactFileWithClassifier() { + return shadedArtifactFileWithClassifier("sources"); } - private File shadedTestSourceArtifactFileWithClassifier() - { - return shadedArtifactFileWithClassifier( "test-sources" ); + private File shadedTestSourceArtifactFileWithClassifier() { + return shadedArtifactFileWithClassifier("test-sources"); } - private File shadedArtifactFileWithClassifier( String classifier ) - { + private File shadedArtifactFileWithClassifier(String classifier) { Artifact artifact = project.getArtifact(); - final String shadedName = shadedArtifactId + "-" + artifact.getVersion() + "-" + shadedClassifierName - + "-" + classifier + "." + artifact.getArtifactHandler().getExtension(); - return new File( outputDirectory, shadedName ); + final String shadedName = shadedArtifactId + "-" + artifact.getVersion() + "-" + shadedClassifierName + "-" + + classifier + "." + artifact.getArtifactHandler().getExtension(); + return new File(outputDirectory, shadedName); } - private File shadedTestArtifactFileWithClassifier() - { - return shadedArtifactFileWithClassifier( "tests" ); + private File shadedTestArtifactFileWithClassifier() { + return shadedArtifactFileWithClassifier("tests"); } - private File shadedSourcesArtifactFile() - { - return shadedArtifactFile( "sources" ); + private File shadedSourcesArtifactFile() { + return shadedArtifactFile("sources"); } - private File shadedTestSourcesArtifactFile() - { - return shadedArtifactFile( "test-sources" ); + private File shadedTestSourcesArtifactFile() { + return shadedArtifactFile("test-sources"); } - private File shadedArtifactFile( String classifier ) - { + private File shadedArtifactFile(String classifier) { Artifact artifact = project.getArtifact(); String shadedName; - if ( project.getBuild().getFinalName() != null ) - { + if (project.getBuild().getFinalName() != null) { shadedName = project.getBuild().getFinalName() + "-" + classifier + "." - + artifact.getArtifactHandler().getExtension(); - } - else - { + + artifact.getArtifactHandler().getExtension(); + } else { shadedName = shadedArtifactId + "-" + artifact.getVersion() + "-" + classifier + "." - + artifact.getArtifactHandler().getExtension(); + + artifact.getArtifactHandler().getExtension(); } - return new File( outputDirectory, shadedName ); + return new File(outputDirectory, shadedName); } - private File shadedTestArtifactFile() - { - return shadedArtifactFile( "tests" ); + private File shadedTestArtifactFile() { + return shadedArtifactFile("tests"); } // We need to find the direct dependencies that have been included in the uber JAR so that we can modify the // POM accordingly. - private void createDependencyReducedPom( Set artifactsToRemove ) - throws IOException, DependencyGraphBuilderException, ProjectBuildingException - { + private void createDependencyReducedPom(Set artifactsToRemove) + throws IOException, DependencyGraphBuilderException, ProjectBuildingException { List transitiveDeps = new ArrayList<>(); // NOTE: By using the getArtifacts() we get the completely evaluated artifacts // including the system scoped artifacts with expanded values of properties used. - for ( Artifact artifact : project.getArtifacts() ) - { - if ( "pom".equals( artifact.getType() ) ) - { + for (Artifact artifact : project.getArtifacts()) { + if ("pom".equals(artifact.getType())) { // don't include pom type dependencies in dependency reduced pom continue; } // promote - Dependency dep = createDependency( artifact ); + Dependency dep = createDependency(artifact); // we'll figure out the exclusions in a bit. - transitiveDeps.add( dep ); + transitiveDeps.add(dep); } Model model = project.getOriginalModel(); @@ -1109,9 +1007,8 @@ private void createDependencyReducedPom( Set artifactsToRemove ) // correctness of the build - or cause an endless loop. List origDeps = new ArrayList<>(); List source = promoteTransitiveDependencies ? transitiveDeps : project.getDependencies(); - for ( Dependency d : source ) - { - origDeps.add( d.clone() ); + for (Dependency d : source) { + origDeps.add(d.clone()); } model = model.clone(); @@ -1119,219 +1016,179 @@ private void createDependencyReducedPom( Set artifactsToRemove ) // have some kind of property usage. At this time the properties within // such things are already evaluated. List originalDependencies = model.getDependencies(); - removeSystemScopedDependencies( artifactsToRemove, originalDependencies ); + removeSystemScopedDependencies(artifactsToRemove, originalDependencies); List dependencies = new ArrayList<>(); boolean modified = false; - for ( Dependency d : origDeps ) - { - if ( artifactsToRemove.contains( getId( d ) ) ) - { - if ( keepDependenciesWithProvidedScope ) - { - if ( !"provided".equals( d.getScope() ) ) - { + for (Dependency d : origDeps) { + if (artifactsToRemove.contains(getId(d))) { + if (keepDependenciesWithProvidedScope) { + if (!"provided".equals(d.getScope())) { modified = true; - d.setScope( "provided" ); + d.setScope("provided"); } - } - else - { + } else { modified = true; continue; } } - dependencies.add( d ); + dependencies.add(d); } // MSHADE-155 - model.setArtifactId( shadedArtifactId ); + model.setArtifactId(shadedArtifactId); // MSHADE-185: We will add those system scoped dependencies // from the non interpolated original pom file. So we keep // things like this: ${tools.jar} intact. - addSystemScopedDependencyFromNonInterpolatedPom( dependencies, originalDependencies ); + addSystemScopedDependencyFromNonInterpolatedPom(dependencies, originalDependencies); // Check to see if we have a reduction and if so rewrite the POM. - rewriteDependencyReducedPomIfWeHaveReduction( dependencies, modified, transitiveDeps, model ); + rewriteDependencyReducedPomIfWeHaveReduction(dependencies, modified, transitiveDeps, model); } - private void rewriteDependencyReducedPomIfWeHaveReduction( List dependencies, boolean modified, - List transitiveDeps, Model model ) - throws IOException, ProjectBuildingException, - DependencyGraphBuilderException - { - if ( modified ) - { - for ( int loopCounter = 0; modified; loopCounter++ ) - { + private void rewriteDependencyReducedPomIfWeHaveReduction( + List dependencies, boolean modified, List transitiveDeps, Model model) + throws IOException, ProjectBuildingException, DependencyGraphBuilderException { + if (modified) { + for (int loopCounter = 0; modified; loopCounter++) { - model.setDependencies( dependencies ); + model.setDependencies(dependencies); - if ( generateUniqueDependencyReducedPom ) - { + if (generateUniqueDependencyReducedPom) { dependencyReducedPomLocation = - File.createTempFile( "dependency-reduced-pom-", ".xml", project.getBasedir() ); - project.getProperties().setProperty( "maven.shade.dependency-reduced-pom", - dependencyReducedPomLocation.getAbsolutePath() ); - } - else - { - if ( dependencyReducedPomLocation == null ) - { + File.createTempFile("dependency-reduced-pom-", ".xml", project.getBasedir()); + project.getProperties() + .setProperty( + "maven.shade.dependency-reduced-pom", + dependencyReducedPomLocation.getAbsolutePath()); + } else { + if (dependencyReducedPomLocation == null) { // MSHADE-123: We can't default to 'target' because it messes up uses of ${project.basedir} - dependencyReducedPomLocation = new File( project.getBasedir(), "dependency-reduced-pom.xml" ); + dependencyReducedPomLocation = new File(project.getBasedir(), "dependency-reduced-pom.xml"); } } File f = dependencyReducedPomLocation; // MSHADE-225 // Works for now, maybe there's a better algorithm where no for-loop is required - if ( loopCounter == 0 ) - { - getLog().info( "Dependency-reduced POM written at: " + f.getAbsolutePath() ); + if (loopCounter == 0) { + getLog().info("Dependency-reduced POM written at: " + f.getAbsolutePath()); } - if ( f.exists() ) - { + if (f.exists()) { // noinspection ResultOfMethodCallIgnored f.delete(); } - Writer w = WriterFactory.newXmlWriter( f ); + Writer w = WriterFactory.newXmlWriter(f); String replaceRelativePath = null; - if ( model.getParent() != null ) - { + if (model.getParent() != null) { replaceRelativePath = model.getParent().getRelativePath(); - } - if ( model.getParent() != null ) - { + if (model.getParent() != null) { File parentFile = - new File( project.getBasedir(), model.getParent().getRelativePath() ).getCanonicalFile(); - if ( !parentFile.isFile() ) - { - parentFile = new File( parentFile, "pom.xml" ); + new File(project.getBasedir(), model.getParent().getRelativePath()).getCanonicalFile(); + if (!parentFile.isFile()) { + parentFile = new File(parentFile, "pom.xml"); } parentFile = parentFile.getCanonicalFile(); - String relPath = RelativizePath.convertToRelativePath( parentFile, f ); - model.getParent().setRelativePath( relPath ); + String relPath = RelativizePath.convertToRelativePath(parentFile, f); + model.getParent().setRelativePath(relPath); } - try - { - PomWriter.write( w, model, true ); - } - finally - { - if ( model.getParent() != null ) - { - model.getParent().setRelativePath( replaceRelativePath ); + try { + PomWriter.write(w, model, true); + } finally { + if (model.getParent() != null) { + model.getParent().setRelativePath(replaceRelativePath); } w.close(); } ProjectBuildingRequest projectBuildingRequest = - new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ); - projectBuildingRequest.setLocalRepository( session.getLocalRepository() ); - projectBuildingRequest.setRemoteRepositories( project.getRemoteArtifactRepositories() ); + new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); + projectBuildingRequest.setLocalRepository(session.getLocalRepository()); + projectBuildingRequest.setRemoteRepositories(project.getRemoteArtifactRepositories()); - ProjectBuildingResult result = projectBuilder.build( f, projectBuildingRequest ); + ProjectBuildingResult result = projectBuilder.build(f, projectBuildingRequest); - getLog().debug( "updateExcludesInDeps()" ); - modified = updateExcludesInDeps( result.getProject(), dependencies, transitiveDeps ); + getLog().debug("updateExcludesInDeps()"); + modified = updateExcludesInDeps(result.getProject(), dependencies, transitiveDeps); } - project.setFile( dependencyReducedPomLocation ); + project.setFile(dependencyReducedPomLocation); } } - private void removeSystemScopedDependencies( Set artifactsToRemove, List originalDependencies ) - { - for ( Dependency dependency : originalDependencies ) - { - if ( dependency.getScope() != null && dependency.getScope().equalsIgnoreCase( "system" ) ) - { - artifactsToRemove.add( getId( dependency ) ); + private void removeSystemScopedDependencies(Set artifactsToRemove, List originalDependencies) { + for (Dependency dependency : originalDependencies) { + if (dependency.getScope() != null && dependency.getScope().equalsIgnoreCase("system")) { + artifactsToRemove.add(getId(dependency)); } } } - private void addSystemScopedDependencyFromNonInterpolatedPom( List dependencies, - List originalDependencies ) - { - for ( Dependency dependency : originalDependencies ) - { - if ( dependency.getScope() != null && dependency.getScope().equalsIgnoreCase( "system" ) ) - { - dependencies.add( dependency ); + private void addSystemScopedDependencyFromNonInterpolatedPom( + List dependencies, List originalDependencies) { + for (Dependency dependency : originalDependencies) { + if (dependency.getScope() != null && dependency.getScope().equalsIgnoreCase("system")) { + dependencies.add(dependency); } } } - private Dependency createDependency( Artifact artifact ) - { + private Dependency createDependency(Artifact artifact) { Dependency dep = new Dependency(); - dep.setArtifactId( artifact.getArtifactId() ); - if ( artifact.hasClassifier() ) - { - dep.setClassifier( artifact.getClassifier() ); + dep.setArtifactId(artifact.getArtifactId()); + if (artifact.hasClassifier()) { + dep.setClassifier(artifact.getClassifier()); } - dep.setGroupId( artifact.getGroupId() ); - dep.setOptional( artifact.isOptional() ); - dep.setScope( artifact.getScope() ); - dep.setType( artifact.getType() ); - if ( useBaseVersion ) - { - dep.setVersion( artifact.getBaseVersion() ); - } - else - { - dep.setVersion( artifact.getVersion() ); + dep.setGroupId(artifact.getGroupId()); + dep.setOptional(artifact.isOptional()); + dep.setScope(artifact.getScope()); + dep.setType(artifact.getType()); + if (useBaseVersion) { + dep.setVersion(artifact.getBaseVersion()); + } else { + dep.setVersion(artifact.getVersion()); } return dep; } - private String getId( Artifact artifact ) - { - return getId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(), artifact.getClassifier() ); + private String getId(Artifact artifact) { + return getId(artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(), artifact.getClassifier()); } - private String getId( Dependency dependency ) - { - return getId( dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), - dependency.getClassifier() ); + private String getId(Dependency dependency) { + return getId( + dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), dependency.getClassifier()); } - private String getId( String groupId, String artifactId, String type, String classifier ) - { - return groupId + ":" + artifactId + ":" + type + ":" + ( ( classifier != null ) ? classifier : "" ); + private String getId(String groupId, String artifactId, String type, String classifier) { + return groupId + ":" + artifactId + ":" + type + ":" + ((classifier != null) ? classifier : ""); } - public boolean updateExcludesInDeps( MavenProject project, List dependencies, - List transitiveDeps ) - throws DependencyGraphBuilderException - { + public boolean updateExcludesInDeps( + MavenProject project, List dependencies, List transitiveDeps) + throws DependencyGraphBuilderException { MavenProject original = session.getProjectBuildingRequest().getProject(); - try - { - session.getProjectBuildingRequest().setProject( project ); - DependencyNode node = dependencyGraphBuilder - .buildDependencyGraph( session.getProjectBuildingRequest(), null ); + try { + session.getProjectBuildingRequest().setProject(project); + DependencyNode node = + dependencyGraphBuilder.buildDependencyGraph(session.getProjectBuildingRequest(), null); boolean modified = false; - for ( DependencyNode n2 : node.getChildren() ) - { - String artifactId2 = getId( n2.getArtifact() ); + for (DependencyNode n2 : node.getChildren()) { + String artifactId2 = getId(n2.getArtifact()); - for ( DependencyNode n3 : n2.getChildren() ) - { + for (DependencyNode n3 : n2.getChildren()) { Artifact artifact3 = n3.getArtifact(); - String artifactId3 = getId( artifact3 ); + String artifactId3 = getId(artifact3); // check if it really isn't in the list of original dependencies. Maven // prior to 2.0.8 may grab versions from transients instead of @@ -1340,10 +1197,8 @@ public boolean updateExcludesInDeps( MavenProject project, List depe // also, if not promoting the transitives, level 2's would be included boolean found = false; - for ( Dependency dep : transitiveDeps ) - { - if ( getId( dep ).equals( artifactId3 ) ) - { + for (Dependency dep : transitiveDeps) { + if (getId(dep).equals(artifactId3)) { found = true; break; } @@ -1353,28 +1208,24 @@ public boolean updateExcludesInDeps( MavenProject project, List depe // note: MSHADE-31 introduced the exclusion logic for promoteTransitiveDependencies=true, // but as of 3.2.1 promoteTransitiveDependencies has no effect for provided deps, // which makes this fix even possible (see also MSHADE-181) - if ( !found && !"provided".equals( artifact3.getScope() ) ) - { - getLog().debug( String.format( "dependency %s (scope %s) not found in transitive dependencies", - artifactId3, artifact3.getScope() ) ); - for ( Dependency dep : dependencies ) - { - if ( getId( dep ).equals( artifactId2 ) ) - { + if (!found && !"provided".equals(artifact3.getScope())) { + getLog().debug(String.format( + "dependency %s (scope %s) not found in transitive dependencies", + artifactId3, artifact3.getScope())); + for (Dependency dep : dependencies) { + if (getId(dep).equals(artifactId2)) { // MSHADE-413: First check whether the exclusion has already been added, // because it's meaningless to add it more than once. Certain cases // can end up adding the exclusion "forever" and cause an endless loop // rewriting the whole dependency-reduced-pom.xml file. - if ( !dependencyHasExclusion( dep, artifact3 ) ) - { - getLog().debug( String.format( "Adding exclusion for dependency %s (scope %s) " - + "to %s (scope %s)", - artifactId3, artifact3.getScope(), - getId( dep ), dep.getScope() ) ); + if (!dependencyHasExclusion(dep, artifact3)) { + getLog().debug(String.format( + "Adding exclusion for dependency %s (scope %s) " + "to %s (scope %s)", + artifactId3, artifact3.getScope(), getId(dep), dep.getScope())); Exclusion exclusion = new Exclusion(); - exclusion.setArtifactId( artifact3.getArtifactId() ); - exclusion.setGroupId( artifact3.getGroupId() ); - dep.addExclusion( exclusion ); + exclusion.setArtifactId(artifact3.getArtifactId()); + exclusion.setGroupId(artifact3.getGroupId()); + dep.addExclusion(exclusion); modified = true; break; } @@ -1384,22 +1235,17 @@ public boolean updateExcludesInDeps( MavenProject project, List depe } } return modified; - } - finally - { + } finally { // restore it - session.getProjectBuildingRequest().setProject( original ); + session.getProjectBuildingRequest().setProject(original); } } - private boolean dependencyHasExclusion( Dependency dep, Artifact exclusionToCheck ) - { + private boolean dependencyHasExclusion(Dependency dep, Artifact exclusionToCheck) { boolean containsExclusion = false; - for ( Exclusion existingExclusion : dep.getExclusions() ) - { - if ( existingExclusion.getGroupId().equals( exclusionToCheck.getGroupId() ) - && existingExclusion.getArtifactId().equals( exclusionToCheck.getArtifactId() ) ) - { + for (Exclusion existingExclusion : dep.getExclusions()) { + if (existingExclusion.getGroupId().equals(exclusionToCheck.getGroupId()) + && existingExclusion.getArtifactId().equals(exclusionToCheck.getArtifactId())) { containsExclusion = true; break; } @@ -1408,39 +1254,29 @@ private boolean dependencyHasExclusion( Dependency dep, Artifact exclusionToChec } private List toResourceTransformers( - String shade, List resourceTransformers ) - { - List forShade = new ArrayList<>(); - ManifestResourceTransformer lastMt = null; - for ( ResourceTransformer transformer : resourceTransformers ) - { - if ( !( transformer instanceof ManifestResourceTransformer ) ) - { - forShade.add( transformer ); - } - else if ( ( ( ManifestResourceTransformer ) transformer ) .isForShade( shade ) ) - { - final ManifestResourceTransformer mt = (ManifestResourceTransformer) transformer; - if ( mt.isUsedForDefaultShading() && lastMt != null && !lastMt.isUsedForDefaultShading() ) - { - continue; // skip, we already have a specific transformer - } - if ( !mt.isUsedForDefaultShading() && lastMt != null && lastMt.isUsedForDefaultShading() ) - { - forShade.remove( lastMt ); - } - else if ( !mt.isUsedForDefaultShading() && lastMt != null ) - { - getLog().warn( "Ambiguous manifest transformer definition for '" + shade + "': " - + mt + " / " + lastMt ); - } - if ( lastMt == null || !mt.isUsedForDefaultShading() ) - { - lastMt = mt; - } - forShade.add( transformer ); - } - } - return forShade; + String shade, List resourceTransformers) { + List forShade = new ArrayList<>(); + ManifestResourceTransformer lastMt = null; + for (ResourceTransformer transformer : resourceTransformers) { + if (!(transformer instanceof ManifestResourceTransformer)) { + forShade.add(transformer); + } else if (((ManifestResourceTransformer) transformer).isForShade(shade)) { + final ManifestResourceTransformer mt = (ManifestResourceTransformer) transformer; + if (mt.isUsedForDefaultShading() && lastMt != null && !lastMt.isUsedForDefaultShading()) { + continue; // skip, we already have a specific transformer + } + if (!mt.isUsedForDefaultShading() && lastMt != null && lastMt.isUsedForDefaultShading()) { + forShade.remove(lastMt); + } else if (!mt.isUsedForDefaultShading() && lastMt != null) { + getLog().warn("Ambiguous manifest transformer definition for '" + shade + "': " + mt + " / " + + lastMt); + } + if (lastMt == null || !mt.isUsedForDefaultShading()) { + lastMt = mt; + } + forShade.add(transformer); + } + } + return forShade; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/pom/Counter.java b/src/main/java/org/apache/maven/plugins/shade/pom/Counter.java index aec94886..80ec5702 100644 --- a/src/main/java/org/apache/maven/plugins/shade/pom/Counter.java +++ b/src/main/java/org/apache/maven/plugins/shade/pom/Counter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.pom; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.pom; /** * Separate class for counter. */ -public class Counter -{ +public class Counter { // --------------------------/ // - Class/Member Variables -/ @@ -43,8 +41,7 @@ public class Counter // - Constructors -/ // ----------------/ - public Counter( int depthLevel ) - { + public Counter(int depthLevel) { level = depthLevel; } // -- org.apache.maven.model.io.jdom.Counter(int) @@ -55,8 +52,7 @@ public Counter( int depthLevel ) /** * Method getCurrentIndex */ - public int getCurrentIndex() - { + public int getCurrentIndex() { return currentIndex; } // -- int getCurrentIndex() @@ -64,17 +60,14 @@ public int getCurrentIndex() * Method getDepth * @return {@link #level} */ - public int getDepth() - { + public int getDepth() { return level; } // -- int getDepth() /** * Method increaseCount */ - public void increaseCount() - { + public void increaseCount() { currentIndex = currentIndex + 1; } // -- void increaseCount() - } diff --git a/src/main/java/org/apache/maven/plugins/shade/pom/MavenJDOMWriter.java b/src/main/java/org/apache/maven/plugins/shade/pom/MavenJDOMWriter.java index ebd65c66..5d3db047 100644 --- a/src/main/java/org/apache/maven/plugins/shade/pom/MavenJDOMWriter.java +++ b/src/main/java/org/apache/maven/plugins/shade/pom/MavenJDOMWriter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.pom; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.pom; import java.io.IOException; import java.io.OutputStream; @@ -86,8 +85,7 @@ * Class MavenJDOMWriter. * */ -public class MavenJDOMWriter -{ +public class MavenJDOMWriter { /** * Field factory */ @@ -98,15 +96,13 @@ public class MavenJDOMWriter */ private final String lineSeparator; - public MavenJDOMWriter() - { - this( "\n" ); + public MavenJDOMWriter() { + this("\n"); } - public MavenJDOMWriter( final String lineSeparator ) - { + public MavenJDOMWriter(final String lineSeparator) { this.factory = new DefaultJDOMFactory(); - this.lineSeparator = Objects.requireNonNull( lineSeparator ); + this.lineSeparator = Objects.requireNonNull(lineSeparator); } /** @@ -118,27 +114,22 @@ public MavenJDOMWriter( final String lineSeparator ) * @param parent {@link Element} * @return {@link Element} */ - protected Element findAndReplaceProperties( Counter counter, Element parent, String name, Map props ) - { + protected Element findAndReplaceProperties(Counter counter, Element parent, String name, Map props) { Map properties = props; boolean shouldExist = properties != null && !properties.isEmpty(); - Element element = updateElement( counter, parent, name, shouldExist ); - if ( shouldExist ) - { - Counter innerCounter = new Counter( counter.getDepth() + 1 ); - for ( Map.Entry entry : properties.entrySet() ) - { + Element element = updateElement(counter, parent, name, shouldExist); + if (shouldExist) { + Counter innerCounter = new Counter(counter.getDepth() + 1); + for (Map.Entry entry : properties.entrySet()) { String key = entry.getKey(); - findAndReplaceSimpleElement( innerCounter, element, key, entry.getValue(), null ); + findAndReplaceSimpleElement(innerCounter, element, key, entry.getValue(), null); } - List lst = new ArrayList<>( properties.keySet() ); + List lst = new ArrayList<>(properties.keySet()); Iterator it = element.getChildren().iterator(); - while ( it.hasNext() ) - { + while (it.hasNext()) { Element elem = it.next(); String key = elem.getName(); - if ( !lst.contains( key ) ) - { + if (!lst.contains(key)) { it.remove(); } } @@ -156,23 +147,19 @@ protected Element findAndReplaceProperties( Counter counter, Element parent, Str * @param parent The parent. * @return {@link Element} */ - protected Element findAndReplaceSimpleElement( Counter counter, Element parent, String name, String text, - String defaultValue ) - { - if ( defaultValue != null && text != null && defaultValue.equals( text ) ) - { - Element element = parent.getChild( name, parent.getNamespace() ); + protected Element findAndReplaceSimpleElement( + Counter counter, Element parent, String name, String text, String defaultValue) { + if (defaultValue != null && text != null && defaultValue.equals(text)) { + Element element = parent.getChild(name, parent.getNamespace()); // if exist and is default value or if doesn't exist.. just keep the way it is.. - if ( element == null || defaultValue.equals( element.getText() ) ) - { + if (element == null || defaultValue.equals(element.getText())) { return element; } } boolean shouldExist = text != null && text.trim().length() > 0; - Element element = updateElement( counter, parent, name, shouldExist ); - if ( shouldExist ) - { - element.setText( text ); + Element element = updateElement(counter, parent, name, shouldExist); + if (shouldExist) { + element.setText(text); } return element; } @@ -187,42 +174,33 @@ protected Element findAndReplaceSimpleElement( Counter counter, Element parent, * @param parent The parent. * @return {@link Element} */ - protected Element findAndReplaceSimpleLists( Counter counter, Element parent, Collection list, - String parentName, String childName ) - { + protected Element findAndReplaceSimpleLists( + Counter counter, Element parent, Collection list, String parentName, String childName) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentName, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childName, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentName, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childName, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( String value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (String value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childName, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childName, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - el.setText( value ); + el.setText(value); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -240,13 +218,11 @@ protected Element findAndReplaceSimpleLists( Counter counter, Element parent, Co * @param parent The parent. * @return {@link Element} */ - protected Element findAndReplaceXpp3DOM( Counter counter, Element parent, String name, Xpp3Dom dom ) - { - boolean shouldExist = dom != null && ( dom.getChildCount() > 0 || dom.getValue() != null ); - Element element = updateElement( counter, parent, name, shouldExist ); - if ( shouldExist ) - { - replaceXpp3DOM( element, dom, new Counter( counter.getDepth() + 1 ) ); + protected Element findAndReplaceXpp3DOM(Counter counter, Element parent, String name, Xpp3Dom dom) { + boolean shouldExist = dom != null && (dom.getChildCount() > 0 || dom.getValue() != null); + Element element = updateElement(counter, parent, name, shouldExist); + if (shouldExist) { + replaceXpp3DOM(element, dom, new Counter(counter.getDepth() + 1)); } return element; } @@ -258,49 +234,41 @@ protected Element findAndReplaceXpp3DOM( Counter counter, Element parent, String * @param counter {@link Counter} * @param child {@link Element} */ - protected void insertAtPreferredLocation( Element parent, Element child, Counter counter ) - { + protected void insertAtPreferredLocation(Element parent, Element child, Counter counter) { int contentIndex = 0; int elementCounter = 0; Iterator it = parent.getContent().iterator(); Text lastText = null; int offset = 0; - while ( it.hasNext() && elementCounter <= counter.getCurrentIndex() ) - { + while (it.hasNext() && elementCounter <= counter.getCurrentIndex()) { Object next = it.next(); offset = offset + 1; - if ( next instanceof Element ) - { + if (next instanceof Element) { elementCounter = elementCounter + 1; contentIndex = contentIndex + offset; offset = 0; } - if ( next instanceof Text && it.hasNext() ) - { + if (next instanceof Text && it.hasNext()) { lastText = (Text) next; } } - if ( lastText != null && lastText.getTextTrim().length() == 0 ) - { + if (lastText != null && lastText.getTextTrim().length() == 0) { lastText = lastText.clone(); - } - else - { - StringBuilder starter = new StringBuilder( lineSeparator ); - for ( int i = 0; i < counter.getDepth(); i++ ) - { - starter.append( " " ); // TODO make settable? + } else { + StringBuilder starter = new StringBuilder(lineSeparator); + for (int i = 0; i < counter.getDepth(); i++) { + starter.append(" "); // TODO make settable? } - lastText = factory.text( starter.toString() ); + lastText = factory.text(starter.toString()); } - if ( parent.getContentSize() == 0 ) - { + if (parent.getContentSize() == 0) { Text finalText = lastText.clone(); - finalText.setText( finalText.getText().substring( 0, finalText.getText().length() - " ".length() ) ); - parent.addContent( contentIndex, finalText ); + finalText.setText( + finalText.getText().substring(0, finalText.getText().length() - " ".length())); + parent.addContent(contentIndex, finalText); } - parent.addContent( contentIndex, child ); - parent.addContent( contentIndex, lastText ); + parent.addContent(contentIndex, child); + parent.addContent(contentIndex, lastText); } /** @@ -312,42 +280,33 @@ protected void insertAtPreferredLocation( Element parent, Element child, Counter * @param list The list of elements. * @param parent The parent. */ - protected void iterateContributor( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateContributor( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Contributor value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Contributor value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateContributor( value, childTag, innerCount, el ); + updateContributor(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -364,42 +323,33 @@ protected void iterateContributor( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateDependency( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Dependency value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Dependency value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateDependency( value, childTag, innerCount, el ); + updateDependency(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -416,42 +366,33 @@ protected void iterateDependency( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateDeveloper( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Developer value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Developer value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateDeveloper( value, childTag, innerCount, el ); + updateDeveloper(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -468,42 +409,33 @@ protected void iterateDeveloper( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateExclusion( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Exclusion value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Exclusion value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateExclusion( value, childTag, innerCount, el ); + updateExclusion(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -520,42 +452,33 @@ protected void iterateExclusion( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateExtension( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Extension value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Extension value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateExtension( value, childTag, innerCount, el ); + updateExtension(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -572,42 +495,33 @@ protected void iterateExtension( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateLicense( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( License value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (License value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateLicense( value, childTag, innerCount, el ); + updateLicense(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -624,42 +538,33 @@ protected void iterateLicense( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateMailingList( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( MailingList value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (MailingList value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateMailingList( value, childTag, innerCount, el ); + updateMailingList(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -676,42 +581,33 @@ protected void iterateMailingList( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateNotifier( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Notifier value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Notifier value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateNotifier( value, childTag, innerCount, el ); + updateNotifier(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -728,42 +624,33 @@ protected void iterateNotifier( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iteratePlugin( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Plugin value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Plugin value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updatePlugin( value, childTag, innerCount, el ); + updatePlugin(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -780,42 +667,33 @@ protected void iteratePlugin( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iteratePluginExecution( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( PluginExecution value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (PluginExecution value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updatePluginExecution( value, childTag, innerCount, el ); + updatePluginExecution(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -832,42 +710,33 @@ protected void iteratePluginExecution( Counter counter, Element parent, Collecti * @param list The list of elements. * @param parent The parent. */ - protected void iterateProfile( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateProfile( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Profile value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Profile value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateProfile( value, childTag, innerCount, el ); + updateProfile(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -884,42 +753,33 @@ protected void iterateProfile( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateReportPlugin( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( ReportPlugin value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (ReportPlugin value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateReportPlugin( value, childTag, innerCount, el ); + updateReportPlugin(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -936,42 +796,33 @@ protected void iterateReportPlugin( Counter counter, Element parent, Collection< * @param list The list of elements. * @param parent The parent. */ - protected void iterateReportSet( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateReportSet( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( ReportSet value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (ReportSet value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateReportSet( value, childTag, innerCount, el ); + updateReportSet(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -988,42 +839,33 @@ protected void iterateReportSet( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateRepository( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Repository value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Repository value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateRepository( value, childTag, innerCount, el ); + updateRepository(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -1040,42 +882,33 @@ protected void iterateRepository( Counter counter, Element parent, Collection list, - String parentTag, String childTag ) - { + protected void iterateResource( + Counter counter, Element parent, Collection list, String parentTag, String childTag) { boolean shouldExist = list != null && list.size() > 0; - Element element = updateElement( counter, parent, parentTag, shouldExist ); - if ( shouldExist ) - { - Iterator elIt = element.getChildren( childTag, element.getNamespace() ).iterator(); - if ( !elIt.hasNext() ) - { + Element element = updateElement(counter, parent, parentTag, shouldExist); + if (shouldExist) { + Iterator elIt = + element.getChildren(childTag, element.getNamespace()).iterator(); + if (!elIt.hasNext()) { elIt = null; } - Counter innerCount = new Counter( counter.getDepth() + 1 ); - for ( Resource value : list ) - { + Counter innerCount = new Counter(counter.getDepth() + 1); + for (Resource value : list) { Element el; - if ( elIt != null && elIt.hasNext() ) - { + if (elIt != null && elIt.hasNext()) { el = elIt.next(); - if ( !elIt.hasNext() ) - { + if (!elIt.hasNext()) { elIt = null; } + } else { + el = factory.element(childTag, element.getNamespace()); + insertAtPreferredLocation(element, el, innerCount); } - else - { - el = factory.element( childTag, element.getNamespace() ); - insertAtPreferredLocation( element, el, innerCount ); - } - updateResource( value, childTag, innerCount, el ); + updateResource(value, childTag, innerCount, el); innerCount.increaseCount(); } - if ( elIt != null ) - { - while ( elIt.hasNext() ) - { + if (elIt != null) { + while (elIt.hasNext()) { elIt.next(); elIt.remove(); } @@ -1090,47 +923,36 @@ protected void iterateResource( Counter counter, Element parent, Collection 0 ) - { + protected void replaceXpp3DOM(Element parent, Xpp3Dom parentDom, Counter counter) { + if (parentDom.getChildCount() > 0) { Xpp3Dom[] childs = parentDom.getChildren(); Collection domChilds = new ArrayList<>(); - Collections.addAll( domChilds, childs ); + Collections.addAll(domChilds, childs); // int domIndex = 0; - for ( Element elem : parent.getChildren() ) - { + for (Element elem : parent.getChildren()) { Xpp3Dom corrDom = null; - for ( Xpp3Dom dm : domChilds ) - { - if ( dm.getName().equals( elem.getName() ) ) - { + for (Xpp3Dom dm : domChilds) { + if (dm.getName().equals(elem.getName())) { corrDom = dm; break; } } - if ( corrDom != null ) - { - domChilds.remove( corrDom ); - replaceXpp3DOM( elem, corrDom, new Counter( counter.getDepth() + 1 ) ); + if (corrDom != null) { + domChilds.remove(corrDom); + replaceXpp3DOM(elem, corrDom, new Counter(counter.getDepth() + 1)); counter.increaseCount(); - } - else - { - parent.removeContent( elem ); + } else { + parent.removeContent(elem); } } - for ( Xpp3Dom dm : domChilds ) - { - Element elem = factory.element( dm.getName(), parent.getNamespace() ); - insertAtPreferredLocation( parent, elem, counter ); + for (Xpp3Dom dm : domChilds) { + Element elem = factory.element(dm.getName(), parent.getNamespace()); + insertAtPreferredLocation(parent, elem, counter); counter.increaseCount(); - replaceXpp3DOM( elem, dm, new Counter( counter.getDepth() + 1 ) ); + replaceXpp3DOM(elem, dm, new Counter(counter.getDepth() + 1)); } - } - else if ( parentDom.getValue() != null ) - { - parent.setText( parentDom.getValue() ); + } else if (parentDom.getValue() != null) { + parent.setText(parentDom.getValue()); } } @@ -1142,15 +964,13 @@ else if ( parentDom.getValue() != null ) * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateActivationFile( ActivationFile value, String xmlTag, Counter counter, Element element ) - { + protected void updateActivationFile(ActivationFile value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "missing", value.getMissing(), null ); - findAndReplaceSimpleElement( innerCount, root, "exists", value.getExists(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "missing", value.getMissing(), null); + findAndReplaceSimpleElement(innerCount, root, "exists", value.getExists(), null); } } @@ -1162,17 +982,15 @@ protected void updateActivationFile( ActivationFile value, String xmlTag, Counte * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateActivationOS( ActivationOS value, String xmlTag, Counter counter, Element element ) - { + protected void updateActivationOS(ActivationOS value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "family", value.getFamily(), null ); - findAndReplaceSimpleElement( innerCount, root, "arch", value.getArch(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "family", value.getFamily(), null); + findAndReplaceSimpleElement(innerCount, root, "arch", value.getArch(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); } } @@ -1184,15 +1002,13 @@ protected void updateActivationOS( ActivationOS value, String xmlTag, Counter co * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateActivationProperty( ActivationProperty value, String xmlTag, Counter counter, Element element ) - { + protected void updateActivationProperty(ActivationProperty value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "value", value.getValue(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "value", value.getValue(), null); } } @@ -1204,32 +1020,30 @@ protected void updateActivationProperty( ActivationProperty value, String xmlTag * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - //CHECKSTYLE_OFF: LineLength - protected void updateBuild( Build value, String xmlTag, Counter counter, Element element ) - { + // CHECKSTYLE_OFF: LineLength + protected void updateBuild(Build value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "sourceDirectory", value.getSourceDirectory(), null ); - findAndReplaceSimpleElement( innerCount, root, "scriptSourceDirectory", value.getScriptSourceDirectory(), - null ); - findAndReplaceSimpleElement( innerCount, root, "testSourceDirectory", value.getTestSourceDirectory(), null ); - findAndReplaceSimpleElement( innerCount, root, "outputDirectory", value.getOutputDirectory(), null ); - findAndReplaceSimpleElement( innerCount, root, "testOutputDirectory", value.getTestOutputDirectory(), null ); - iterateExtension( innerCount, root, value.getExtensions(), "extensions", "extension" ); - findAndReplaceSimpleElement( innerCount, root, "defaultGoal", value.getDefaultGoal(), null ); - iterateResource( innerCount, root, value.getResources(), "resources", "resource" ); - iterateResource( innerCount, root, value.getTestResources(), "testResources", "testResource" ); - findAndReplaceSimpleElement( innerCount, root, "directory", value.getDirectory(), null ); - findAndReplaceSimpleElement( innerCount, root, "finalName", value.getFinalName(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getFilters(), "filters", "filter" ); - updatePluginManagement( value.getPluginManagement(), "pluginManagement", innerCount, root ); - iteratePlugin( innerCount, root, value.getPlugins(), "plugins", "plugin" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "sourceDirectory", value.getSourceDirectory(), null); + findAndReplaceSimpleElement( + innerCount, root, "scriptSourceDirectory", value.getScriptSourceDirectory(), null); + findAndReplaceSimpleElement(innerCount, root, "testSourceDirectory", value.getTestSourceDirectory(), null); + findAndReplaceSimpleElement(innerCount, root, "outputDirectory", value.getOutputDirectory(), null); + findAndReplaceSimpleElement(innerCount, root, "testOutputDirectory", value.getTestOutputDirectory(), null); + iterateExtension(innerCount, root, value.getExtensions(), "extensions", "extension"); + findAndReplaceSimpleElement(innerCount, root, "defaultGoal", value.getDefaultGoal(), null); + iterateResource(innerCount, root, value.getResources(), "resources", "resource"); + iterateResource(innerCount, root, value.getTestResources(), "testResources", "testResource"); + findAndReplaceSimpleElement(innerCount, root, "directory", value.getDirectory(), null); + findAndReplaceSimpleElement(innerCount, root, "finalName", value.getFinalName(), null); + findAndReplaceSimpleLists(innerCount, root, value.getFilters(), "filters", "filter"); + updatePluginManagement(value.getPluginManagement(), "pluginManagement", innerCount, root); + iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); } } - //CHECKSTYLE_ON: LineLength + // CHECKSTYLE_ON: LineLength /** * Method updateBuildBase @@ -1239,21 +1053,19 @@ protected void updateBuild( Build value, String xmlTag, Counter counter, Element * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateBuildBase( BuildBase value, String xmlTag, Counter counter, Element element ) - { + protected void updateBuildBase(BuildBase value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "defaultGoal", value.getDefaultGoal(), null ); - iterateResource( innerCount, root, value.getResources(), "resources", "resource" ); - iterateResource( innerCount, root, value.getTestResources(), "testResources", "testResource" ); - findAndReplaceSimpleElement( innerCount, root, "directory", value.getDirectory(), null ); - findAndReplaceSimpleElement( innerCount, root, "finalName", value.getFinalName(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getFilters(), "filters", "filter" ); - updatePluginManagement( value.getPluginManagement(), "pluginManagement", innerCount, root ); - iteratePlugin( innerCount, root, value.getPlugins(), "plugins", "plugin" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "defaultGoal", value.getDefaultGoal(), null); + iterateResource(innerCount, root, value.getResources(), "resources", "resource"); + iterateResource(innerCount, root, value.getTestResources(), "testResources", "testResource"); + findAndReplaceSimpleElement(innerCount, root, "directory", value.getDirectory(), null); + findAndReplaceSimpleElement(innerCount, root, "finalName", value.getFinalName(), null); + findAndReplaceSimpleLists(innerCount, root, value.getFilters(), "filters", "filter"); + updatePluginManagement(value.getPluginManagement(), "pluginManagement", innerCount, root); + iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); } } @@ -1265,16 +1077,14 @@ protected void updateBuildBase( BuildBase value, String xmlTag, Counter counter, * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateCiManagement( CiManagement value, String xmlTag, Counter counter, Element element ) - { + protected void updateCiManagement(CiManagement value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "system", value.getSystem(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - iterateNotifier( innerCount, root, value.getNotifiers(), "notifiers", "notifier" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "system", value.getSystem(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + iterateNotifier(innerCount, root, value.getNotifiers(), "notifiers", "notifier"); } } @@ -1286,16 +1096,14 @@ protected void updateCiManagement( CiManagement value, String xmlTag, Counter co * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateConfigurationContainer( ConfigurationContainer value, String xmlTag, Counter counter, - Element element ) - { + protected void updateConfigurationContainer( + ConfigurationContainer value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "inherited", value.getInherited(), null ); - findAndReplaceXpp3DOM( innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration() ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "inherited", value.getInherited(), null); + findAndReplaceXpp3DOM(innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration()); } } @@ -1307,18 +1115,17 @@ protected void updateConfigurationContainer( ConfigurationContainer value, Strin * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateContributor( Contributor value, String xmlTag, Counter counter, Element element ) - { + protected void updateContributor(Contributor value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "email", value.getEmail(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - findAndReplaceSimpleElement( innerCount, root, "organization", value.getOrganization(), null ); - findAndReplaceSimpleElement( innerCount, root, "organizationUrl", value.getOrganizationUrl(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getRoles(), "roles", "role" ); - findAndReplaceSimpleElement( innerCount, root, "timezone", value.getTimezone(), null ); - findAndReplaceProperties( innerCount, root, "properties", value.getProperties() ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "email", value.getEmail(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + findAndReplaceSimpleElement(innerCount, root, "organization", value.getOrganization(), null); + findAndReplaceSimpleElement(innerCount, root, "organizationUrl", value.getOrganizationUrl(), null); + findAndReplaceSimpleLists(innerCount, root, value.getRoles(), "roles", "role"); + findAndReplaceSimpleElement(innerCount, root, "timezone", value.getTimezone(), null); + findAndReplaceProperties(innerCount, root, "properties", value.getProperties()); } /** @@ -1329,20 +1136,19 @@ protected void updateContributor( Contributor value, String xmlTag, Counter coun * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateDependency( Dependency value, String xmlTag, Counter counter, Element element ) - { + protected void updateDependency(Dependency value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), null ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); - findAndReplaceSimpleElement( innerCount, root, "type", value.getType(), "jar" ); - findAndReplaceSimpleElement( innerCount, root, "classifier", value.getClassifier(), null ); - findAndReplaceSimpleElement( innerCount, root, "scope", value.getScope(), null ); - findAndReplaceSimpleElement( innerCount, root, "systemPath", value.getSystemPath(), null ); - iterateExclusion( innerCount, root, value.getExclusions(), "exclusions", "exclusion" ); - findAndReplaceSimpleElement( innerCount, root, "optional", - !value.isOptional() ? null : String.valueOf( value.isOptional() ), "false" ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), null); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); + findAndReplaceSimpleElement(innerCount, root, "type", value.getType(), "jar"); + findAndReplaceSimpleElement(innerCount, root, "classifier", value.getClassifier(), null); + findAndReplaceSimpleElement(innerCount, root, "scope", value.getScope(), null); + findAndReplaceSimpleElement(innerCount, root, "systemPath", value.getSystemPath(), null); + iterateExclusion(innerCount, root, value.getExclusions(), "exclusions", "exclusion"); + findAndReplaceSimpleElement( + innerCount, root, "optional", !value.isOptional() ? null : String.valueOf(value.isOptional()), "false"); } /** @@ -1353,15 +1159,13 @@ protected void updateDependency( Dependency value, String xmlTag, Counter counte * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateDependencyManagement( DependencyManagement value, String xmlTag, Counter counter, - Element element ) - { + protected void updateDependencyManagement( + DependencyManagement value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - iterateDependency( innerCount, root, value.getDependencies(), "dependencies", "dependency" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + iterateDependency(innerCount, root, value.getDependencies(), "dependencies", "dependency"); } } @@ -1373,21 +1177,22 @@ protected void updateDependencyManagement( DependencyManagement value, String xm * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateDeploymentRepository( DeploymentRepository value, String xmlTag, Counter counter, - Element element ) - { + protected void updateDeploymentRepository( + DeploymentRepository value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "uniqueVersion", - value.isUniqueVersion() ? null : String.valueOf( value.isUniqueVersion() ), - "true" ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), null ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - findAndReplaceSimpleElement( innerCount, root, "layout", value.getLayout(), "default" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement( + innerCount, + root, + "uniqueVersion", + value.isUniqueVersion() ? null : String.valueOf(value.isUniqueVersion()), + "true"); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + findAndReplaceSimpleElement(innerCount, root, "layout", value.getLayout(), "default"); } } @@ -1399,19 +1204,18 @@ protected void updateDeploymentRepository( DeploymentRepository value, String xm * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateDeveloper( Developer value, String xmlTag, Counter counter, Element element ) - { + protected void updateDeveloper(Developer value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), null ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "email", value.getEmail(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - findAndReplaceSimpleElement( innerCount, root, "organization", value.getOrganization(), null ); - findAndReplaceSimpleElement( innerCount, root, "organizationUrl", value.getOrganizationUrl(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getRoles(), "roles", "role" ); - findAndReplaceSimpleElement( innerCount, root, "timezone", value.getTimezone(), null ); - findAndReplaceProperties( innerCount, root, "properties", value.getProperties() ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "email", value.getEmail(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + findAndReplaceSimpleElement(innerCount, root, "organization", value.getOrganization(), null); + findAndReplaceSimpleElement(innerCount, root, "organizationUrl", value.getOrganizationUrl(), null); + findAndReplaceSimpleLists(innerCount, root, value.getRoles(), "roles", "role"); + findAndReplaceSimpleElement(innerCount, root, "timezone", value.getTimezone(), null); + findAndReplaceProperties(innerCount, root, "properties", value.getProperties()); } /** @@ -1422,20 +1226,18 @@ protected void updateDeveloper( Developer value, String xmlTag, Counter counter, * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateDistributionManagement( DistributionManagement value, String xmlTag, Counter counter, - Element element ) - { + protected void updateDistributionManagement( + DistributionManagement value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - updateDeploymentRepository( value.getRepository(), "repository", innerCount, root ); - updateDeploymentRepository( value.getSnapshotRepository(), "snapshotRepository", innerCount, root ); - updateSite( value.getSite(), "site", innerCount, root ); - findAndReplaceSimpleElement( innerCount, root, "downloadUrl", value.getDownloadUrl(), null ); - updateRelocation( value.getRelocation(), "relocation", innerCount, root ); - findAndReplaceSimpleElement( innerCount, root, "status", value.getStatus(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + updateDeploymentRepository(value.getRepository(), "repository", innerCount, root); + updateDeploymentRepository(value.getSnapshotRepository(), "snapshotRepository", innerCount, root); + updateSite(value.getSite(), "site", innerCount, root); + findAndReplaceSimpleElement(innerCount, root, "downloadUrl", value.getDownloadUrl(), null); + updateRelocation(value.getRelocation(), "relocation", innerCount, root); + findAndReplaceSimpleElement(innerCount, root, "status", value.getStatus(), null); } } @@ -1448,35 +1250,28 @@ protected void updateDistributionManagement( DistributionManagement value, Strin * @param parent The parent. * @return {@link Element} */ - protected Element updateElement( Counter counter, Element parent, String name, boolean shouldExist ) - { - Element element = parent.getChild( name, parent.getNamespace() ); - if ( element != null && shouldExist ) - { + protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist) { + Element element = parent.getChild(name, parent.getNamespace()); + if (element != null && shouldExist) { counter.increaseCount(); } - if ( element == null && shouldExist ) - { - element = factory.element( name, parent.getNamespace() ); - insertAtPreferredLocation( parent, element, counter ); + if (element == null && shouldExist) { + element = factory.element(name, parent.getNamespace()); + insertAtPreferredLocation(parent, element, counter); counter.increaseCount(); } - if ( !shouldExist && element != null ) - { - int index = parent.indexOf( element ); - if ( index > 0 ) - { - Content previous = parent.getContent( index - 1 ); - if ( previous instanceof Text ) - { + if (!shouldExist && element != null) { + int index = parent.indexOf(element); + if (index > 0) { + Content previous = parent.getContent(index - 1); + if (previous instanceof Text) { Text txt = (Text) previous; - if ( txt.getTextTrim().length() == 0 ) - { - parent.removeContent( txt ); + if (txt.getTextTrim().length() == 0) { + parent.removeContent(txt); } } } - parent.removeContent( element ); + parent.removeContent(element); } return element; } @@ -1489,12 +1284,11 @@ protected Element updateElement( Counter counter, Element parent, String name, b * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateExclusion( Exclusion value, String xmlTag, Counter counter, Element element ) - { + protected void updateExclusion(Exclusion value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), null ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), null); } /** @@ -1505,13 +1299,12 @@ protected void updateExclusion( Exclusion value, String xmlTag, Counter counter, * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateExtension( Extension value, String xmlTag, Counter counter, Element element ) - { + protected void updateExtension(Extension value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), null ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), null); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); } /** @@ -1522,16 +1315,14 @@ protected void updateExtension( Extension value, String xmlTag, Counter counter, * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateFileSet( FileSet value, String xmlTag, Counter counter, Element element ) - { + protected void updateFileSet(FileSet value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "directory", value.getDirectory(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getIncludes(), "includes", "include" ); - findAndReplaceSimpleLists( innerCount, root, value.getExcludes(), "excludes", "exclude" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "directory", value.getDirectory(), null); + findAndReplaceSimpleLists(innerCount, root, value.getIncludes(), "includes", "include"); + findAndReplaceSimpleLists(innerCount, root, value.getExcludes(), "excludes", "exclude"); } } @@ -1543,15 +1334,13 @@ protected void updateFileSet( FileSet value, String xmlTag, Counter counter, Ele * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateIssueManagement( IssueManagement value, String xmlTag, Counter counter, Element element ) - { + protected void updateIssueManagement(IssueManagement value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "system", value.getSystem(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "system", value.getSystem(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); } } @@ -1563,14 +1352,13 @@ protected void updateIssueManagement( IssueManagement value, String xmlTag, Coun * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateLicense( License value, String xmlTag, Counter counter, Element element ) - { + protected void updateLicense(License value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - findAndReplaceSimpleElement( innerCount, root, "distribution", value.getDistribution(), null ); - findAndReplaceSimpleElement( innerCount, root, "comments", value.getComments(), null ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + findAndReplaceSimpleElement(innerCount, root, "distribution", value.getDistribution(), null); + findAndReplaceSimpleElement(innerCount, root, "comments", value.getComments(), null); } /** @@ -1581,16 +1369,15 @@ protected void updateLicense( License value, String xmlTag, Counter counter, Ele * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateMailingList( MailingList value, String xmlTag, Counter counter, Element element ) - { + protected void updateMailingList(MailingList value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "subscribe", value.getSubscribe(), null ); - findAndReplaceSimpleElement( innerCount, root, "unsubscribe", value.getUnsubscribe(), null ); - findAndReplaceSimpleElement( innerCount, root, "post", value.getPost(), null ); - findAndReplaceSimpleElement( innerCount, root, "archive", value.getArchive(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getOtherArchives(), "otherArchives", "otherArchive" ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "subscribe", value.getSubscribe(), null); + findAndReplaceSimpleElement(innerCount, root, "unsubscribe", value.getUnsubscribe(), null); + findAndReplaceSimpleElement(innerCount, root, "post", value.getPost(), null); + findAndReplaceSimpleElement(innerCount, root, "archive", value.getArchive(), null); + findAndReplaceSimpleLists(innerCount, root, value.getOtherArchives(), "otherArchives", "otherArchive"); } /** @@ -1601,39 +1388,38 @@ protected void updateMailingList( MailingList value, String xmlTag, Counter coun * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateModel( Model value, String xmlTag, Counter counter, Element element ) - { + protected void updateModel(Model value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - updateParent( value.getParent(), "parent", innerCount, root ); - findAndReplaceSimpleElement( innerCount, root, "modelVersion", value.getModelVersion(), null ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), null ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "packaging", value.getPackaging(), "jar" ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); - findAndReplaceSimpleElement( innerCount, root, "description", value.getDescription(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - updatePrerequisites( value.getPrerequisites(), "prerequisites", innerCount, root ); - updateIssueManagement( value.getIssueManagement(), "issueManagement", innerCount, root ); - updateCiManagement( value.getCiManagement(), "ciManagement", innerCount, root ); - findAndReplaceSimpleElement( innerCount, root, "inceptionYear", value.getInceptionYear(), null ); - iterateMailingList( innerCount, root, value.getMailingLists(), "mailingLists", "mailingList" ); - iterateDeveloper( innerCount, root, value.getDevelopers(), "developers", "developer" ); - iterateContributor( innerCount, root, value.getContributors(), "contributors", "contributor" ); - iterateLicense( innerCount, root, value.getLicenses(), "licenses", "license" ); - updateScm( value.getScm(), "scm", innerCount, root ); - updateOrganization( value.getOrganization(), "organization", innerCount, root ); - updateBuild( value.getBuild(), "build", innerCount, root ); - iterateProfile( innerCount, root, value.getProfiles(), "profiles", "profile" ); - findAndReplaceSimpleLists( innerCount, root, value.getModules(), "modules", "module" ); - iterateRepository( innerCount, root, value.getRepositories(), "repositories", "repository" ); - iterateRepository( innerCount, root, value.getPluginRepositories(), "pluginRepositories", "pluginRepository" ); - iterateDependency( innerCount, root, value.getDependencies(), "dependencies", "dependency" ); - updateReporting( value.getReporting(), "reporting", innerCount, root ); - updateDependencyManagement( value.getDependencyManagement(), "dependencyManagement", innerCount, root ); - updateDistributionManagement( value.getDistributionManagement(), "distributionManagement", innerCount, root ); - findAndReplaceProperties( innerCount, root, "properties", value.getProperties() ); + Counter innerCount = new Counter(counter.getDepth() + 1); + updateParent(value.getParent(), "parent", innerCount, root); + findAndReplaceSimpleElement(innerCount, root, "modelVersion", value.getModelVersion(), null); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), null); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "packaging", value.getPackaging(), "jar"); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); + findAndReplaceSimpleElement(innerCount, root, "description", value.getDescription(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + updatePrerequisites(value.getPrerequisites(), "prerequisites", innerCount, root); + updateIssueManagement(value.getIssueManagement(), "issueManagement", innerCount, root); + updateCiManagement(value.getCiManagement(), "ciManagement", innerCount, root); + findAndReplaceSimpleElement(innerCount, root, "inceptionYear", value.getInceptionYear(), null); + iterateMailingList(innerCount, root, value.getMailingLists(), "mailingLists", "mailingList"); + iterateDeveloper(innerCount, root, value.getDevelopers(), "developers", "developer"); + iterateContributor(innerCount, root, value.getContributors(), "contributors", "contributor"); + iterateLicense(innerCount, root, value.getLicenses(), "licenses", "license"); + updateScm(value.getScm(), "scm", innerCount, root); + updateOrganization(value.getOrganization(), "organization", innerCount, root); + updateBuild(value.getBuild(), "build", innerCount, root); + iterateProfile(innerCount, root, value.getProfiles(), "profiles", "profile"); + findAndReplaceSimpleLists(innerCount, root, value.getModules(), "modules", "module"); + iterateRepository(innerCount, root, value.getRepositories(), "repositories", "repository"); + iterateRepository(innerCount, root, value.getPluginRepositories(), "pluginRepositories", "pluginRepository"); + iterateDependency(innerCount, root, value.getDependencies(), "dependencies", "dependency"); + updateReporting(value.getReporting(), "reporting", innerCount, root); + updateDependencyManagement(value.getDependencyManagement(), "dependencyManagement", innerCount, root); + updateDistributionManagement(value.getDistributionManagement(), "distributionManagement", innerCount, root); + findAndReplaceProperties(innerCount, root, "properties", value.getProperties()); } /** @@ -1644,26 +1430,24 @@ protected void updateModel( Model value, String xmlTag, Counter counter, Element * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - //CHECKSTYLE_OFF: LineLength - protected void updateModelBase( ModelBase value, String xmlTag, Counter counter, Element element ) - { + // CHECKSTYLE_OFF: LineLength + protected void updateModelBase(ModelBase value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleLists( innerCount, root, value.getModules(), "modules", "module" ); - iterateRepository( innerCount, root, value.getRepositories(), "repositories", "repository" ); - iterateRepository( innerCount, root, value.getPluginRepositories(), "pluginRepositories", - "pluginRepository" ); - iterateDependency( innerCount, root, value.getDependencies(), "dependencies", "dependency" ); - updateReporting( value.getReporting(), "reporting", innerCount, root ); - updateDependencyManagement( value.getDependencyManagement(), "dependencyManagement", innerCount, root ); - updateDistributionManagement( value.getDistributionManagement(), "distributionManagement", innerCount, root ); - findAndReplaceProperties( innerCount, root, "properties", value.getProperties() ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleLists(innerCount, root, value.getModules(), "modules", "module"); + iterateRepository(innerCount, root, value.getRepositories(), "repositories", "repository"); + iterateRepository( + innerCount, root, value.getPluginRepositories(), "pluginRepositories", "pluginRepository"); + iterateDependency(innerCount, root, value.getDependencies(), "dependencies", "dependency"); + updateReporting(value.getReporting(), "reporting", innerCount, root); + updateDependencyManagement(value.getDependencyManagement(), "dependencyManagement", innerCount, root); + updateDistributionManagement(value.getDistributionManagement(), "distributionManagement", innerCount, root); + findAndReplaceProperties(innerCount, root, "properties", value.getProperties()); } } - //CHECKSTYLE_ON: LineLength + // CHECKSTYLE_ON: LineLength /** * Method updateNotifier @@ -1673,24 +1457,39 @@ protected void updateModelBase( ModelBase value, String xmlTag, Counter counter, * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - //CHECKSTYLE_OFF: LineLength - protected void updateNotifier( Notifier value, String xmlTag, Counter counter, Element element ) - { + // CHECKSTYLE_OFF: LineLength + protected void updateNotifier(Notifier value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "type", value.getType(), "mail" ); - findAndReplaceSimpleElement( innerCount, root, "sendOnError", - value.isSendOnError() ? null : String.valueOf( value.isSendOnError() ), "true" ); - findAndReplaceSimpleElement( innerCount, root, "sendOnFailure", - value.isSendOnFailure() ? null : String.valueOf( value.isSendOnFailure() ), "true" ); - findAndReplaceSimpleElement( innerCount, root, "sendOnSuccess", - value.isSendOnSuccess() ? null : String.valueOf( value.isSendOnSuccess() ), "true" ); - findAndReplaceSimpleElement( innerCount, root, "sendOnWarning", - value.isSendOnWarning() ? null : String.valueOf( value.isSendOnWarning() ), "true" ); - findAndReplaceSimpleElement( innerCount, root, "address", value.getAddress(), null ); - findAndReplaceProperties( innerCount, root, "configuration", value.getConfiguration() ); - } - //CHECKSTYLE_ON: LineLength + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "type", value.getType(), "mail"); + findAndReplaceSimpleElement( + innerCount, + root, + "sendOnError", + value.isSendOnError() ? null : String.valueOf(value.isSendOnError()), + "true"); + findAndReplaceSimpleElement( + innerCount, + root, + "sendOnFailure", + value.isSendOnFailure() ? null : String.valueOf(value.isSendOnFailure()), + "true"); + findAndReplaceSimpleElement( + innerCount, + root, + "sendOnSuccess", + value.isSendOnSuccess() ? null : String.valueOf(value.isSendOnSuccess()), + "true"); + findAndReplaceSimpleElement( + innerCount, + root, + "sendOnWarning", + value.isSendOnWarning() ? null : String.valueOf(value.isSendOnWarning()), + "true"); + findAndReplaceSimpleElement(innerCount, root, "address", value.getAddress(), null); + findAndReplaceProperties(innerCount, root, "configuration", value.getConfiguration()); + } + // CHECKSTYLE_ON: LineLength /** * Method updateOrganization @@ -1700,15 +1499,13 @@ protected void updateNotifier( Notifier value, String xmlTag, Counter counter, E * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateOrganization( Organization value, String xmlTag, Counter counter, Element element ) - { + protected void updateOrganization(Organization value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); } } @@ -1720,17 +1517,15 @@ protected void updateOrganization( Organization value, String xmlTag, Counter co * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateParent( Parent value, String xmlTag, Counter counter, Element element ) - { + protected void updateParent(Parent value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); - findAndReplaceSimpleElement( innerCount, root, "relativePath", value.getRelativePath(), "../pom.xml" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); + findAndReplaceSimpleElement(innerCount, root, "relativePath", value.getRelativePath(), "../pom.xml"); } } @@ -1742,15 +1537,13 @@ protected void updateParent( Parent value, String xmlTag, Counter counter, Eleme * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updatePatternSet( PatternSet value, String xmlTag, Counter counter, Element element ) - { + protected void updatePatternSet(PatternSet value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleLists( innerCount, root, value.getIncludes(), "includes", "include" ); - findAndReplaceSimpleLists( innerCount, root, value.getExcludes(), "excludes", "exclude" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleLists(innerCount, root, value.getIncludes(), "includes", "include"); + findAndReplaceSimpleLists(innerCount, root, value.getExcludes(), "excludes", "exclude"); } } @@ -1762,19 +1555,22 @@ protected void updatePatternSet( PatternSet value, String xmlTag, Counter counte * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updatePlugin( Plugin value, String xmlTag, Counter counter, Element element ) - { + protected void updatePlugin(Plugin value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), "org.apache.maven.plugins" ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); - findAndReplaceSimpleElement( innerCount, root, "extensions", - !value.isExtensions() ? null : String.valueOf( value.isExtensions() ), "false" ); - iteratePluginExecution( innerCount, root, value.getExecutions(), "executions", "execution" ); - iterateDependency( innerCount, root, value.getDependencies(), "dependencies", "dependency" ); - findAndReplaceSimpleElement( innerCount, root, "inherited", value.getInherited(), null ); - findAndReplaceXpp3DOM( innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration() ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), "org.apache.maven.plugins"); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); + findAndReplaceSimpleElement( + innerCount, + root, + "extensions", + !value.isExtensions() ? null : String.valueOf(value.isExtensions()), + "false"); + iteratePluginExecution(innerCount, root, value.getExecutions(), "executions", "execution"); + iterateDependency(innerCount, root, value.getDependencies(), "dependencies", "dependency"); + findAndReplaceSimpleElement(innerCount, root, "inherited", value.getInherited(), null); + findAndReplaceXpp3DOM(innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration()); } /** @@ -1785,19 +1581,18 @@ protected void updatePlugin( Plugin value, String xmlTag, Counter counter, Eleme * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - //CHECKSTYLE_OFF: LineLength - protected void updatePluginConfiguration( PluginConfiguration value, String xmlTag, Counter counter, Element element ) - { + // CHECKSTYLE_OFF: LineLength + protected void updatePluginConfiguration( + PluginConfiguration value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - updatePluginManagement( value.getPluginManagement(), "pluginManagement", innerCount, root ); - iteratePlugin( innerCount, root, value.getPlugins(), "plugins", "plugin" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + updatePluginManagement(value.getPluginManagement(), "pluginManagement", innerCount, root); + iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); } } - //CHECKSTYLE_ON: LineLength + // CHECKSTYLE_ON: LineLength /** * Method updatePluginContainer @@ -1807,14 +1602,12 @@ protected void updatePluginConfiguration( PluginConfiguration value, String xmlT * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updatePluginContainer( PluginContainer value, String xmlTag, Counter counter, Element element ) - { + protected void updatePluginContainer(PluginContainer value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - iteratePlugin( innerCount, root, value.getPlugins(), "plugins", "plugin" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); } } @@ -1826,15 +1619,14 @@ protected void updatePluginContainer( PluginContainer value, String xmlTag, Coun * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updatePluginExecution( PluginExecution value, String xmlTag, Counter counter, Element element ) - { + protected void updatePluginExecution(PluginExecution value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), "default" ); - findAndReplaceSimpleElement( innerCount, root, "phase", value.getPhase(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getGoals(), "goals", "goal" ); - findAndReplaceSimpleElement( innerCount, root, "inherited", value.getInherited(), null ); - findAndReplaceXpp3DOM( innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration() ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), "default"); + findAndReplaceSimpleElement(innerCount, root, "phase", value.getPhase(), null); + findAndReplaceSimpleLists(innerCount, root, value.getGoals(), "goals", "goal"); + findAndReplaceSimpleElement(innerCount, root, "inherited", value.getInherited(), null); + findAndReplaceXpp3DOM(innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration()); } /** @@ -1845,14 +1637,12 @@ protected void updatePluginExecution( PluginExecution value, String xmlTag, Coun * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updatePluginManagement( PluginManagement value, String xmlTag, Counter counter, Element element ) - { + protected void updatePluginManagement(PluginManagement value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - iteratePlugin( innerCount, root, value.getPlugins(), "plugins", "plugin" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); } } @@ -1864,14 +1654,12 @@ protected void updatePluginManagement( PluginManagement value, String xmlTag, Co * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updatePrerequisites( Prerequisites value, String xmlTag, Counter counter, Element element ) - { + protected void updatePrerequisites(Prerequisites value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "maven", value.getMaven(), "2.0" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "maven", value.getMaven(), "2.0"); } } @@ -1883,21 +1671,20 @@ protected void updatePrerequisites( Prerequisites value, String xmlTag, Counter * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateProfile( Profile value, String xmlTag, Counter counter, Element element ) - { + protected void updateProfile(Profile value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), "default" ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), "default"); // updateActivation( value.getActivation(), "activation", innerCount, root); - updateBuildBase( value.getBuild(), "build", innerCount, root ); - findAndReplaceSimpleLists( innerCount, root, value.getModules(), "modules", "module" ); - iterateRepository( innerCount, root, value.getRepositories(), "repositories", "repository" ); - iterateRepository( innerCount, root, value.getPluginRepositories(), "pluginRepositories", "pluginRepository" ); - iterateDependency( innerCount, root, value.getDependencies(), "dependencies", "dependency" ); - updateReporting( value.getReporting(), "reporting", innerCount, root ); - updateDependencyManagement( value.getDependencyManagement(), "dependencyManagement", innerCount, root ); - updateDistributionManagement( value.getDistributionManagement(), "distributionManagement", innerCount, root ); - findAndReplaceProperties( innerCount, root, "properties", value.getProperties() ); + updateBuildBase(value.getBuild(), "build", innerCount, root); + findAndReplaceSimpleLists(innerCount, root, value.getModules(), "modules", "module"); + iterateRepository(innerCount, root, value.getRepositories(), "repositories", "repository"); + iterateRepository(innerCount, root, value.getPluginRepositories(), "pluginRepositories", "pluginRepository"); + iterateDependency(innerCount, root, value.getDependencies(), "dependencies", "dependency"); + updateReporting(value.getReporting(), "reporting", innerCount, root); + updateDependencyManagement(value.getDependencyManagement(), "dependencyManagement", innerCount, root); + updateDistributionManagement(value.getDistributionManagement(), "distributionManagement", innerCount, root); + findAndReplaceProperties(innerCount, root, "properties", value.getProperties()); } /** @@ -1908,17 +1695,15 @@ protected void updateProfile( Profile value, String xmlTag, Counter counter, Ele * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateRelocation( Relocation value, String xmlTag, Counter counter, Element element ) - { + protected void updateRelocation(Relocation value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), null ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); - findAndReplaceSimpleElement( innerCount, root, "message", value.getMessage(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), null); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); + findAndReplaceSimpleElement(innerCount, root, "message", value.getMessage(), null); } } @@ -1930,16 +1715,15 @@ protected void updateRelocation( Relocation value, String xmlTag, Counter counte * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateReportPlugin( ReportPlugin value, String xmlTag, Counter counter, Element element ) - { + protected void updateReportPlugin(ReportPlugin value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "groupId", value.getGroupId(), "org.apache.maven.plugins" ); - findAndReplaceSimpleElement( innerCount, root, "artifactId", value.getArtifactId(), null ); - findAndReplaceSimpleElement( innerCount, root, "version", value.getVersion(), null ); - findAndReplaceSimpleElement( innerCount, root, "inherited", value.getInherited(), null ); - findAndReplaceXpp3DOM( innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration() ); - iterateReportSet( innerCount, root, value.getReportSets(), "reportSets", "reportSet" ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "groupId", value.getGroupId(), "org.apache.maven.plugins"); + findAndReplaceSimpleElement(innerCount, root, "artifactId", value.getArtifactId(), null); + findAndReplaceSimpleElement(innerCount, root, "version", value.getVersion(), null); + findAndReplaceSimpleElement(innerCount, root, "inherited", value.getInherited(), null); + findAndReplaceXpp3DOM(innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration()); + iterateReportSet(innerCount, root, value.getReportSets(), "reportSets", "reportSet"); } /** @@ -1950,14 +1734,13 @@ protected void updateReportPlugin( ReportPlugin value, String xmlTag, Counter co * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateReportSet( ReportSet value, String xmlTag, Counter counter, Element element ) - { + protected void updateReportSet(ReportSet value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), "default" ); - findAndReplaceXpp3DOM( innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration() ); - findAndReplaceSimpleElement( innerCount, root, "inherited", value.getInherited(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getReports(), "reports", "report" ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), "default"); + findAndReplaceXpp3DOM(innerCount, root, "configuration", (Xpp3Dom) value.getConfiguration()); + findAndReplaceSimpleElement(innerCount, root, "inherited", value.getInherited(), null); + findAndReplaceSimpleLists(innerCount, root, value.getReports(), "reports", "report"); } /** @@ -1968,17 +1751,19 @@ protected void updateReportSet( ReportSet value, String xmlTag, Counter counter, * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateReporting( Reporting value, String xmlTag, Counter counter, Element element ) - { + protected void updateReporting(Reporting value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "excludeDefaults", !value.isExcludeDefaults() ? null - : String.valueOf( value.isExcludeDefaults() ), "false" ); - findAndReplaceSimpleElement( innerCount, root, "outputDirectory", value.getOutputDirectory(), null ); - iterateReportPlugin( innerCount, root, value.getPlugins(), "plugins", "plugin" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement( + innerCount, + root, + "excludeDefaults", + !value.isExcludeDefaults() ? null : String.valueOf(value.isExcludeDefaults()), + "false"); + findAndReplaceSimpleElement(innerCount, root, "outputDirectory", value.getOutputDirectory(), null); + iterateReportPlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); } } @@ -1990,16 +1775,15 @@ protected void updateReporting( Reporting value, String xmlTag, Counter counter, * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateRepository( Repository value, String xmlTag, Counter counter, Element element ) - { + protected void updateRepository(Repository value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - updateRepositoryPolicy( value.getReleases(), "releases", innerCount, root ); - updateRepositoryPolicy( value.getSnapshots(), "snapshots", innerCount, root ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), null ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - findAndReplaceSimpleElement( innerCount, root, "layout", value.getLayout(), "default" ); + Counter innerCount = new Counter(counter.getDepth() + 1); + updateRepositoryPolicy(value.getReleases(), "releases", innerCount, root); + updateRepositoryPolicy(value.getSnapshots(), "snapshots", innerCount, root); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + findAndReplaceSimpleElement(innerCount, root, "layout", value.getLayout(), "default"); } /** @@ -2010,17 +1794,15 @@ protected void updateRepository( Repository value, String xmlTag, Counter counte * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateRepositoryBase( RepositoryBase value, String xmlTag, Counter counter, Element element ) - { + protected void updateRepositoryBase(RepositoryBase value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), null ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - findAndReplaceSimpleElement( innerCount, root, "layout", value.getLayout(), "default" ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + findAndReplaceSimpleElement(innerCount, root, "layout", value.getLayout(), "default"); } } @@ -2032,17 +1814,15 @@ protected void updateRepositoryBase( RepositoryBase value, String xmlTag, Counte * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateRepositoryPolicy( RepositoryPolicy value, String xmlTag, Counter counter, Element element ) - { + protected void updateRepositoryPolicy(RepositoryPolicy value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "enabled", - value.isEnabled() ? null : String.valueOf( value.isEnabled() ), "true" ); - findAndReplaceSimpleElement( innerCount, root, "updatePolicy", value.getUpdatePolicy(), null ); - findAndReplaceSimpleElement( innerCount, root, "checksumPolicy", value.getChecksumPolicy(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement( + innerCount, root, "enabled", value.isEnabled() ? null : String.valueOf(value.isEnabled()), "true"); + findAndReplaceSimpleElement(innerCount, root, "updatePolicy", value.getUpdatePolicy(), null); + findAndReplaceSimpleElement(innerCount, root, "checksumPolicy", value.getChecksumPolicy(), null); } } @@ -2054,16 +1834,19 @@ protected void updateRepositoryPolicy( RepositoryPolicy value, String xmlTag, Co * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateResource( Resource value, String xmlTag, Counter counter, Element element ) - { + protected void updateResource(Resource value, String xmlTag, Counter counter, Element element) { Element root = element; - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "targetPath", value.getTargetPath(), null ); - findAndReplaceSimpleElement( innerCount, root, "filtering", - !value.isFiltering() ? null : String.valueOf( value.isFiltering() ), "false" ); - findAndReplaceSimpleElement( innerCount, root, "directory", value.getDirectory(), null ); - findAndReplaceSimpleLists( innerCount, root, value.getIncludes(), "includes", "include" ); - findAndReplaceSimpleLists( innerCount, root, value.getExcludes(), "excludes", "exclude" ); + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "targetPath", value.getTargetPath(), null); + findAndReplaceSimpleElement( + innerCount, + root, + "filtering", + !value.isFiltering() ? null : String.valueOf(value.isFiltering()), + "false"); + findAndReplaceSimpleElement(innerCount, root, "directory", value.getDirectory(), null); + findAndReplaceSimpleLists(innerCount, root, value.getIncludes(), "includes", "include"); + findAndReplaceSimpleLists(innerCount, root, value.getExcludes(), "excludes", "exclude"); } /** @@ -2074,21 +1857,19 @@ protected void updateResource( Resource value, String xmlTag, Counter counter, E * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateScm( Scm value, String xmlTag, Counter counter, Element element ) - { + protected void updateScm(Scm value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - //CHECKSTYLE_OFF: LineLength - - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "connection", value.getConnection(), null ); - findAndReplaceSimpleElement( innerCount, root, "developerConnection", value.getDeveloperConnection(), null ); - findAndReplaceSimpleElement( innerCount, root, "tag", value.getTag(), "HEAD" ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); - - //CHECKSTYLE_ON: LineLength + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + // CHECKSTYLE_OFF: LineLength + + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "connection", value.getConnection(), null); + findAndReplaceSimpleElement(innerCount, root, "developerConnection", value.getDeveloperConnection(), null); + findAndReplaceSimpleElement(innerCount, root, "tag", value.getTag(), "HEAD"); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); + + // CHECKSTYLE_ON: LineLength } } @@ -2100,16 +1881,14 @@ protected void updateScm( Scm value, String xmlTag, Counter counter, Element ele * @param counter {@link Counter} * @param xmlTag The XMLTag. */ - protected void updateSite( Site value, String xmlTag, Counter counter, Element element ) - { + protected void updateSite(Site value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; - Element root = updateElement( counter, element, xmlTag, shouldExist ); - if ( shouldExist ) - { - Counter innerCount = new Counter( counter.getDepth() + 1 ); - findAndReplaceSimpleElement( innerCount, root, "id", value.getId(), null ); - findAndReplaceSimpleElement( innerCount, root, "name", value.getName(), null ); - findAndReplaceSimpleElement( innerCount, root, "url", value.getUrl(), null ); + Element root = updateElement(counter, element, xmlTag, shouldExist); + if (shouldExist) { + Counter innerCount = new Counter(counter.getDepth() + 1); + findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); + findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); + findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); } } @@ -2122,15 +1901,13 @@ protected void updateSite( Site value, String xmlTag, Counter counter, Element e * @deprecated * @throws IOException in case of an error. */ - public void write( Model project, Document document, OutputStream stream ) - throws IOException - { - updateModel( project, "project", new Counter( 0 ), document.getRootElement() ); + public void write(Model project, Document document, OutputStream stream) throws IOException { + updateModel(project, "project", new Counter(0), document.getRootElement()); XMLOutputter outputter = new XMLOutputter(); Format format = Format.getPrettyFormat(); - format.setIndent( " " ).setLineSeparator( lineSeparator ); - outputter.setFormat( format ); - outputter.output( document, stream ); + format.setIndent(" ").setLineSeparator(lineSeparator); + outputter.setFormat(format); + outputter.output(document, stream); } /** @@ -2141,12 +1918,10 @@ public void write( Model project, Document document, OutputStream stream ) * @param document {@link Document} * @throws IOException in case of an error. */ - public void write( Model project, Document document, OutputStreamWriter writer ) - throws IOException - { + public void write(Model project, Document document, OutputStreamWriter writer) throws IOException { Format format = Format.getRawFormat(); - format.setEncoding( writer.getEncoding() ).setLineSeparator( lineSeparator ); - write( project, document, writer, format ); + format.setEncoding(writer.getEncoding()).setLineSeparator(lineSeparator); + write(project, document, writer, format); } /** @@ -2158,13 +1933,10 @@ public void write( Model project, Document document, OutputStreamWriter writer ) * @param document {@link Document} * @throws IOException in case of an error. */ - public void write( Model project, Document document, Writer writer, Format jdomFormat ) - throws IOException - { - updateModel( project, "project", new Counter( 0 ), document.getRootElement() ); + public void write(Model project, Document document, Writer writer, Format jdomFormat) throws IOException { + updateModel(project, "project", new Counter(0), document.getRootElement()); XMLOutputter outputter = new XMLOutputter(); - outputter.setFormat( jdomFormat ); - outputter.output( document, writer ); + outputter.setFormat(jdomFormat); + outputter.output(document, writer); } - } diff --git a/src/main/java/org/apache/maven/plugins/shade/pom/PomWriter.java b/src/main/java/org/apache/maven/plugins/shade/pom/PomWriter.java index 90dbaf50..14001c24 100644 --- a/src/main/java/org/apache/maven/plugins/shade/pom/PomWriter.java +++ b/src/main/java/org/apache/maven/plugins/shade/pom/PomWriter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.pom; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.pom; import java.io.IOException; import java.io.Writer; @@ -31,47 +30,42 @@ /** * @author Jason van Zyl */ -public class PomWriter -{ - public static void write( Writer w, Model newModel ) - throws IOException - { - write( w, newModel, false ); +public class PomWriter { + public static void write(Writer w, Model newModel) throws IOException { + write(w, newModel, false); } - public static void write( Writer w, Model newModel, boolean namespaceDeclaration ) - throws IOException - { - Element root = new Element( "project" ); + public static void write(Writer w, Model newModel, boolean namespaceDeclaration) throws IOException { + Element root = new Element("project"); - if ( namespaceDeclaration ) - { + if (namespaceDeclaration) { String modelVersion = newModel.getModelVersion(); - Namespace pomNamespace = Namespace.getNamespace( "", "http://maven.apache.org/POM/" + modelVersion ); + Namespace pomNamespace = Namespace.getNamespace("", "http://maven.apache.org/POM/" + modelVersion); - root.setNamespace( pomNamespace ); + root.setNamespace(pomNamespace); - Namespace xsiNamespace = Namespace.getNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + Namespace xsiNamespace = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); - root.addNamespaceDeclaration( xsiNamespace ); + root.addNamespaceDeclaration(xsiNamespace); - if ( root.getAttribute( "schemaLocation", xsiNamespace ) == null ) - { - root.setAttribute( "schemaLocation", - "http://maven.apache.org/POM/" + modelVersion + " http://maven.apache.org/maven-v" - + modelVersion.replace( '.', '_' ) + ".xsd", xsiNamespace ); + if (root.getAttribute("schemaLocation", xsiNamespace) == null) { + root.setAttribute( + "schemaLocation", + "http://maven.apache.org/POM/" + modelVersion + " http://maven.apache.org/maven-v" + + modelVersion.replace('.', '_') + ".xsd", + xsiNamespace); } } - Document doc = new Document( root ); + Document doc = new Document(root); MavenJDOMWriter writer = new MavenJDOMWriter(); String encoding = newModel.getModelEncoding() != null ? newModel.getModelEncoding() : "UTF-8"; - Format format = Format.getPrettyFormat().setEncoding( encoding ); + Format format = Format.getPrettyFormat().setEncoding(encoding); - writer.write( newModel, doc, w, format ); + writer.write(newModel, doc, w, format); } } diff --git a/src/main/java/org/apache/maven/plugins/shade/relocation/Relocator.java b/src/main/java/org/apache/maven/plugins/shade/relocation/Relocator.java index c9420ca5..d3027c4d 100644 --- a/src/main/java/org/apache/maven/plugins/shade/relocation/Relocator.java +++ b/src/main/java/org/apache/maven/plugins/shade/relocation/Relocator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.relocation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.relocation; /** @author Jason van Zyl */ -public interface Relocator -{ +public interface Relocator { String ROLE = Relocator.class.getName(); - boolean canRelocatePath( String clazz ); + boolean canRelocatePath(String clazz); + + String relocatePath(String clazz); - String relocatePath( String clazz ); + boolean canRelocateClass(String clazz); - boolean canRelocateClass( String clazz ); + String relocateClass(String clazz); - String relocateClass( String clazz ); - - String applyToSourceContent( String sourceContent ); + String applyToSourceContent(String sourceContent); } diff --git a/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java b/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java index df51ea24..ad8af632 100644 --- a/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java +++ b/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.relocation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.codehaus.plexus.util.SelectorUtils; +package org.apache.maven.plugins.shade.relocation; import java.util.Collection; import java.util.LinkedHashSet; @@ -27,17 +24,17 @@ import java.util.Set; import java.util.regex.Pattern; +import org.codehaus.plexus.util.SelectorUtils; + /** * @author Jason van Zyl * @author Mauro Talevi */ -public class SimpleRelocator - implements Relocator -{ +public class SimpleRelocator implements Relocator { /** * Match dot, slash or space at end of string */ - private static final Pattern RX_ENDS_WITH_DOT_SLASH_SPACE = Pattern.compile( "[./ ]$" ); + private static final Pattern RX_ENDS_WITH_DOT_SLASH_SPACE = Pattern.compile("[./ ]$"); /** * Match
    @@ -46,11 +43,10 @@ public class SimpleRelocator *
* at end of string */ - private static final Pattern RX_ENDS_WITH_JAVA_KEYWORD = Pattern.compile( - "\\b(import|package|public|protected|private|static|final|synchronized|abstract|volatile) $" - + "|" - + "\\{@link( \\*)* $" - ); + private static final Pattern RX_ENDS_WITH_JAVA_KEYWORD = + Pattern.compile("\\b(import|package|public|protected|private|static|final|synchronized|abstract|volatile) $" + + "|" + + "\\{@link( \\*)* $"); private final String pattern; @@ -70,99 +66,80 @@ public class SimpleRelocator private final boolean rawString; - public SimpleRelocator( String patt, String shadedPattern, List includes, List excludes ) - { - this( patt, shadedPattern, includes, excludes, false ); + public SimpleRelocator(String patt, String shadedPattern, List includes, List excludes) { + this(patt, shadedPattern, includes, excludes, false); } - public SimpleRelocator( String patt, String shadedPattern, List includes, List excludes, - boolean rawString ) - { + public SimpleRelocator( + String patt, String shadedPattern, List includes, List excludes, boolean rawString) { this.rawString = rawString; - if ( rawString ) - { + if (rawString) { this.pathPattern = patt; this.shadedPathPattern = shadedPattern; this.pattern = null; // not used for raw string relocator this.shadedPattern = null; // not used for raw string relocator - } - else - { - if ( patt == null ) - { + } else { + if (patt == null) { this.pattern = ""; this.pathPattern = ""; - } - else - { - this.pattern = patt.replace( '/', '.' ); - this.pathPattern = patt.replace( '.', '/' ); + } else { + this.pattern = patt.replace('/', '.'); + this.pathPattern = patt.replace('.', '/'); } - if ( shadedPattern != null ) - { - this.shadedPattern = shadedPattern.replace( '/', '.' ); - this.shadedPathPattern = shadedPattern.replace( '.', '/' ); - } - else - { + if (shadedPattern != null) { + this.shadedPattern = shadedPattern.replace('/', '.'); + this.shadedPathPattern = shadedPattern.replace('.', '/'); + } else { this.shadedPattern = "hidden." + this.pattern; this.shadedPathPattern = "hidden/" + this.pathPattern; } } - this.includes = normalizePatterns( includes ); - this.excludes = normalizePatterns( excludes ); + this.includes = normalizePatterns(includes); + this.excludes = normalizePatterns(excludes); // Don't replace all dots to slashes, otherwise /META-INF/maven/${groupId} can't be matched. - if ( includes != null && !includes.isEmpty() ) - { - this.includes.addAll( includes ); + if (includes != null && !includes.isEmpty()) { + this.includes.addAll(includes); } - if ( excludes != null && !excludes.isEmpty() ) - { - this.excludes.addAll( excludes ); + if (excludes != null && !excludes.isEmpty()) { + this.excludes.addAll(excludes); } - if ( !rawString && this.excludes != null ) - { + if (!rawString && this.excludes != null) { // Create exclude pattern sets for sources - for ( String exclude : this.excludes ) - { + for (String exclude : this.excludes) { // Excludes should be subpackages of the global pattern - if ( exclude.startsWith( pattern ) ) - { - sourcePackageExcludes.add( exclude.substring( pattern.length() ).replaceFirst( "[.][*]$", "" ) ); + if (exclude.startsWith(pattern)) { + sourcePackageExcludes.add( + exclude.substring(pattern.length()).replaceFirst("[.][*]$", "")); } // Excludes should be subpackages of the global pattern - if ( exclude.startsWith( pathPattern ) ) - { - sourcePathExcludes.add( exclude.substring( pathPattern.length() ).replaceFirst( "[/][*]$", "" ) ); + if (exclude.startsWith(pathPattern)) { + sourcePathExcludes.add( + exclude.substring(pathPattern.length()).replaceFirst("[/][*]$", "")); } } } } - private static Set normalizePatterns( Collection patterns ) - { + private static Set normalizePatterns(Collection patterns) { Set normalized = null; - if ( patterns != null && !patterns.isEmpty() ) - { + if (patterns != null && !patterns.isEmpty()) { normalized = new LinkedHashSet<>(); - for ( String pattern : patterns ) - { - String classPattern = pattern.replace( '.', '/' ); - normalized.add( classPattern ); + for (String pattern : patterns) { + String classPattern = pattern.replace('.', '/'); + normalized.add(classPattern); // Actually, class patterns should just use 'foo.bar.*' ending with a single asterisk, but some users // mistake them for path patterns like 'my/path/**', so let us be a bit more lenient here. - if ( classPattern.endsWith( "/*" ) || classPattern.endsWith( "/**" ) ) - { - String packagePattern = classPattern.substring( 0, classPattern.lastIndexOf( '/' ) ); - normalized.add( packagePattern ); + if (classPattern.endsWith("/*") || classPattern.endsWith("/**")) { + String packagePattern = classPattern.substring(0, classPattern.lastIndexOf('/')); + normalized.add(packagePattern); } } } @@ -170,14 +147,10 @@ private static Set normalizePatterns( Collection patterns ) return normalized; } - private boolean isIncluded( String path ) - { - if ( includes != null && !includes.isEmpty() ) - { - for ( String include : includes ) - { - if ( SelectorUtils.matchPath( include, path, true ) ) - { + private boolean isIncluded(String path) { + if (includes != null && !includes.isEmpty()) { + for (String include : includes) { + if (SelectorUtils.matchPath(include, path, true)) { return true; } } @@ -186,14 +159,10 @@ private boolean isIncluded( String path ) return true; } - private boolean isExcluded( String path ) - { - if ( excludes != null && !excludes.isEmpty() ) - { - for ( String exclude : excludes ) - { - if ( SelectorUtils.matchPath( exclude, path, true ) ) - { + private boolean isExcluded(String path) { + if (excludes != null && !excludes.isEmpty()) { + for (String exclude : excludes) { + if (SelectorUtils.matchPath(exclude, path, true)) { return true; } } @@ -201,93 +170,80 @@ private boolean isExcluded( String path ) return false; } - public boolean canRelocatePath( String path ) - { - if ( rawString ) - { - return Pattern.compile( pathPattern ).matcher( path ).find(); + public boolean canRelocatePath(String path) { + if (rawString) { + return Pattern.compile(pathPattern).matcher(path).find(); } - if ( path.endsWith( ".class" ) ) - { - path = path.substring( 0, path.length() - 6 ); + if (path.endsWith(".class")) { + path = path.substring(0, path.length() - 6); } // Allow for annoying option of an extra / on the front of a path. See MSHADE-119; comes from // getClass().getResource("/a/b/c.properties"). - if ( !path.isEmpty() && path.charAt( 0 ) == '/' ) - { - path = path.substring( 1 ); + if (!path.isEmpty() && path.charAt(0) == '/') { + path = path.substring(1); } - return isIncluded( path ) && !isExcluded( path ) && path.startsWith( pathPattern ); + return isIncluded(path) && !isExcluded(path) && path.startsWith(pathPattern); } - public boolean canRelocateClass( String clazz ) - { - return !rawString && clazz.indexOf( '/' ) < 0 && canRelocatePath( clazz.replace( '.', '/' ) ); + public boolean canRelocateClass(String clazz) { + return !rawString && clazz.indexOf('/') < 0 && canRelocatePath(clazz.replace('.', '/')); } - public String relocatePath( String path ) - { - if ( rawString ) - { - return path.replaceAll( pathPattern, shadedPathPattern ); - } - else - { - return path.replaceFirst( pathPattern, shadedPathPattern ); + public String relocatePath(String path) { + if (rawString) { + return path.replaceAll(pathPattern, shadedPathPattern); + } else { + return path.replaceFirst(pathPattern, shadedPathPattern); } } - public String relocateClass( String clazz ) - { - return rawString ? clazz : clazz.replaceFirst( pattern, shadedPattern ); + public String relocateClass(String clazz) { + return rawString ? clazz : clazz.replaceFirst(pattern, shadedPattern); } - public String applyToSourceContent( String sourceContent ) - { - if ( rawString ) - { + public String applyToSourceContent(String sourceContent) { + if (rawString) { return sourceContent; } - sourceContent = shadeSourceWithExcludes( sourceContent, pattern, shadedPattern, sourcePackageExcludes ); - return shadeSourceWithExcludes( sourceContent, pathPattern, shadedPathPattern, sourcePathExcludes ); + sourceContent = shadeSourceWithExcludes(sourceContent, pattern, shadedPattern, sourcePackageExcludes); + return shadeSourceWithExcludes(sourceContent, pathPattern, shadedPathPattern, sourcePathExcludes); } - private String shadeSourceWithExcludes( String sourceContent, String patternFrom, String patternTo, - Set excludedPatterns ) - { + private String shadeSourceWithExcludes( + String sourceContent, String patternFrom, String patternTo, Set excludedPatterns) { // Usually shading makes package names a bit longer, so make buffer 10% bigger than original source - StringBuilder shadedSourceContent = new StringBuilder( sourceContent.length() * 11 / 10 ); + StringBuilder shadedSourceContent = new StringBuilder(sourceContent.length() * 11 / 10); boolean isFirstSnippet = true; // Make sure that search pattern starts at word boundary and we look for literal ".", not regex jokers - String[] snippets = sourceContent.split( "\\b" + patternFrom.replace( ".", "[.]" ) + "\\b" ); - for ( int i = 0, snippetsLength = snippets.length; i < snippetsLength; i++ ) - { + String[] snippets = sourceContent.split("\\b" + patternFrom.replace(".", "[.]") + "\\b"); + for (int i = 0, snippetsLength = snippets.length; i < snippetsLength; i++) { String snippet = snippets[i]; String previousSnippet = isFirstSnippet ? "" : snippets[i - 1]; boolean doExclude = false; - for ( String excludedPattern : excludedPatterns ) - { - if ( snippet.startsWith( excludedPattern ) ) - { + for (String excludedPattern : excludedPatterns) { + if (snippet.startsWith(excludedPattern)) { doExclude = true; break; } } - if ( isFirstSnippet ) - { - shadedSourceContent.append( snippet ); + if (isFirstSnippet) { + shadedSourceContent.append(snippet); isFirstSnippet = false; - } - else - { - String previousSnippetOneLine = previousSnippet.replaceAll( "\\s+", " " ); - boolean afterDotSlashSpace = RX_ENDS_WITH_DOT_SLASH_SPACE.matcher( previousSnippetOneLine ).find(); - boolean afterJavaKeyWord = RX_ENDS_WITH_JAVA_KEYWORD.matcher( previousSnippetOneLine ).find(); + } else { + String previousSnippetOneLine = previousSnippet.replaceAll("\\s+", " "); + boolean afterDotSlashSpace = RX_ENDS_WITH_DOT_SLASH_SPACE + .matcher(previousSnippetOneLine) + .find(); + boolean afterJavaKeyWord = RX_ENDS_WITH_JAVA_KEYWORD + .matcher(previousSnippetOneLine) + .find(); boolean shouldExclude = doExclude || afterDotSlashSpace && !afterJavaKeyWord; - shadedSourceContent.append( shouldExclude ? patternFrom : patternTo ).append( snippet ); + shadedSourceContent + .append(shouldExclude ? patternFrom : patternTo) + .append(snippet); } } return shadedSourceContent.toString(); diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/AbstractCompatibilityTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/AbstractCompatibilityTransformer.java index 392ddb96..fea63b83 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/AbstractCompatibilityTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/AbstractCompatibilityTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,22 +16,19 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.maven.plugins.shade.relocation.Relocator; + /** * An abstract class to implement once the old non-reproducible ResourceTransformer API. */ -abstract class AbstractCompatibilityTransformer - implements ReproducibleResourceTransformer -{ - public final void processResource( String resource, InputStream is, List relocators ) - throws IOException - { - processResource( resource, is, relocators, 0 ); +abstract class AbstractCompatibilityTransformer implements ReproducibleResourceTransformer { + public final void processResource(String resource, InputStream is, List relocators) throws IOException { + processResource(resource, is, relocators, 0); } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformer.java index 9ae341ab..b14452c4 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; @@ -29,36 +28,29 @@ /** * Prevents duplicate copies of the license */ -public class ApacheLicenseResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class ApacheLicenseResourceTransformer extends AbstractCompatibilityTransformer { private static final String LICENSE_PATH = "META-INF/LICENSE"; private static final String LICENSE_TXT_PATH = "META-INF/LICENSE.txt"; - + private static final String LICENSE_MD_PATH = "META-INF/LICENSE.md"; - public boolean canTransformResource( String resource ) - { - return LICENSE_PATH.equalsIgnoreCase( resource ) - || LICENSE_TXT_PATH.regionMatches( true, 0, resource, 0, LICENSE_TXT_PATH.length() ) - || LICENSE_MD_PATH.regionMatches( true, 0, resource, 0, LICENSE_MD_PATH.length() ); + public boolean canTransformResource(String resource) { + return LICENSE_PATH.equalsIgnoreCase(resource) + || LICENSE_TXT_PATH.regionMatches(true, 0, resource, 0, LICENSE_TXT_PATH.length()) + || LICENSE_MD_PATH.regionMatches(true, 0, resource, 0, LICENSE_MD_PATH.length()); } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { // no op } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return false; } - public void modifyOutputStream( JarOutputStream os ) - throws IOException - { + public void modifyOutputStream(JarOutputStream os) throws IOException { // no op } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformer.java index b7bdc4ca..4b31d329 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; -import org.codehaus.plexus.util.StringUtils; +package org.apache.maven.plugins.shade.resource; import java.io.BufferedReader; import java.io.IOException; @@ -39,12 +35,13 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.codehaus.plexus.util.StringUtils; + /** * Merges META-INF/NOTICE.TXT files. */ -public class ApacheNoticeResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class ApacheNoticeResourceTransformer extends AbstractCompatibilityTransformer { Set entries = new LinkedHashSet<>(); Map> organizationEntries = new LinkedHashMap<>(); @@ -54,14 +51,14 @@ public class ApacheNoticeResourceTransformer boolean addHeader = true; String preamble1 = "// ------------------------------------------------------------------\n" - + "// NOTICE file corresponding to the section 4d of The Apache License,\n" - + "// Version 2.0, in this case for "; + + "// NOTICE file corresponding to the section 4d of The Apache License,\n" + + "// Version 2.0, in this case for "; String preamble2 = "\n// ------------------------------------------------------------------\n"; String preamble3 = "This product includes software developed at\n"; - //defaults overridable via config in pom + // defaults overridable via config in pom String organizationName = "The Apache Software Foundation"; String organizationURL = "http://www.apache.org/"; @@ -80,102 +77,76 @@ public class ApacheNoticeResourceTransformer private static final String NOTICE_PATH = "META-INF/NOTICE"; private static final String NOTICE_TXT_PATH = "META-INF/NOTICE.txt"; - - private static final String NOTICE_MD_PATH = "META-INF/NOTICE.md"; - public boolean canTransformResource( String resource ) - { - return NOTICE_PATH.equalsIgnoreCase( resource ) - || NOTICE_TXT_PATH.equalsIgnoreCase( resource ) - || NOTICE_MD_PATH.equalsIgnoreCase( resource ); + private static final String NOTICE_MD_PATH = "META-INF/NOTICE.md"; + public boolean canTransformResource(String resource) { + return NOTICE_PATH.equalsIgnoreCase(resource) + || NOTICE_TXT_PATH.equalsIgnoreCase(resource) + || NOTICE_MD_PATH.equalsIgnoreCase(resource); } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { - if ( entries.isEmpty() ) - { - String year = new SimpleDateFormat( "yyyy" ).format( new Date() ); - if ( !inceptionYear.equals( year ) ) - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { + if (entries.isEmpty()) { + String year = new SimpleDateFormat("yyyy").format(new Date()); + if (!inceptionYear.equals(year)) { year = inceptionYear + "-" + year; } - //add headers - if ( addHeader ) - { - entries.add( preamble1 + projectName + preamble2 ); - } - else - { - entries.add( "" ); + // add headers + if (addHeader) { + entries.add(preamble1 + projectName + preamble2); + } else { + entries.add(""); } - //fake second entry, we'll look for a real one later - entries.add( projectName + "\nCopyright " + year + " " + organizationName + "\n" ); - entries.add( preamble3 + organizationName + " (" + organizationURL + ").\n" ); + // fake second entry, we'll look for a real one later + entries.add(projectName + "\nCopyright " + year + " " + organizationName + "\n"); + entries.add(preamble3 + organizationName + " (" + organizationURL + ").\n"); } BufferedReader reader; - if ( StringUtils.isNotEmpty( encoding ) ) - { - reader = new BufferedReader( new InputStreamReader( is, encoding ) ); - } - else - { - reader = new BufferedReader( new InputStreamReader( is ) ); + if (StringUtils.isNotEmpty(encoding)) { + reader = new BufferedReader(new InputStreamReader(is, encoding)); + } else { + reader = new BufferedReader(new InputStreamReader(is)); } String line = reader.readLine(); StringBuilder sb = new StringBuilder(); Set currentOrg = null; int lineCount = 0; - while ( line != null ) - { + while (line != null) { String trimedLine = line.trim(); - if ( !trimedLine.startsWith( "//" ) ) - { - if ( trimedLine.length() > 0 ) - { - if ( trimedLine.startsWith( "- " ) ) - { - //resource-bundle 1.3 mode - if ( lineCount == 1 - && sb.toString().contains( "This product includes/uses software(s) developed by" ) ) - { - currentOrg = organizationEntries.get( sb.toString().trim() ); - if ( currentOrg == null ) - { + if (!trimedLine.startsWith("//")) { + if (trimedLine.length() > 0) { + if (trimedLine.startsWith("- ")) { + // resource-bundle 1.3 mode + if (lineCount == 1 + && sb.toString().contains("This product includes/uses software(s) developed by")) { + currentOrg = organizationEntries.get(sb.toString().trim()); + if (currentOrg == null) { currentOrg = new TreeSet<>(); - organizationEntries.put( sb.toString().trim(), currentOrg ); + organizationEntries.put(sb.toString().trim(), currentOrg); } sb = new StringBuilder(); - } - else if ( sb.length() > 0 && currentOrg != null ) - { - currentOrg.add( sb.toString() ); + } else if (sb.length() > 0 && currentOrg != null) { + currentOrg.add(sb.toString()); sb = new StringBuilder(); } - } - sb.append( line ).append( "\n" ); + sb.append(line).append("\n"); lineCount++; - } - else - { + } else { String ent = sb.toString(); - if ( ent.startsWith( projectName ) && ent.contains( "Copyright " ) ) - { + if (ent.startsWith(projectName) && ent.contains("Copyright ")) { copyright = ent; } - if ( currentOrg == null ) - { - entries.add( ent ); - } - else - { - currentOrg.add( ent ); + if (currentOrg == null) { + entries.add(ent); + } else { + currentOrg.add(ent); } sb = new StringBuilder(); lineCount = 0; @@ -185,76 +156,57 @@ else if ( sb.length() > 0 && currentOrg != null ) line = reader.readLine(); } - if ( sb.length() > 0 ) - { - if ( currentOrg == null ) - { - entries.add( sb.toString() ); - } - else - { - currentOrg.add( sb.toString() ); + if (sb.length() > 0) { + if (currentOrg == null) { + entries.add(sb.toString()); + } else { + currentOrg.add(sb.toString()); } } - if ( time > this.time ) - { - this.time = time; + if (time > this.time) { + this.time = time; } } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return true; } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { - JarEntry jarEntry = new JarEntry( NOTICE_PATH ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); + public void modifyOutputStream(JarOutputStream jos) throws IOException { + JarEntry jarEntry = new JarEntry(NOTICE_PATH); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); Writer writer; - if ( StringUtils.isNotEmpty( encoding ) ) - { - writer = new OutputStreamWriter( jos, encoding ); - } - else - { - writer = new OutputStreamWriter( jos ); + if (StringUtils.isNotEmpty(encoding)) { + writer = new OutputStreamWriter(jos, encoding); + } else { + writer = new OutputStreamWriter(jos); } int count = 0; - for ( String line : entries ) - { + for (String line : entries) { ++count; - if ( line.equals( copyright ) && count != 2 ) - { + if (line.equals(copyright) && count != 2) { continue; } - if ( count == 2 && copyright != null ) - { - writer.write( copyright ); - writer.write( '\n' ); - } - else - { - writer.write( line ); - writer.write( '\n' ); + if (count == 2 && copyright != null) { + writer.write(copyright); + writer.write('\n'); + } else { + writer.write(line); + writer.write('\n'); } - if ( count == 3 ) - { - //do org stuff - for ( Map.Entry> entry : organizationEntries.entrySet() ) - { - writer.write( entry.getKey() ); - writer.write( '\n' ); - for ( String l : entry.getValue() ) - { - writer.write( l ); + if (count == 3) { + // do org stuff + for (Map.Entry> entry : organizationEntries.entrySet()) { + writer.write(entry.getKey()); + writer.write('\n'); + for (String l : entry.getValue()) { + writer.write(l); } - writer.write( '\n' ); + writer.write('\n'); } } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/AppendingTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/AppendingTransformer.java index 77746041..7d31ee4b 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/AppendingTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/AppendingTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; -import org.codehaus.plexus.util.IOUtil; +package org.apache.maven.plugins.shade.resource; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -29,47 +25,42 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.codehaus.plexus.util.IOUtil; + /** * A resource processor that appends content for a resource, separated by a newline. */ -public class AppendingTransformer - extends AbstractCompatibilityTransformer -{ +public class AppendingTransformer extends AbstractCompatibilityTransformer { String resource; ByteArrayOutputStream data = new ByteArrayOutputStream(); private long time = Long.MIN_VALUE; - public boolean canTransformResource( String r ) - { - return resource != null && resource.equalsIgnoreCase( r ); + public boolean canTransformResource(String r) { + return resource != null && resource.equalsIgnoreCase(r); } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { - IOUtil.copy( is, data ); - data.write( '\n' ); - if ( time > this.time ) - { - this.time = time; + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { + IOUtil.copy(is, data); + data.write('\n'); + if (time > this.time) { + this.time = time; } } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return data.size() > 0; } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { - JarEntry jarEntry = new JarEntry( resource ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); + public void modifyOutputStream(JarOutputStream jos) throws IOException { + JarEntry jarEntry = new JarEntry(resource); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); - jos.write( data.toByteArray() ); + jos.write(data.toByteArray()); data.reset(); } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformer.java index 9f836188..9a5269a8 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.WriterFactory; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -import org.codehaus.plexus.util.xml.Xpp3DomWriter; +package org.apache.maven.plugins.shade.resource; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; @@ -38,156 +30,135 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.WriterFactory; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.xml.Xpp3DomBuilder; +import org.codehaus.plexus.util.xml.Xpp3DomWriter; + /** * A resource processor that aggregates plexus components.xml files. */ -public class ComponentsXmlResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class ComponentsXmlResourceTransformer extends AbstractCompatibilityTransformer { private Map components = new LinkedHashMap<>(); private long time = Long.MIN_VALUE; public static final String COMPONENTS_XML_PATH = "META-INF/plexus/components.xml"; - public boolean canTransformResource( String resource ) - { - return COMPONENTS_XML_PATH.equals( resource ); + public boolean canTransformResource(String resource) { + return COMPONENTS_XML_PATH.equals(resource); } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { Xpp3Dom newDom; - try - { - BufferedInputStream bis = new BufferedInputStream( is ) - { - public void close() - throws IOException - { + try { + BufferedInputStream bis = new BufferedInputStream(is) { + public void close() throws IOException { // leave ZIP open } }; - Reader reader = ReaderFactory.newXmlReader( bis ); + Reader reader = ReaderFactory.newXmlReader(bis); - newDom = Xpp3DomBuilder.build( reader ); - } - catch ( Exception e ) - { - throw new IOException( "Error parsing components.xml in " + is, e ); + newDom = Xpp3DomBuilder.build(reader); + } catch (Exception e) { + throw new IOException("Error parsing components.xml in " + is, e); } // Only try to merge in components if there are some elements in the component-set - if ( newDom.getChild( "components" ) == null ) - { + if (newDom.getChild("components") == null) { return; } - Xpp3Dom[] children = newDom.getChild( "components" ).getChildren( "component" ); + Xpp3Dom[] children = newDom.getChild("components").getChildren("component"); - for ( Xpp3Dom component : children ) - { - String role = getValue( component, "role" ); - role = getRelocatedClass( role, relocators ); - setValue( component, "role", role ); + for (Xpp3Dom component : children) { + String role = getValue(component, "role"); + role = getRelocatedClass(role, relocators); + setValue(component, "role", role); - String roleHint = getValue( component, "role-hint" ); + String roleHint = getValue(component, "role-hint"); - String impl = getValue( component, "implementation" ); - impl = getRelocatedClass( impl, relocators ); - setValue( component, "implementation", impl ); + String impl = getValue(component, "implementation"); + impl = getRelocatedClass(impl, relocators); + setValue(component, "implementation", impl); String key = role + ':' + roleHint; - if ( components.containsKey( key ) ) - { + if (components.containsKey(key)) { // TODO: use the tools in Plexus to merge these properly. For now, I just need an all-or-nothing // configuration carry over - Xpp3Dom dom = components.get( key ); - if ( dom.getChild( "configuration" ) != null ) - { - component.addChild( dom.getChild( "configuration" ) ); + Xpp3Dom dom = components.get(key); + if (dom.getChild("configuration") != null) { + component.addChild(dom.getChild("configuration")); } } - Xpp3Dom requirements = component.getChild( "requirements" ); - if ( requirements != null && requirements.getChildCount() > 0 ) - { - for ( int r = requirements.getChildCount() - 1; r >= 0; r-- ) - { - Xpp3Dom requirement = requirements.getChild( r ); + Xpp3Dom requirements = component.getChild("requirements"); + if (requirements != null && requirements.getChildCount() > 0) { + for (int r = requirements.getChildCount() - 1; r >= 0; r--) { + Xpp3Dom requirement = requirements.getChild(r); - String requiredRole = getValue( requirement, "role" ); - requiredRole = getRelocatedClass( requiredRole, relocators ); - setValue( requirement, "role", requiredRole ); + String requiredRole = getValue(requirement, "role"); + requiredRole = getRelocatedClass(requiredRole, relocators); + setValue(requirement, "role", requiredRole); } } - components.put( key, component ); + components.put(key, component); } - if ( time > this.time ) - { - this.time = time; + if (time > this.time) { + this.time = time; } } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { - JarEntry jarEntry = new JarEntry( COMPONENTS_XML_PATH ); - jarEntry.setTime( time ); + public void modifyOutputStream(JarOutputStream jos) throws IOException { + JarEntry jarEntry = new JarEntry(COMPONENTS_XML_PATH); + jarEntry.setTime(time); byte[] data = getTransformedResource(); - jos.putNextEntry( jarEntry ); + jos.putNextEntry(jarEntry); - jos.write( data ); + jos.write(data); components.clear(); } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return !components.isEmpty(); } - byte[] getTransformedResource() - throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 * 4 ); + byte[] getTransformedResource() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 4); - try ( Writer writer = WriterFactory.newXmlWriter( baos ) ) - { - Xpp3Dom dom = new Xpp3Dom( "component-set" ); + try (Writer writer = WriterFactory.newXmlWriter(baos)) { + Xpp3Dom dom = new Xpp3Dom("component-set"); - Xpp3Dom componentDom = new Xpp3Dom( "components" ); + Xpp3Dom componentDom = new Xpp3Dom("components"); - dom.addChild( componentDom ); + dom.addChild(componentDom); - for ( Xpp3Dom component : components.values() ) - { - componentDom.addChild( component ); + for (Xpp3Dom component : components.values()) { + componentDom.addChild(component); } - Xpp3DomWriter.write( writer, dom ); + Xpp3DomWriter.write(writer, dom); } return baos.toByteArray(); } - private String getRelocatedClass( String className, List relocators ) - { - if ( className != null && className.length() > 0 && relocators != null ) - { - for ( Relocator relocator : relocators ) - { - if ( relocator.canRelocateClass( className ) ) - { - return relocator.relocateClass( className ); + private String getRelocatedClass(String className, List relocators) { + if (className != null && className.length() > 0 && relocators != null) { + for (Relocator relocator : relocators) { + if (relocator.canRelocateClass(className)) { + return relocator.relocateClass(className); } } } @@ -195,23 +166,19 @@ private String getRelocatedClass( String className, List relocators ) return className; } - private static String getValue( Xpp3Dom dom, String element ) - { - Xpp3Dom child = dom.getChild( element ); + private static String getValue(Xpp3Dom dom, String element) { + Xpp3Dom child = dom.getChild(element); - return ( child != null && child.getValue() != null ) ? child.getValue() : ""; + return (child != null && child.getValue() != null) ? child.getValue() : ""; } - private static void setValue( Xpp3Dom dom, String element, String value ) - { - Xpp3Dom child = dom.getChild( element ); + private static void setValue(Xpp3Dom dom, String element, String value) { + Xpp3Dom child = dom.getChild(element); - if ( child == null || value == null || value.length() <= 0 ) - { + if (child == null || value == null || value.length() <= 0) { return; } - child.setValue( value ); + child.setValue(value); } - } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/DontIncludeResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/DontIncludeResourceTransformer.java index e1b7bc2d..406171e8 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/DontIncludeResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/DontIncludeResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,39 +16,33 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; -import org.codehaus.plexus.util.StringUtils; +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.jar.JarOutputStream; +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.codehaus.plexus.util.StringUtils; + /** * A resource processor that prevents the inclusion of an arbitrary * resource into the shaded JAR. */ -public class DontIncludeResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class DontIncludeResourceTransformer extends AbstractCompatibilityTransformer { String resource; - + List resources; - public boolean canTransformResource( String r ) - { - if ( StringUtils.isNotEmpty( resource ) && r.endsWith( resource ) ) - { + public boolean canTransformResource(String r) { + if (StringUtils.isNotEmpty(resource) && r.endsWith(resource)) { return true; } - - if ( resources != null ) - { - for ( String resourceEnd : resources ) - { - if ( r.endsWith( resourceEnd ) ) - { + + if (resources != null) { + for (String resourceEnd : resources) { + if (r.endsWith(resourceEnd)) { return true; } } @@ -59,20 +51,16 @@ public boolean canTransformResource( String r ) return false; } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { // no op } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return false; } - public void modifyOutputStream( JarOutputStream os ) - throws IOException - { + public void modifyOutputStream(JarOutputStream os) throws IOException { // no op } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformer.java index 1a8d61d4..b015574b 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; @@ -32,12 +29,12 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; +import org.apache.maven.plugins.shade.relocation.Relocator; + /** * Aggregate Apache Groovy extension modules descriptors */ -public class GroovyResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class GroovyResourceTransformer extends AbstractCompatibilityTransformer { static final String EXT_MODULE_NAME_LEGACY = "META-INF/services/org.codehaus.groovy.runtime.ExtensionModule"; @@ -55,101 +52,83 @@ public class GroovyResourceTransformer private long time = Long.MIN_VALUE; @Override - public boolean canTransformResource( String resource ) - { - return EXT_MODULE_NAME.equals( resource ) || EXT_MODULE_NAME_LEGACY.equals( resource ); + public boolean canTransformResource(String resource) { + return EXT_MODULE_NAME.equals(resource) || EXT_MODULE_NAME_LEGACY.equals(resource); } @Override - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { Properties out = new Properties(); - try ( InputStream props = is ) - { - out.load( props ); + try (InputStream props = is) { + out.load(props); } - String extensionClasses = out.getProperty( "extensionClasses", "" ).trim(); - if ( extensionClasses.length() > 0 ) - { - append( extensionClasses, extensionClassesList ); + String extensionClasses = out.getProperty("extensionClasses", "").trim(); + if (extensionClasses.length() > 0) { + append(extensionClasses, extensionClassesList); } - String staticExtensionClasses = out.getProperty( "staticExtensionClasses", "" ).trim(); - if ( staticExtensionClasses.length() > 0 ) - { - append( staticExtensionClasses, staticExtensionClassesList ); + String staticExtensionClasses = + out.getProperty("staticExtensionClasses", "").trim(); + if (staticExtensionClasses.length() > 0) { + append(staticExtensionClasses, staticExtensionClassesList); } - if ( time > this.time ) - { - this.time = time; + if (time > this.time) { + this.time = time; } } - private void append( String entry, List list ) - { - if ( entry != null ) - { - Collections.addAll( list, entry.split( "\\s*,\\s*" ) ); + private void append(String entry, List list) { + if (entry != null) { + Collections.addAll(list, entry.split("\\s*,\\s*")); } } @Override - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return extensionClassesList.size() > 0 && staticExtensionClassesList.size() > 0; } @Override - public void modifyOutputStream( JarOutputStream os ) - throws IOException - { - if ( hasTransformedResource() ) - { - JarEntry jarEntry = new JarEntry( EXT_MODULE_NAME ); - jarEntry.setTime( time ); - os.putNextEntry( jarEntry ); + public void modifyOutputStream(JarOutputStream os) throws IOException { + if (hasTransformedResource()) { + JarEntry jarEntry = new JarEntry(EXT_MODULE_NAME); + jarEntry.setTime(time); + os.putNextEntry(jarEntry); Properties desc = new Properties(); - desc.put( "moduleName", extModuleName ); - desc.put( "moduleVersion", extModuleVersion ); - if ( extensionClassesList.size() > 0 ) - { - desc.put( "extensionClasses", join( extensionClassesList ) ); + desc.put("moduleName", extModuleName); + desc.put("moduleVersion", extModuleVersion); + if (extensionClassesList.size() > 0) { + desc.put("extensionClasses", join(extensionClassesList)); } - if ( staticExtensionClassesList.size() > 0 ) - { - desc.put( "staticExtensionClasses", join( staticExtensionClassesList ) ); + if (staticExtensionClassesList.size() > 0) { + desc.put("staticExtensionClasses", join(staticExtensionClassesList)); } - desc.store( os, null ); + desc.store(os, null); } } - private String join( Collection strings ) - { + private String join(Collection strings) { Iterator it = strings.iterator(); - switch ( strings.size() ) - { + switch (strings.size()) { case 0: return ""; case 1: return it.next(); default: - StringBuilder buff = new StringBuilder( it.next() ); - while ( it.hasNext() ) - { - buff.append( "," ).append( it.next() ); + StringBuilder buff = new StringBuilder(it.next()); + while (it.hasNext()) { + buff.append(",").append(it.next()); } return buff.toString(); } } - public void setExtModuleName( String extModuleName ) - { + public void setExtModuleName(String extModuleName) { this.extModuleName = extModuleName; } - public void setExtModuleVersion( String extModuleVersion ) - { + public void setExtModuleVersion(String extModuleVersion) { this.extModuleVersion = extModuleVersion; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/IncludeResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/IncludeResourceTransformer.java index dfe3326b..30e64f9c 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/IncludeResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/IncludeResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; -import org.codehaus.plexus.util.IOUtil; +package org.apache.maven.plugins.shade.resource; import java.io.File; import java.io.FileInputStream; @@ -30,54 +26,47 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.codehaus.plexus.util.IOUtil; + /** * A resource processor that allows the addition of an arbitrary file * content into the shaded JAR. */ -public class IncludeResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class IncludeResourceTransformer extends AbstractCompatibilityTransformer { File file; String resource; private long time = Long.MIN_VALUE; - public boolean canTransformResource( String r ) - { + public boolean canTransformResource(String r) { return false; } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { - if ( time > this.time ) - { - this.time = time; + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { + if (time > this.time) { + this.time = time; } } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return file != null && file.exists(); } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { - JarEntry jarEntry = new JarEntry( resource ); - jarEntry.setTime( time ); + public void modifyOutputStream(JarOutputStream jos) throws IOException { + JarEntry jarEntry = new JarEntry(resource); + jarEntry.setTime(time); - try ( InputStream in = new FileInputStream( file ) ) - { - jos.putNextEntry( jarEntry ); - IOUtil.copy( in, jos ); + try (InputStream in = new FileInputStream(file)) { + jos.putNextEntry(jarEntry); + IOUtil.copy(in, jos); } } - + @Override - public String toString() - { + public String toString() { return "IncludeResourceTransformer {resource: '" + resource + "'}"; } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformer.java index d835afde..9ef598b9 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; @@ -40,14 +39,10 @@ * @author Jason van Zyl * @since 1.2 */ -public class ManifestResourceTransformer - extends AbstractCompatibilityTransformer -{ - private final List defaultAttributes = Arrays.asList( "Export-Package", - "Import-Package", - "Provide-Capability", - "Require-Capability" ); - +public class ManifestResourceTransformer extends AbstractCompatibilityTransformer { + private final List defaultAttributes = + Arrays.asList("Export-Package", "Import-Package", "Provide-Capability", "Require-Capability"); + // Configuration private String mainClass; @@ -64,61 +59,49 @@ public class ManifestResourceTransformer private String shade; - public void setMainClass( String mainClass ) - { + public void setMainClass(String mainClass) { this.mainClass = mainClass; } - - public void setManifestEntries( Map manifestEntries ) - { + + public void setManifestEntries(Map manifestEntries) { this.manifestEntries = manifestEntries; } - - public void setAdditionalAttributes( List additionalAttributes ) - { + + public void setAdditionalAttributes(List additionalAttributes) { this.additionalAttributes = additionalAttributes; } @Override - public boolean canTransformResource( String resource ) - { - return JarFile.MANIFEST_NAME.equalsIgnoreCase( resource ); + public boolean canTransformResource(String resource) { + return JarFile.MANIFEST_NAME.equalsIgnoreCase(resource); } @Override - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { // We just want to take the first manifest we come across as that's our project's manifest. This is the behavior // now which is situational at best. Right now there is no context passed in with the processing so we cannot // tell what artifact is being processed. - if ( !manifestDiscovered ) - { - manifest = new Manifest( is ); + if (!manifestDiscovered) { + manifest = new Manifest(is); - if ( relocators != null && !relocators.isEmpty() ) - { + if (relocators != null && !relocators.isEmpty()) { final Attributes attributes = manifest.getMainAttributes(); - for ( final String attribute : defaultAttributes ) - { - final String attributeValue = attributes.getValue( attribute ); - if ( attributeValue != null ) - { - String newValue = relocate( attributeValue, relocators ); - attributes.putValue( attribute, newValue ); + for (final String attribute : defaultAttributes) { + final String attributeValue = attributes.getValue(attribute); + if (attributeValue != null) { + String newValue = relocate(attributeValue, relocators); + attributes.putValue(attribute, newValue); } } - if ( additionalAttributes != null ) - { - for ( final String attribute : additionalAttributes ) - { - final String attributeValue = attributes.getValue( attribute ); - if ( attributeValue != null ) - { - String newValue = relocate( attributeValue, relocators ); - attributes.putValue( attribute, newValue ); + if (additionalAttributes != null) { + for (final String attribute : additionalAttributes) { + final String attributeValue = attributes.getValue(attribute); + if (attributeValue != null) { + String newValue = relocate(attributeValue, relocators); + attributes.putValue(attribute, newValue); } } } @@ -126,69 +109,54 @@ public void processResource( String resource, InputStream is, List re manifestDiscovered = true; - if ( time > this.time ) - { - this.time = time; + if (time > this.time) { + this.time = time; } } } @Override - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return true; } @Override - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { + public void modifyOutputStream(JarOutputStream jos) throws IOException { // If we didn't find a manifest, then let's create one. - if ( manifest == null ) - { + if (manifest == null) { manifest = new Manifest(); } Attributes attributes = manifest.getMainAttributes(); - if ( mainClass != null ) - { - attributes.put( Attributes.Name.MAIN_CLASS, mainClass ); + if (mainClass != null) { + attributes.put(Attributes.Name.MAIN_CLASS, mainClass); } - if ( manifestEntries != null ) - { - for ( Map.Entry entry : manifestEntries.entrySet() ) - { - if ( entry.getValue() == null ) - { - attributes.remove( new Attributes.Name( entry.getKey() ) ); - } - else - { - attributes.put( new Attributes.Name( entry.getKey() ), entry.getValue() ); + if (manifestEntries != null) { + for (Map.Entry entry : manifestEntries.entrySet()) { + if (entry.getValue() == null) { + attributes.remove(new Attributes.Name(entry.getKey())); + } else { + attributes.put(new Attributes.Name(entry.getKey()), entry.getValue()); } } } - JarEntry jarEntry = new JarEntry( JarFile.MANIFEST_NAME ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); - manifest.write( jos ); + JarEntry jarEntry = new JarEntry(JarFile.MANIFEST_NAME); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); + manifest.write(jos); } - - private String relocate( String originalValue, List relocators ) - { + + private String relocate(String originalValue, List relocators) { String newValue = originalValue; - for ( Relocator relocator : relocators ) - { + for (Relocator relocator : relocators) { String value; - do - { + do { value = newValue; - newValue = relocator.relocateClass( value ); - } - while ( !value.equals( newValue ) ); + newValue = relocator.relocateClass(value); + } while (!value.equals(newValue)); } return newValue; } @@ -198,18 +166,15 @@ private String relocate( String originalValue, List relocators ) * * @param shade {@code null}, {@code jar}, {@code test-jar}, {@code sources-jar} or {@code test-sources-jar}. */ - public void setForShade( String shade ) - { + public void setForShade(String shade) { this.shade = shade; } - public boolean isForShade( String shade ) - { - return isUsedForDefaultShading() || this.shade.equalsIgnoreCase( shade ); + public boolean isForShade(String shade) { + return isUsedForDefaultShading() || this.shade.equalsIgnoreCase(shade); } - public boolean isUsedForDefaultShading() - { + public boolean isUsedForDefaultShading() { return this.shade == null || this.shade.isEmpty(); } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/PluginXmlResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/PluginXmlResourceTransformer.java index 0cbb3fae..eed7295b 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/PluginXmlResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/PluginXmlResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; @@ -39,155 +38,125 @@ /** * A resource processor that aggregates Maven plugin.xml files. - * + * * @author Robert Scholte * @since 3.0 */ -public class PluginXmlResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class PluginXmlResourceTransformer extends AbstractCompatibilityTransformer { private List mojos = new ArrayList<>(); private long time = Long.MIN_VALUE; public static final String PLUGIN_XML_PATH = "META-INF/maven/plugin.xml"; - public boolean canTransformResource( String resource ) - { - return PLUGIN_XML_PATH.equals( resource ); + public boolean canTransformResource(String resource) { + return PLUGIN_XML_PATH.equals(resource); } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { Xpp3Dom newDom; - try - { - BufferedInputStream bis = new BufferedInputStream( is ) - { - public void close() - throws IOException - { + try { + BufferedInputStream bis = new BufferedInputStream(is) { + public void close() throws IOException { // leave ZIP open } }; - Reader reader = ReaderFactory.newXmlReader( bis ); + Reader reader = ReaderFactory.newXmlReader(bis); - newDom = Xpp3DomBuilder.build( reader ); - } - catch ( Exception e ) - { - throw new IOException( "Error parsing plugin.xml in " + is, e ); + newDom = Xpp3DomBuilder.build(reader); + } catch (Exception e) { + throw new IOException("Error parsing plugin.xml in " + is, e); } // Only try to merge in mojos if there are some elements in the plugin - if ( newDom.getChild( "mojos" ) == null ) - { + if (newDom.getChild("mojos") == null) { return; } - if ( time > this.time ) - { - this.time = time; + if (time > this.time) { + this.time = time; } - for ( Xpp3Dom mojo : newDom.getChild( "mojos" ).getChildren( "mojo" ) ) - { - - String impl = getValue( mojo, "implementation" ); - impl = getRelocatedClass( impl, relocators ); - setValue( mojo, "implementation", impl ); - - Xpp3Dom parameters = mojo.getChild( "parameters" ); - if ( parameters != null ) - { - for ( Xpp3Dom parameter : parameters.getChildren() ) - { - String type = getValue( parameter, "type" ); - type = getRelocatedClass( type, relocators ); - setValue( parameter, "type", type ); + for (Xpp3Dom mojo : newDom.getChild("mojos").getChildren("mojo")) { + + String impl = getValue(mojo, "implementation"); + impl = getRelocatedClass(impl, relocators); + setValue(mojo, "implementation", impl); + + Xpp3Dom parameters = mojo.getChild("parameters"); + if (parameters != null) { + for (Xpp3Dom parameter : parameters.getChildren()) { + String type = getValue(parameter, "type"); + type = getRelocatedClass(type, relocators); + setValue(parameter, "type", type); } } - Xpp3Dom configuration = mojo.getChild( "configuration" ); - if ( configuration != null ) - { - for ( Xpp3Dom configurationEntry : configuration.getChildren() ) - { - String implementation = getAttribute( configurationEntry, "implementation" ); - implementation = getRelocatedClass( implementation, relocators ); - setAttribute( configurationEntry, "implementation", implementation ); + Xpp3Dom configuration = mojo.getChild("configuration"); + if (configuration != null) { + for (Xpp3Dom configurationEntry : configuration.getChildren()) { + String implementation = getAttribute(configurationEntry, "implementation"); + implementation = getRelocatedClass(implementation, relocators); + setAttribute(configurationEntry, "implementation", implementation); } } - Xpp3Dom requirements = mojo.getChild( "requirements" ); - if ( requirements != null && requirements.getChildCount() > 0 ) - { - for ( Xpp3Dom requirement : requirements.getChildren() ) - { - String requiredRole = getValue( requirement, "role" ); - requiredRole = getRelocatedClass( requiredRole, relocators ); - setValue( requirement, "role", requiredRole ); + Xpp3Dom requirements = mojo.getChild("requirements"); + if (requirements != null && requirements.getChildCount() > 0) { + for (Xpp3Dom requirement : requirements.getChildren()) { + String requiredRole = getValue(requirement, "role"); + requiredRole = getRelocatedClass(requiredRole, relocators); + setValue(requirement, "role", requiredRole); } } - mojos.add( mojo ); + mojos.add(mojo); } } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { + public void modifyOutputStream(JarOutputStream jos) throws IOException { byte[] data = getTransformedResource(); - JarEntry jarEntry = new JarEntry( PLUGIN_XML_PATH ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); + JarEntry jarEntry = new JarEntry(PLUGIN_XML_PATH); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); - jos.write( data ); + jos.write(data); mojos.clear(); } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return !mojos.isEmpty(); } - byte[] getTransformedResource() - throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 * 4 ); + byte[] getTransformedResource() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 4); - try ( Writer writer = WriterFactory.newXmlWriter( baos ) ) - { - Xpp3Dom dom = new Xpp3Dom( "plugin" ); + try (Writer writer = WriterFactory.newXmlWriter(baos)) { + Xpp3Dom dom = new Xpp3Dom("plugin"); - Xpp3Dom componentDom = new Xpp3Dom( "mojos" ); + Xpp3Dom componentDom = new Xpp3Dom("mojos"); - dom.addChild( componentDom ); + dom.addChild(componentDom); - for ( Xpp3Dom mojo : mojos ) - { - componentDom.addChild( mojo ); + for (Xpp3Dom mojo : mojos) { + componentDom.addChild(mojo); } - Xpp3DomWriter.write( writer, dom ); + Xpp3DomWriter.write(writer, dom); } return baos.toByteArray(); } - private String getRelocatedClass( String className, List relocators ) - { - if ( className != null && className.length() > 0 && relocators != null ) - { - for ( Relocator relocator : relocators ) - { - if ( relocator.canRelocateClass( className ) ) - { - return relocator.relocateClass( className ); + private String getRelocatedClass(String className, List relocators) { + if (className != null && className.length() > 0 && relocators != null) { + for (Relocator relocator : relocators) { + if (relocator.canRelocateClass(className)) { + return relocator.relocateClass(className); } } } @@ -195,40 +164,33 @@ private String getRelocatedClass( String className, List relocators ) return className; } - private static String getValue( Xpp3Dom dom, String element ) - { - Xpp3Dom child = dom.getChild( element ); + private static String getValue(Xpp3Dom dom, String element) { + Xpp3Dom child = dom.getChild(element); - return ( child != null && child.getValue() != null ) ? child.getValue() : ""; + return (child != null && child.getValue() != null) ? child.getValue() : ""; } - private static void setValue( Xpp3Dom dom, String element, String value ) - { - Xpp3Dom child = dom.getChild( element ); + private static void setValue(Xpp3Dom dom, String element, String value) { + Xpp3Dom child = dom.getChild(element); - if ( child == null || value == null || value.length() <= 0 ) - { + if (child == null || value == null || value.length() <= 0) { return; } - child.setValue( value ); + child.setValue(value); } - private static String getAttribute( Xpp3Dom dom, String attribute ) - { - return ( dom.getAttribute( attribute ) != null ) ? dom.getAttribute( attribute ) : ""; + private static String getAttribute(Xpp3Dom dom, String attribute) { + return (dom.getAttribute(attribute) != null) ? dom.getAttribute(attribute) : ""; } - private static void setAttribute( Xpp3Dom dom, String attribute, String value ) - { - String attr = dom.getAttribute( attribute ); + private static void setAttribute(Xpp3Dom dom, String attribute, String value) { + String attr = dom.getAttribute(attribute); - if ( attr == null || value == null || value.length() <= 0 ) - { + if (attr == null || value == null || value.length() <= 0) { return; } - dom.setAttribute( attribute, value ); + dom.setAttribute(attribute, value); } - } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java index eb660320..96e3fe5f 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.maven.plugins.shade.relocation.Relocator; + /** * Transform resource ensuring reproducible output: that requires to get the timestamp of * the initial resources to define in a reproducible way the timestamp of the transformed @@ -33,9 +32,7 @@ * @author Hervé Boutemy * @since 3.2.4 */ -public interface ReproducibleResourceTransformer - extends ResourceTransformer -{ +public interface ReproducibleResourceTransformer extends ResourceTransformer { /** * Transform an individual resource * @param resource The resource name @@ -44,6 +41,5 @@ public interface ReproducibleResourceTransformer * @param time the time of the resource to process * @throws IOException When the IO blows up */ - void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException; + void processResource(String resource, InputStream is, List relocators, long time) throws IOException; } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformer.java index a84322ed..a3255e38 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -34,15 +33,13 @@ /** * An appending transformer for resource bundles - * + * * @author Robert Scholte * @since 3.0.0 */ -public class ResourceBundleAppendingTransformer - extends AbstractCompatibilityTransformer -{ - private Map dataMap = new HashMap<>(); - +public class ResourceBundleAppendingTransformer extends AbstractCompatibilityTransformer { + private Map dataMap = new HashMap<>(); + private Pattern resourceBundlePattern; private long time = Long.MIN_VALUE; @@ -51,52 +48,42 @@ public class ResourceBundleAppendingTransformer * the base name of the resource bundle, a fully qualified class name * @param basename The basename. */ - public void setBasename( String basename ) - { - resourceBundlePattern = Pattern.compile( basename + "(_[a-zA-Z]+){0,3}\\.properties" ); + public void setBasename(String basename) { + resourceBundlePattern = Pattern.compile(basename + "(_[a-zA-Z]+){0,3}\\.properties"); } - public boolean canTransformResource( String r ) - { - return resourceBundlePattern != null && resourceBundlePattern.matcher( r ).matches(); + public boolean canTransformResource(String r) { + return resourceBundlePattern != null && resourceBundlePattern.matcher(r).matches(); } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { - ByteArrayOutputStream data = dataMap.get( resource ); - if ( data == null ) - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { + ByteArrayOutputStream data = dataMap.get(resource); + if (data == null) { data = new ByteArrayOutputStream(); - dataMap.put( resource, data ); + dataMap.put(resource, data); } - - IOUtil.copy( is, data ); - data.write( '\n' ); - if ( time > this.time ) - { - this.time = time; + IOUtil.copy(is, data); + data.write('\n'); + + if (time > this.time) { + this.time = time; } } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return !dataMap.isEmpty(); } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { - for ( Map.Entry dataEntry : dataMap.entrySet() ) - { - JarEntry jarEntry = new JarEntry( dataEntry.getKey() ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); + public void modifyOutputStream(JarOutputStream jos) throws IOException { + for (Map.Entry dataEntry : dataMap.entrySet()) { + JarEntry jarEntry = new JarEntry(dataEntry.getKey()); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); - jos.write( dataEntry.getValue().toByteArray() ); + jos.write(dataEntry.getValue().toByteArray()); dataEntry.getValue().reset(); } } - } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ResourceTransformer.java index 7b766667..6452091f 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,18 +16,18 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.jar.JarOutputStream; +import org.apache.maven.plugins.shade.relocation.Relocator; + /** @author Jason van Zyl */ -public interface ResourceTransformer -{ - boolean canTransformResource( String resource ); +public interface ResourceTransformer { + boolean canTransformResource(String resource); /** * Transform an individual resource @@ -39,11 +37,9 @@ public interface ResourceTransformer * @throws IOException When the IO blows up * @deprecated prefer ReproducibleResourceTransformer */ - void processResource( String resource, InputStream is, List relocators ) - throws IOException; + void processResource(String resource, InputStream is, List relocators) throws IOException; boolean hasTransformedResource(); - void modifyOutputStream( JarOutputStream os ) - throws IOException; + void modifyOutputStream(JarOutputStream os) throws IOException; } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/ServicesResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/ServicesResourceTransformer.java index b4e7b63b..0aed982f 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/ServicesResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/ServicesResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; @@ -41,74 +40,60 @@ * META-INF/services/org.apache.maven.project.ProjectBuilder resource packaged into the resultant JAR produced by the * shading process. */ -public class ServicesResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class ServicesResourceTransformer extends AbstractCompatibilityTransformer { private static final String SERVICES_PATH = "META-INF/services"; private final Map> serviceEntries = new HashMap<>(); private long time = Long.MIN_VALUE; - public boolean canTransformResource( String resource ) - { - return resource.startsWith( SERVICES_PATH ); + public boolean canTransformResource(String resource) { + return resource.startsWith(SERVICES_PATH); } - public void processResource( String resource, InputStream is, final List relocators, long time ) - throws IOException - { - resource = resource.substring( SERVICES_PATH.length() + 1 ); - for ( Relocator relocator : relocators ) - { - if ( relocator.canRelocateClass( resource ) ) - { - resource = relocator.relocateClass( resource ); + public void processResource(String resource, InputStream is, final List relocators, long time) + throws IOException { + resource = resource.substring(SERVICES_PATH.length() + 1); + for (Relocator relocator : relocators) { + if (relocator.canRelocateClass(resource)) { + resource = relocator.relocateClass(resource); break; } } resource = SERVICES_PATH + '/' + resource; - Set out = serviceEntries.computeIfAbsent( resource, k -> new LinkedHashSet<>() ); + Set out = serviceEntries.computeIfAbsent(resource, k -> new LinkedHashSet<>()); - Scanner scanner = new Scanner( is, StandardCharsets.UTF_8.name() ); - while ( scanner.hasNextLine() ) - { + Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name()); + while (scanner.hasNextLine()) { String relContent = scanner.nextLine(); - for ( Relocator relocator : relocators ) - { - if ( relocator.canRelocateClass( relContent ) ) - { - relContent = relocator.applyToSourceContent( relContent ); + for (Relocator relocator : relocators) { + if (relocator.canRelocateClass(relContent)) { + relContent = relocator.applyToSourceContent(relContent); } } - out.add( relContent ); + out.add(relContent); } - if ( time > this.time ) - { + if (time > this.time) { this.time = time; } } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return !serviceEntries.isEmpty(); } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { - for ( Map.Entry> entry : serviceEntries.entrySet() ) - { + public void modifyOutputStream(JarOutputStream jos) throws IOException { + for (Map.Entry> entry : serviceEntries.entrySet()) { String key = entry.getKey(); Set data = entry.getValue(); - JarEntry jarEntry = new JarEntry( key ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); + JarEntry jarEntry = new JarEntry(key); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); - IOUtils.writeLines( data, "\n", jos, StandardCharsets.UTF_8 ); + IOUtils.writeLines(data, "\n", jos, StandardCharsets.UTF_8); jos.flush(); data.clear(); } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/SisuIndexResourceTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/SisuIndexResourceTransformer.java index 546970d8..380acbe6 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/SisuIndexResourceTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/SisuIndexResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; @@ -37,9 +36,7 @@ * * @since 3.3.0 */ -public class SisuIndexResourceTransformer - extends AbstractCompatibilityTransformer -{ +public class SisuIndexResourceTransformer extends AbstractCompatibilityTransformer { private static final String SISU_INDEX_PATH = "META-INF/sisu/javax.inject.Named"; private final ArrayList indexEntries = new ArrayList<>(); @@ -47,52 +44,42 @@ public class SisuIndexResourceTransformer private long time = Long.MIN_VALUE; @Override - public boolean canTransformResource( final String resource ) - { - return resource.equals( SISU_INDEX_PATH ); + public boolean canTransformResource(final String resource) { + return resource.equals(SISU_INDEX_PATH); } @Override - public void processResource( final String resource, - final InputStream is, - final List relocators, - long time ) throws IOException - { - Scanner scanner = new Scanner( is, StandardCharsets.UTF_8.name() ); - while ( scanner.hasNextLine() ) - { + public void processResource( + final String resource, final InputStream is, final List relocators, long time) + throws IOException { + Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name()); + while (scanner.hasNextLine()) { String relContent = scanner.nextLine(); - for ( Relocator relocator : relocators ) - { - if ( relocator.canRelocateClass( relContent ) ) - { - relContent = relocator.applyToSourceContent( relContent ); + for (Relocator relocator : relocators) { + if (relocator.canRelocateClass(relContent)) { + relContent = relocator.applyToSourceContent(relContent); } } - indexEntries.add( relContent ); + indexEntries.add(relContent); } - if ( time > this.time ) - { - this.time = time; + if (time > this.time) { + this.time = time; } } @Override - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return !indexEntries.isEmpty(); } @Override - public void modifyOutputStream( final JarOutputStream jos ) - throws IOException - { - JarEntry jarEntry = new JarEntry( SISU_INDEX_PATH ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); - IOUtils.writeLines( indexEntries, "\n", jos, StandardCharsets.UTF_8 ); + public void modifyOutputStream(final JarOutputStream jos) throws IOException { + JarEntry jarEntry = new JarEntry(SISU_INDEX_PATH); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); + IOUtils.writeLines(indexEntries, "\n", jos, StandardCharsets.UTF_8); jos.flush(); indexEntries.clear(); - } + } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/UseDependencyReducedPom.java b/src/main/java/org/apache/maven/plugins/shade/resource/UseDependencyReducedPom.java index 8e7071d1..0f882b56 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/UseDependencyReducedPom.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/UseDependencyReducedPom.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,24 +16,21 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.project.MavenProject; +package org.apache.maven.plugins.shade.resource; import java.io.File; import java.util.ArrayList; import java.util.List; +import org.apache.maven.project.MavenProject; + /** * Manually creates the resource processors needed to remove the original pom.xml and inject * the dependency-reduced-pom.xml in its place in the shaded JAR. */ -public class UseDependencyReducedPom -{ +public class UseDependencyReducedPom { public static List createPomReplaceTransformers( - MavenProject project, - File dependencyReducedPomLocation - ) - { + MavenProject project, File dependencyReducedPomLocation) { String pomInFinalJarFilename = "META-INF/maven/" + project.getGroupId() + "/" + project.getArtifactId() + "/pom.xml"; @@ -43,12 +38,12 @@ public static List createPomReplaceTransformers( DontIncludeResourceTransformer removePom = new DontIncludeResourceTransformer(); removePom.resource = pomInFinalJarFilename; - resourceTransformers.add( removePom ); + resourceTransformers.add(removePom); IncludeResourceTransformer insertDependencyReducedPom = new IncludeResourceTransformer(); insertDependencyReducedPom.file = dependencyReducedPomLocation; insertDependencyReducedPom.resource = pomInFinalJarFilename; - resourceTransformers.add( insertDependencyReducedPom ); + resourceTransformers.add(insertDependencyReducedPom); return resourceTransformers; } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformer.java index c60cebca..856e15c2 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; @@ -43,9 +42,7 @@ /** * Appends multiple occurrences of some XML file. */ -public class XmlAppendingTransformer - extends AbstractCompatibilityTransformer -{ +public class XmlAppendingTransformer extends AbstractCompatibilityTransformer { public static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"; boolean ignoreDtd = true; @@ -56,86 +53,68 @@ public class XmlAppendingTransformer private long time = Long.MIN_VALUE; - public boolean canTransformResource( String r ) - { - return resource != null && resource.equalsIgnoreCase( r ); + public boolean canTransformResource(String r) { + return resource != null && resource.equalsIgnoreCase(r); } - public void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException - { + public void processResource(String resource, InputStream is, List relocators, long time) + throws IOException { Document r; - try - { - SAXBuilder builder = new SAXBuilder( false ); - builder.setExpandEntities( false ); - if ( ignoreDtd ) - { - builder.setEntityResolver( new EntityResolver() - { - public InputSource resolveEntity( String publicId, String systemId ) - throws SAXException, IOException - { - return new InputSource( new StringReader( "" ) ); + try { + SAXBuilder builder = new SAXBuilder(false); + builder.setExpandEntities(false); + if (ignoreDtd) { + builder.setEntityResolver(new EntityResolver() { + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException, IOException { + return new InputSource(new StringReader("")); } - } ); + }); } - r = builder.build( is ); - } - catch ( JDOMException e ) - { - throw new RuntimeException( "Error processing resource " + resource + ": " + e.getMessage(), e ); + r = builder.build(is); + } catch (JDOMException e) { + throw new RuntimeException("Error processing resource " + resource + ": " + e.getMessage(), e); } - if ( doc == null ) - { + if (doc == null) { doc = r; - } - else - { + } else { Element root = r.getRootElement(); - for ( Iterator itr = root.getAttributes().iterator(); itr.hasNext(); ) - { + for (Iterator itr = root.getAttributes().iterator(); itr.hasNext(); ) { Attribute a = itr.next(); itr.remove(); Element mergedEl = doc.getRootElement(); - Attribute mergedAtt = mergedEl.getAttribute( a.getName(), a.getNamespace() ); - if ( mergedAtt == null ) - { - mergedEl.setAttribute( a ); + Attribute mergedAtt = mergedEl.getAttribute(a.getName(), a.getNamespace()); + if (mergedAtt == null) { + mergedEl.setAttribute(a); } } - for ( Iterator itr = root.getChildren().iterator(); itr.hasNext(); ) - { + for (Iterator itr = root.getChildren().iterator(); itr.hasNext(); ) { Content n = itr.next(); itr.remove(); - doc.getRootElement().addContent( n ); + doc.getRootElement().addContent(n); } } - if ( time > this.time ) - { - this.time = time; + if (time > this.time) { + this.time = time; } } - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return doc != null; } - public void modifyOutputStream( JarOutputStream jos ) - throws IOException - { - JarEntry jarEntry = new JarEntry( resource ); - jarEntry.setTime( time ); - jos.putNextEntry( jarEntry ); + public void modifyOutputStream(JarOutputStream jos) throws IOException { + JarEntry jarEntry = new JarEntry(resource); + jarEntry.setTime(time); + jos.putNextEntry(jarEntry); - new XMLOutputter( Format.getPrettyFormat() ).output( doc, jos ); + new XMLOutputter(Format.getPrettyFormat()).output(doc, jos); doc = null; } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/properties/MicroprofileConfigTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/properties/MicroprofileConfigTransformer.java index 7d47f251..2c22cc56 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/properties/MicroprofileConfigTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/properties/MicroprofileConfigTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.properties; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,16 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource.properties; /** * Enables to merge Microprofile Config configuration files properly respecting their ordinal. * * @since 3.2.2 */ -public class MicroprofileConfigTransformer extends PropertiesTransformer -{ - public MicroprofileConfigTransformer() - { - super( null, "config_ordinal", 1000, false ); +public class MicroprofileConfigTransformer extends PropertiesTransformer { + public MicroprofileConfigTransformer() { + super(null, "config_ordinal", 1000, false); } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/properties/OpenWebBeansPropertiesTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/properties/OpenWebBeansPropertiesTransformer.java index 7c37d34d..352f0e9a 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/properties/OpenWebBeansPropertiesTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/properties/OpenWebBeansPropertiesTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.properties; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,16 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource.properties; /** * Enables to merge openwebbeans configuration files properly respecting their ordinal. * * @since 3.2.2 */ -public class OpenWebBeansPropertiesTransformer extends PropertiesTransformer -{ - public OpenWebBeansPropertiesTransformer() - { - super( "META-INF/openwebbeans/openwebbeans.properties", "configuration.ordinal", 100, false ); +public class OpenWebBeansPropertiesTransformer extends PropertiesTransformer { + public OpenWebBeansPropertiesTransformer() { + super("META-INF/openwebbeans/openwebbeans.properties", "configuration.ordinal", 100, false); } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformer.java b/src/main/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformer.java index 9b927973..f93f5b9e 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformer.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.properties; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource.properties; import java.io.BufferedWriter; import java.io.IOException; @@ -41,9 +40,7 @@ * * @since 3.2.2 */ -public class PropertiesTransformer - implements ReproducibleResourceTransformer -{ +public class PropertiesTransformer implements ReproducibleResourceTransformer { private String resource; private String alreadyMergedKey; private String ordinalKey; @@ -53,14 +50,12 @@ public class PropertiesTransformer private final List properties = new ArrayList<>(); - public PropertiesTransformer() - { + public PropertiesTransformer() { // no-op } - protected PropertiesTransformer( final String resource, final String ordinalKey, - final int defaultOrdinal, final boolean reversed ) - { + protected PropertiesTransformer( + final String resource, final String ordinalKey, final int defaultOrdinal, final boolean reversed) { this.resource = resource; this.ordinalKey = ordinalKey; this.defaultOrdinal = defaultOrdinal; @@ -68,152 +63,123 @@ protected PropertiesTransformer( final String resource, final String ordinalKey, } @Override - public boolean canTransformResource( final String resource ) - { - return Objects.equals( resource, this.resource ); + public boolean canTransformResource(final String resource) { + return Objects.equals(resource, this.resource); } @Override - public final void processResource( String resource, InputStream is, List relocators ) - throws IOException - { - processResource( resource, is, relocators, 0 ); + public final void processResource(String resource, InputStream is, List relocators) throws IOException { + processResource(resource, is, relocators, 0); } @Override - public void processResource( final String resource, final InputStream is, final List relocators, - long time ) - throws IOException - { + public void processResource( + final String resource, final InputStream is, final List relocators, long time) + throws IOException { final Properties p = new Properties(); - p.load( is ); - properties.add( p ); - if ( time > this.time ) - { - this.time = time; + p.load(is); + properties.add(p); + if (time > this.time) { + this.time = time; } } @Override - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return !properties.isEmpty(); } @Override - public void modifyOutputStream( JarOutputStream os ) - throws IOException - { - if ( properties.isEmpty() ) - { + public void modifyOutputStream(JarOutputStream os) throws IOException { + if (properties.isEmpty()) { return; } - final Properties out = mergeProperties( sortProperties() ); - if ( ordinalKey != null ) - { - out.remove( ordinalKey ); + final Properties out = mergeProperties(sortProperties()); + if (ordinalKey != null) { + out.remove(ordinalKey); } - if ( alreadyMergedKey != null ) - { - out.remove( alreadyMergedKey ); + if (alreadyMergedKey != null) { + out.remove(alreadyMergedKey); } - JarEntry jarEntry = new JarEntry( resource ); - jarEntry.setTime( time ); - os.putNextEntry( jarEntry ); + JarEntry jarEntry = new JarEntry(resource); + jarEntry.setTime(time); + os.putNextEntry(jarEntry); final BufferedWriter writer = new SkipPropertiesDateLineWriter( - new OutputStreamWriter( new NoCloseOutputStream( os ), StandardCharsets.ISO_8859_1 ) ); - out.store( writer, " Merged by maven-shade-plugin (" + getClass().getName() + ")" ); + new OutputStreamWriter(new NoCloseOutputStream(os), StandardCharsets.ISO_8859_1)); + out.store(writer, " Merged by maven-shade-plugin (" + getClass().getName() + ")"); writer.close(); os.closeEntry(); } - public void setReverseOrder( final boolean reverseOrder ) - { + public void setReverseOrder(final boolean reverseOrder) { this.reverseOrder = reverseOrder; } - public void setResource( final String resource ) - { + public void setResource(final String resource) { this.resource = resource; } - public void setOrdinalKey( final String ordinalKey ) - { + public void setOrdinalKey(final String ordinalKey) { this.ordinalKey = ordinalKey; } - public void setDefaultOrdinal( final int defaultOrdinal ) - { + public void setDefaultOrdinal(final int defaultOrdinal) { this.defaultOrdinal = defaultOrdinal; } - public void setAlreadyMergedKey( final String alreadyMergedKey ) - { + public void setAlreadyMergedKey(final String alreadyMergedKey) { this.alreadyMergedKey = alreadyMergedKey; } - private List sortProperties() - { + private List sortProperties() { final List sortedProperties = new ArrayList<>(); boolean foundMaster = false; - for ( final Properties current : properties ) - { - if ( alreadyMergedKey != null ) - { - final String master = current.getProperty( alreadyMergedKey ); - if ( Boolean.parseBoolean( master ) ) - { - if ( foundMaster ) - { + for (final Properties current : properties) { + if (alreadyMergedKey != null) { + final String master = current.getProperty(alreadyMergedKey); + if (Boolean.parseBoolean(master)) { + if (foundMaster) { throw new IllegalStateException( - "Ambiguous merged values: " + sortedProperties + ", " + current ); + "Ambiguous merged values: " + sortedProperties + ", " + current); } foundMaster = true; sortedProperties.clear(); - sortedProperties.add( current ); + sortedProperties.add(current); } } - if ( !foundMaster ) - { - final int configOrder = getConfigurationOrdinal( current ); + if (!foundMaster) { + final int configOrder = getConfigurationOrdinal(current); int i; - for ( i = 0; i < sortedProperties.size(); i++ ) - { - int listConfigOrder = getConfigurationOrdinal( sortedProperties.get( i ) ); - if ( ( !reverseOrder && listConfigOrder > configOrder ) - || ( reverseOrder && listConfigOrder < configOrder ) ) - { + for (i = 0; i < sortedProperties.size(); i++) { + int listConfigOrder = getConfigurationOrdinal(sortedProperties.get(i)); + if ((!reverseOrder && listConfigOrder > configOrder) + || (reverseOrder && listConfigOrder < configOrder)) { break; } } - sortedProperties.add( i, current ); + sortedProperties.add(i, current); } } return sortedProperties; } - private int getConfigurationOrdinal( final Properties p ) - { - if ( ordinalKey == null ) - { + private int getConfigurationOrdinal(final Properties p) { + if (ordinalKey == null) { return defaultOrdinal; } - final String configOrderString = p.getProperty( ordinalKey ); - if ( configOrderString != null && configOrderString.length() > 0 ) - { - return Integer.parseInt( configOrderString ); + final String configOrderString = p.getProperty(ordinalKey); + if (configOrderString != null && configOrderString.length() > 0) { + return Integer.parseInt(configOrderString); } return defaultOrdinal; } - private static Properties mergeProperties( final List sortedProperties ) - { + private static Properties mergeProperties(final List sortedProperties) { final Properties mergedProperties = new SortedProperties(); - for ( final Properties p : sortedProperties ) - { - mergedProperties.putAll( p ); + for (final Properties p : sortedProperties) { + mergedProperties.putAll(p); } return mergedProperties; } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/properties/SortedProperties.java b/src/main/java/org/apache/maven/plugins/shade/resource/properties/SortedProperties.java index fb96b84b..1e827362 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/properties/SortedProperties.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/properties/SortedProperties.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.properties; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource.properties; import java.util.ArrayList; import java.util.Collections; @@ -37,44 +36,36 @@ * * IMPORTANT: this only overrides methods used across JVM in store() so ordering is not guaranteed for other cases. */ -public class SortedProperties extends Properties -{ +public class SortedProperties extends Properties { @Override - public Set> entrySet() - { - final List> entries = new ArrayList<>( super.entrySet() ); - Collections.sort( entries, new Comparator>() - { + public Set> entrySet() { + final List> entries = new ArrayList<>(super.entrySet()); + Collections.sort(entries, new Comparator>() { @Override - public int compare( Map.Entry o1, Map.Entry o2 ) - { - return String.valueOf( o1.getKey() ).compareTo( String.valueOf( o2.getKey() ) ); + public int compare(Map.Entry o1, Map.Entry o2) { + return String.valueOf(o1.getKey()).compareTo(String.valueOf(o2.getKey())); } - } ); - return new LinkedHashSet<>( entries ); + }); + return new LinkedHashSet<>(entries); } @Override public synchronized Enumeration keys() // ensure it is sorted to be deterministic - { + { final List keys = new LinkedList<>(); - for ( Object k : super.keySet() ) - { - keys.add( (String) k ); + for (Object k : super.keySet()) { + keys.add((String) k); } - Collections.sort( keys ); + Collections.sort(keys); final Iterator it = keys.iterator(); - return new Enumeration() - { + return new Enumeration() { @Override - public boolean hasMoreElements() - { + public boolean hasMoreElements() { return it.hasNext(); } @Override - public Object nextElement() - { + public Object nextElement() { return it.next(); } }; diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/NoCloseOutputStream.java b/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/NoCloseOutputStream.java index b956044e..30b4e486 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/NoCloseOutputStream.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/NoCloseOutputStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.properties.io; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource.properties.io; import java.io.IOException; import java.io.OutputStream; @@ -26,42 +25,35 @@ * Simple output stream replacing close call by a simpe flush. * Useful for output streams nesting streams (like jar output streams) and using a stream encoder. */ -public class NoCloseOutputStream extends OutputStream -{ +public class NoCloseOutputStream extends OutputStream { private final OutputStream delegate; - public NoCloseOutputStream( OutputStream delegate ) - { + public NoCloseOutputStream(OutputStream delegate) { this.delegate = delegate; } @Override - public void write( int b ) throws IOException - { - delegate.write( b ); + public void write(int b) throws IOException { + delegate.write(b); } @Override - public void write( byte[] b ) throws IOException - { - delegate.write( b ); + public void write(byte[] b) throws IOException { + delegate.write(b); } @Override - public void write( byte[] b, int off, int len ) throws IOException - { - delegate.write( b, off, len ); + public void write(byte[] b, int off, int len) throws IOException { + delegate.write(b, off, len); } @Override - public void flush() throws IOException - { + public void flush() throws IOException { delegate.flush(); } @Override - public void close() throws IOException - { + public void close() throws IOException { delegate.flush(); } } diff --git a/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/SkipPropertiesDateLineWriter.java b/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/SkipPropertiesDateLineWriter.java index 663c7003..cd10ac8e 100644 --- a/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/SkipPropertiesDateLineWriter.java +++ b/src/main/java/org/apache/maven/plugins/shade/resource/properties/io/SkipPropertiesDateLineWriter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.properties.io; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource.properties.io; import java.io.BufferedWriter; import java.io.IOException; @@ -26,72 +25,59 @@ /** * Simple buffered writer skipping its first write(String) call. */ -public class SkipPropertiesDateLineWriter extends BufferedWriter -{ +public class SkipPropertiesDateLineWriter extends BufferedWriter { private State currentState = State.MUST_SKIP_DATE_COMMENT; - public SkipPropertiesDateLineWriter( Writer out ) - { - super( out ); + public SkipPropertiesDateLineWriter(Writer out) { + super(out); } @Override - public void write( String str ) throws IOException - { - if ( currentState.shouldSkip( str ) ) - { + public void write(String str) throws IOException { + if (currentState.shouldSkip(str)) { currentState = currentState.next(); return; } - super.write( str ); + super.write(str); } - private enum State - { - MUST_SKIP_DATE_COMMENT - { + private enum State { + MUST_SKIP_DATE_COMMENT { @Override - boolean shouldSkip( String content ) - { - return content.length() > 1 && content.startsWith( "#" ) && !content.startsWith( "# " ); + boolean shouldSkip(String content) { + return content.length() > 1 && content.startsWith("#") && !content.startsWith("# "); } @Override - State next() - { + State next() { return SKIPPED_DATE_COMMENT; } }, - SKIPPED_DATE_COMMENT - { + SKIPPED_DATE_COMMENT { @Override - boolean shouldSkip( String content ) - { + boolean shouldSkip(String content) { return content.trim().isEmpty(); } @Override - State next() - { + State next() { return DONE; } }, - DONE - { + DONE { @Override - boolean shouldSkip( String content ) - { + boolean shouldSkip(String content) { return false; } @Override - State next() - { - throw new UnsupportedOperationException( "done is a terminal state" ); + State next() { + throw new UnsupportedOperationException("done is a terminal state"); } }; - abstract boolean shouldSkip( String content ); + abstract boolean shouldSkip(String content); + abstract State next(); } } diff --git a/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java b/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java index 960cf8d1..06395d13 100644 --- a/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade; import java.io.BufferedReader; import java.io.File; @@ -25,8 +24,8 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.io.InputStreamReader; +import java.io.OutputStream; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; @@ -71,8 +70,8 @@ import static java.util.Arrays.asList; import static java.util.Collections.singleton; -import static org.codehaus.plexus.util.FileUtils.forceMkdir; import static java.util.Objects.requireNonNull; +import static org.codehaus.plexus.util.FileUtils.forceMkdir; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.hasItems; @@ -89,10 +88,9 @@ * @author Jason van Zyl * @author Mauro Talevi */ -public class DefaultShaderTest -{ - private static final String[] EXCLUDES = new String[] { "org/codehaus/plexus/util/xml/Xpp3Dom", - "org/codehaus/plexus/util/xml/pull.*" }; +public class DefaultShaderTest { + private static final String[] EXCLUDES = + new String[] {"org/codehaus/plexus/util/xml/Xpp3Dom", "org/codehaus/plexus/util/xml/pull.*"}; @ClassRule public static final TemporaryFolder tmp = new TemporaryFolder(); @@ -101,58 +99,56 @@ public class DefaultShaderTest @Test public void testNoopWhenNotRelocated() throws IOException, MojoExecutionException { - final File plexusJar = new File("src/test/jars/plexus-utils-1.4.1.jar" ); - final File shadedOutput = new File( "target/foo-custom_testNoopWhenNotRelocated.jar" ); + final File plexusJar = new File("src/test/jars/plexus-utils-1.4.1.jar"); + final File shadedOutput = new File("target/foo-custom_testNoopWhenNotRelocated.jar"); final Set jars = new LinkedHashSet<>(); - jars.add( new File( "src/test/jars/test-project-1.0-SNAPSHOT.jar" ) ); - jars.add( plexusJar ); + jars.add(new File("src/test/jars/test-project-1.0-SNAPSHOT.jar")); + jars.add(plexusJar); final Relocator relocator = new SimpleRelocator( - "org/codehaus/plexus/util/cli", "relocated/plexus/util/cli", - Collections.emptyList(), Collections.emptyList() ); + "org/codehaus/plexus/util/cli", + "relocated/plexus/util/cli", + Collections.emptyList(), + Collections.emptyList()); final ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( jars ); - shadeRequest.setRelocators( Collections.singletonList( relocator ) ); - shadeRequest.setResourceTransformers( Collections.emptyList() ); - shadeRequest.setFilters( Collections.emptyList() ); - shadeRequest.setUberJar( shadedOutput ); + shadeRequest.setJars(jars); + shadeRequest.setRelocators(Collections.singletonList(relocator)); + shadeRequest.setResourceTransformers(Collections.emptyList()); + shadeRequest.setFilters(Collections.emptyList()); + shadeRequest.setUberJar(shadedOutput); final DefaultShader shader = newShader(); - shader.shade( shadeRequest ); + shader.shade(shadeRequest); - try ( final JarFile originalJar = new JarFile( plexusJar ); - final JarFile shadedJar = new JarFile( shadedOutput ) ) - { + try (final JarFile originalJar = new JarFile(plexusJar); + final JarFile shadedJar = new JarFile(shadedOutput)) { // ASM processes all class files. In doing so, it modifies them, even when not relocating anything. // Before MSHADE-391, the processed files were written to the uber JAR, which did no harm, but made it // difficult to find out by simple file comparison, if a file was actually relocated or not. Now, Shade // makes sure to always write the original file if the class neither was relocated itself nor references // other, relocated classes. So we are checking for regressions here. - assertTrue( areEqual( originalJar, shadedJar, - "org/codehaus/plexus/util/Expand.class" ) ); + assertTrue(areEqual(originalJar, shadedJar, "org/codehaus/plexus/util/Expand.class")); // Relocated files should always be different, because they contain different package names in their byte // code. We should verify this anyway, in order to avoid an existing class file from simply being moved to // another location without actually having been relocated internally. - assertFalse( areEqual( - originalJar, shadedJar, - "org/codehaus/plexus/util/cli/Arg.class", "relocated/plexus/util/cli/Arg.class" ) ); + assertFalse(areEqual( + originalJar, + shadedJar, + "org/codehaus/plexus/util/cli/Arg.class", + "relocated/plexus/util/cli/Arg.class")); } int result = 0; - for ( final String msg : debugMessages.getAllValues() ) - { - if ( "Rewrote class bytecode: org/codehaus/plexus/util/cli/Arg.class".equals(msg) ) - { + for (final String msg : debugMessages.getAllValues()) { + if ("Rewrote class bytecode: org/codehaus/plexus/util/cli/Arg.class".equals(msg)) { result |= 1; - } - else if ( "Keeping original class bytecode: org/codehaus/plexus/util/Expand.class".equals(msg) ) - { + } else if ("Keeping original class bytecode: org/codehaus/plexus/util/Expand.class".equals(msg)) { result |= 2; } } - assertEquals( 3 /* 1 | 2 */ , result); + assertEquals(3 /* 1 | 2 */, result); } @Test @@ -162,28 +158,32 @@ public void testOverlappingResourcesAreLogged() throws IOException, MojoExecutio // we will shade two jars and expect to see META-INF/MANIFEST.MF overlaps, this will always be true // but this can lead to a broken deployment if intended for OSGi or so, so even this should be logged final Set set = new LinkedHashSet<>(); - set.add( new File( "src/test/jars/test-project-1.0-SNAPSHOT.jar" ) ); - set.add( new File( "src/test/jars/plexus-utils-1.4.1.jar" ) ); + set.add(new File("src/test/jars/test-project-1.0-SNAPSHOT.jar")); + set.add(new File("src/test/jars/plexus-utils-1.4.1.jar")); final ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( set ); - shadeRequest.setRelocators( Collections.emptyList() ); - shadeRequest.setResourceTransformers( Collections.emptyList() ); - shadeRequest.setFilters( Collections.emptyList() ); - shadeRequest.setUberJar( new File( "target/foo-custom_testOverlappingResourcesAreLogged.jar" ) ); - shader.shade( shadeRequest ); - - assertThat(warnMessages.getAllValues(), - hasItem(containsString("plexus-utils-1.4.1.jar, test-project-1.0-SNAPSHOT.jar define 1 overlapping resource:"))); - assertThat(warnMessages.getAllValues(), - hasItem(containsString("- META-INF/MANIFEST.MF"))); + shadeRequest.setJars(set); + shadeRequest.setRelocators(Collections.emptyList()); + shadeRequest.setResourceTransformers(Collections.emptyList()); + shadeRequest.setFilters(Collections.emptyList()); + shadeRequest.setUberJar(new File("target/foo-custom_testOverlappingResourcesAreLogged.jar")); + shader.shade(shadeRequest); + + assertThat( + warnMessages.getAllValues(), + hasItem(containsString( + "plexus-utils-1.4.1.jar, test-project-1.0-SNAPSHOT.jar define 1 overlapping resource:"))); + assertThat(warnMessages.getAllValues(), hasItem(containsString("- META-INF/MANIFEST.MF"))); if (Os.isFamily(Os.FAMILY_WINDOWS)) { - assertThat(debugMessages.getAllValues(), - hasItem(containsString("We have a duplicate META-INF/MANIFEST.MF in src\\test\\jars\\plexus-utils-1.4.1.jar"))); - } - else { - assertThat(debugMessages.getAllValues(), - hasItem(containsString("We have a duplicate META-INF/MANIFEST.MF in src/test/jars/plexus-utils-1.4.1.jar"))); + assertThat( + debugMessages.getAllValues(), + hasItem(containsString( + "We have a duplicate META-INF/MANIFEST.MF in src\\test\\jars\\plexus-utils-1.4.1.jar"))); + } else { + assertThat( + debugMessages.getAllValues(), + hasItem(containsString( + "We have a duplicate META-INF/MANIFEST.MF in src/test/jars/plexus-utils-1.4.1.jar"))); } } @@ -223,413 +223,379 @@ public void testOverlappingResourcesAreLoggedExceptATransformerHandlesIt() throw DefaultShader shaderWithTransformer = newShader(); shaderWithTransformer.shade(shadeRequest); - assertThat(warnMessages.getAllValues().size(), is(0) ); + assertThat(warnMessages.getAllValues().size(), is(0)); DefaultShader shaderWithoutTransformer = newShader(); shadeRequest.setResourceTransformers(Collections.emptyList()); shaderWithoutTransformer.shade(shadeRequest); - assertThat(warnMessages.getAllValues(), - hasItems(containsString("j1.jar, j2.jar define 1 overlapping resource:"))); - assertThat(warnMessages.getAllValues(), - hasItems(containsString("- foo.txt"))); - } - finally { + assertThat( + warnMessages.getAllValues(), + hasItems(containsString("j1.jar, j2.jar define 1 overlapping resource:"))); + assertThat(warnMessages.getAllValues(), hasItems(containsString("- foo.txt"))); + } finally { temporaryFolder.delete(); } } @Test - public void testShaderWithDefaultShadedPattern() - throws Exception - { - shaderWithPattern( null, new File( "target/foo-default.jar" ), EXCLUDES ); + public void testShaderWithDefaultShadedPattern() throws Exception { + shaderWithPattern(null, new File("target/foo-default.jar"), EXCLUDES); } @Test - public void testShaderWithStaticInitializedClass() - throws Exception - { + public void testShaderWithStaticInitializedClass() throws Exception { Shader s = newShader(); Set set = new LinkedHashSet<>(); - set.add( new File( "src/test/jars/test-artifact-1.0-SNAPSHOT.jar" ) ); + set.add(new File("src/test/jars/test-artifact-1.0-SNAPSHOT.jar")); List relocators = new ArrayList<>(); - relocators.add( new SimpleRelocator( "org.apache.maven.plugins.shade", null, null, null ) ); + relocators.add(new SimpleRelocator("org.apache.maven.plugins.shade", null, null, null)); List resourceTransformers = new ArrayList<>(); List filters = new ArrayList<>(); - File file = new File( "target/testShaderWithStaticInitializedClass.jar" ); + File file = new File("target/testShaderWithStaticInitializedClass.jar"); ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( set ); - shadeRequest.setUberJar( file ); - shadeRequest.setFilters( filters ); - shadeRequest.setRelocators( relocators ); - shadeRequest.setResourceTransformers( resourceTransformers ); - - s.shade( shadeRequest ); - - try ( URLClassLoader cl = new URLClassLoader( new URL[] { file.toURI().toURL() } ) ) { - Class c = cl.loadClass( "hidden.org.apache.maven.plugins.shade.Lib" ); - Object o = c.newInstance(); - assertEquals( "foo.bar/baz", c.getDeclaredField( "CONSTANT" ).get( o ) ); + shadeRequest.setJars(set); + shadeRequest.setUberJar(file); + shadeRequest.setFilters(filters); + shadeRequest.setRelocators(relocators); + shadeRequest.setResourceTransformers(resourceTransformers); + + s.shade(shadeRequest); + + try (URLClassLoader cl = new URLClassLoader(new URL[] {file.toURI().toURL()})) { + Class c = cl.loadClass("hidden.org.apache.maven.plugins.shade.Lib"); + Object o = c.newInstance(); + assertEquals("foo.bar/baz", c.getDeclaredField("CONSTANT").get(o)); } } @Test - public void testShaderWithCustomShadedPattern() - throws Exception - { - shaderWithPattern( "org/shaded/plexus/util", new File( "target/foo-custom.jar" ), EXCLUDES ); + public void testShaderWithCustomShadedPattern() throws Exception { + shaderWithPattern("org/shaded/plexus/util", new File("target/foo-custom.jar"), EXCLUDES); } @Test - public void testShaderWithoutExcludesShouldRemoveReferencesOfOriginalPattern() - throws Exception - { + public void testShaderWithoutExcludesShouldRemoveReferencesOfOriginalPattern() throws Exception { // FIXME: shaded jar should not include references to org/codehaus/* (empty dirs) or org.codehaus.* META-INF // files. - shaderWithPattern( "org/shaded/plexus/util", new File( "target/foo-custom-without-excludes.jar" ), - new String[] {} ); + shaderWithPattern( + "org/shaded/plexus/util", new File("target/foo-custom-without-excludes.jar"), new String[] {}); } @Test - public void testHandleDirectory() - throws Exception - { + public void testHandleDirectory() throws Exception { final File dir = tmp.getRoot(); // explode src/test/jars/test-artifact-1.0-SNAPSHOT.jar in this temp dir - try ( final JarInputStream in = new JarInputStream( - new FileInputStream( "src/test/jars/test-artifact-1.0-SNAPSHOT.jar" ) ) ) - { + try (final JarInputStream in = + new JarInputStream(new FileInputStream("src/test/jars/test-artifact-1.0-SNAPSHOT.jar"))) { JarEntry nextJarEntry; - while ( (nextJarEntry = in.getNextJarEntry()) != null ) - { - if ( nextJarEntry.isDirectory() ) - { + while ((nextJarEntry = in.getNextJarEntry()) != null) { + if (nextJarEntry.isDirectory()) { continue; } - final File out = new File( dir, nextJarEntry.getName() ); - forceMkdir( out.getParentFile() ); - try ( final OutputStream outputStream = new FileOutputStream( out ) ) - { - IOUtil.copy( in, outputStream, (int) Math.max( nextJarEntry.getSize(), 512 ) ); + final File out = new File(dir, nextJarEntry.getName()); + forceMkdir(out.getParentFile()); + try (final OutputStream outputStream = new FileOutputStream(out)) { + IOUtil.copy(in, outputStream, (int) Math.max(nextJarEntry.getSize(), 512)); } } } // do shade - final File shade = new File( "target/testHandleDirectory.jar" ); - shaderWithPattern( "org/shaded/plexus/util", shade, new String[0], singleton( dir ) ); + final File shade = new File("target/testHandleDirectory.jar"); + shaderWithPattern("org/shaded/plexus/util", shade, new String[0], singleton(dir)); // ensure directory was shaded properly - try ( final JarFile jar = new JarFile( shade ) ) - { + try (final JarFile jar = new JarFile(shade)) { final List entries = new ArrayList<>(); final Enumeration jarEntryEnumeration = jar.entries(); - while ( jarEntryEnumeration.hasMoreElements() ) - { + while (jarEntryEnumeration.hasMoreElements()) { final JarEntry jarEntry = jarEntryEnumeration.nextElement(); - if ( jarEntry.isDirectory() ) - { + if (jarEntry.isDirectory()) { continue; } - entries.add( jarEntry.getName() ); + entries.add(jarEntry.getName()); } - Collections.sort( entries ); + Collections.sort(entries); assertEquals( asList( "META-INF/maven/org.apache.maven.plugins.shade/test-artifact/pom.properties", "META-INF/maven/org.apache.maven.plugins.shade/test-artifact/pom.xml", - "org/apache/maven/plugins/shade/Lib.class" - ), - entries ); + "org/apache/maven/plugins/shade/Lib.class"), + entries); } } @Test - public void testShaderWithRelocatedClassname() - throws Exception - { + public void testShaderWithRelocatedClassname() throws Exception { DefaultShader s = newShader(); Set set = new LinkedHashSet<>(); - set.add( new File( "src/test/jars/test-project-1.0-SNAPSHOT.jar" ) ); + set.add(new File("src/test/jars/test-project-1.0-SNAPSHOT.jar")); - set.add( new File( "src/test/jars/plexus-utils-1.4.1.jar" ) ); + set.add(new File("src/test/jars/plexus-utils-1.4.1.jar")); List relocators = new ArrayList<>(); - relocators.add( new SimpleRelocator( "org/codehaus/plexus/util/", "_plexus/util/__", null, - Collections.emptyList() ) ); + relocators.add(new SimpleRelocator( + "org/codehaus/plexus/util/", "_plexus/util/__", null, Collections.emptyList())); List resourceTransformers = new ArrayList<>(); - resourceTransformers.add( new ComponentsXmlResourceTransformer() ); + resourceTransformers.add(new ComponentsXmlResourceTransformer()); List filters = new ArrayList<>(); - File file = new File( "target/foo-relocate-class.jar" ); + File file = new File("target/foo-relocate-class.jar"); ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( set ); - shadeRequest.setUberJar( file ); - shadeRequest.setFilters( filters ); - shadeRequest.setRelocators( relocators ); - shadeRequest.setResourceTransformers( resourceTransformers ); - - s.shade( shadeRequest ); - - try ( URLClassLoader cl = new URLClassLoader( new URL[] { file.toURI().toURL() } ) ) { - Class c = cl.loadClass( "_plexus.util.__StringUtils" ); - // first, ensure it works: - Object o = c.newInstance(); - assertEquals( "", c.getMethod( "clean", String.class ).invoke( o, (String) null ) ); - - // now, check that its source file was rewritten: - final String[] source = { null }; - final ClassReader classReader = new ClassReader( cl.getResourceAsStream( "_plexus/util/__StringUtils.class" ) ); - classReader.accept( new ClassVisitor( Opcodes.ASM4 ) - { - @Override - public void visitSource( String arg0, String arg1 ) - { - super.visitSource( arg0, arg1 ); - source[0] = arg0; - } - }, ClassReader.SKIP_CODE ); - assertEquals( "__StringUtils.java", source[0] ); + shadeRequest.setJars(set); + shadeRequest.setUberJar(file); + shadeRequest.setFilters(filters); + shadeRequest.setRelocators(relocators); + shadeRequest.setResourceTransformers(resourceTransformers); + + s.shade(shadeRequest); + + try (URLClassLoader cl = new URLClassLoader(new URL[] {file.toURI().toURL()})) { + Class c = cl.loadClass("_plexus.util.__StringUtils"); + // first, ensure it works: + Object o = c.newInstance(); + assertEquals("", c.getMethod("clean", String.class).invoke(o, (String) null)); + + // now, check that its source file was rewritten: + final String[] source = {null}; + final ClassReader classReader = new ClassReader(cl.getResourceAsStream("_plexus/util/__StringUtils.class")); + classReader.accept( + new ClassVisitor(Opcodes.ASM4) { + @Override + public void visitSource(String arg0, String arg1) { + super.visitSource(arg0, arg1); + source[0] = arg0; + } + }, + ClassReader.SKIP_CODE); + assertEquals("__StringUtils.java", source[0]); } } @Test - public void testShaderWithNestedJar() throws Exception - { + public void testShaderWithNestedJar() throws Exception { TemporaryFolder temporaryFolder = new TemporaryFolder(); final String innerJarFileName = "inner.jar"; temporaryFolder.create(); - File innerJar = temporaryFolder.newFile( innerJarFileName ); - try ( JarOutputStream jos = new JarOutputStream( Files.newOutputStream( innerJar.toPath() ) ) ) - { - jos.putNextEntry( new JarEntry( "foo.txt" ) ); - jos.write( "c1".getBytes( StandardCharsets.UTF_8 ) ); + File innerJar = temporaryFolder.newFile(innerJarFileName); + try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(innerJar.toPath()))) { + jos.putNextEntry(new JarEntry("foo.txt")); + jos.write("c1".getBytes(StandardCharsets.UTF_8)); jos.closeEntry(); } ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( new LinkedHashSet<>( Collections.singleton( innerJar ) ) ); - shadeRequest.setFilters( Collections.emptyList() ); - shadeRequest.setRelocators( Collections.emptyList() ); - shadeRequest.setResourceTransformers( Collections.emptyList() ); - File shadedFile = temporaryFolder.newFile( "shaded.jar" ); - shadeRequest.setUberJar( shadedFile ); + shadeRequest.setJars(new LinkedHashSet<>(Collections.singleton(innerJar))); + shadeRequest.setFilters(Collections.emptyList()); + shadeRequest.setRelocators(Collections.emptyList()); + shadeRequest.setResourceTransformers(Collections.emptyList()); + File shadedFile = temporaryFolder.newFile("shaded.jar"); + shadeRequest.setUberJar(shadedFile); DefaultShader shader = newShader(); - shader.shade( shadeRequest ); + shader.shade(shadeRequest); - FileTime lastModified = FileTime.from( Files.getLastModifiedTime( shadedFile.toPath() ).toInstant() - .minus( 5, ChronoUnit.SECONDS ) ); + FileTime lastModified = FileTime.from( + Files.getLastModifiedTime(shadedFile.toPath()).toInstant().minus(5, ChronoUnit.SECONDS)); - Files.setLastModifiedTime( shadedFile.toPath(), lastModified ); + Files.setLastModifiedTime(shadedFile.toPath(), lastModified); shader.shade(shadeRequest); - assertEquals( lastModified, Files.getLastModifiedTime( shadedFile.toPath() ) ); + assertEquals(lastModified, Files.getLastModifiedTime(shadedFile.toPath())); temporaryFolder.delete(); } @Test - public void testShaderNoOverwrite() throws Exception - { + public void testShaderNoOverwrite() throws Exception { TemporaryFolder temporaryFolder = new TemporaryFolder(); final String innerJarFileName = "inner.jar"; temporaryFolder.create(); - File innerJar = temporaryFolder.newFile( innerJarFileName ); - try ( JarOutputStream jos = new JarOutputStream( new FileOutputStream( innerJar ) ) ) - { - jos.putNextEntry( new JarEntry( "foo.txt" ) ); - jos.write( "c1".getBytes( StandardCharsets.UTF_8 ) ); + File innerJar = temporaryFolder.newFile(innerJarFileName); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(innerJar))) { + jos.putNextEntry(new JarEntry("foo.txt")); + jos.write("c1".getBytes(StandardCharsets.UTF_8)); jos.closeEntry(); } - File outerJar = temporaryFolder.newFile( "outer.jar" ); - try ( JarOutputStream jos = new JarOutputStream( new FileOutputStream( outerJar ) ) ) - { - FileInputStream innerStream = new FileInputStream( innerJar ); - byte[] bytes = IOUtil.toByteArray( innerStream, 32 * 1024 ); + File outerJar = temporaryFolder.newFile("outer.jar"); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(outerJar))) { + FileInputStream innerStream = new FileInputStream(innerJar); + byte[] bytes = IOUtil.toByteArray(innerStream, 32 * 1024); innerStream.close(); - writeEntryWithoutCompression( innerJarFileName, bytes, jos ); + writeEntryWithoutCompression(innerJarFileName, bytes, jos); } - ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( new LinkedHashSet<>( Collections.singleton( outerJar ) ) ); - shadeRequest.setFilters( new ArrayList() ); - shadeRequest.setRelocators( new ArrayList() ); - shadeRequest.setResourceTransformers( new ArrayList() ); - File shadedFile = temporaryFolder.newFile( "shaded.jar" ); - shadeRequest.setUberJar( shadedFile ); + shadeRequest.setJars(new LinkedHashSet<>(Collections.singleton(outerJar))); + shadeRequest.setFilters(new ArrayList()); + shadeRequest.setRelocators(new ArrayList()); + shadeRequest.setResourceTransformers(new ArrayList()); + File shadedFile = temporaryFolder.newFile("shaded.jar"); + shadeRequest.setUberJar(shadedFile); DefaultShader shader = newShader(); - shader.shade( shadeRequest ); + shader.shade(shadeRequest); - JarFile shadedJarFile = new JarFile( shadedFile ); - JarEntry entry = shadedJarFile.getJarEntry( innerJarFileName ); + JarFile shadedJarFile = new JarFile(shadedFile); + JarEntry entry = shadedJarFile.getJarEntry(innerJarFileName); - //After shading, entry compression method should not be changed. - Assert.assertEquals( entry.getMethod(), ZipEntry.STORED ); + // After shading, entry compression method should not be changed. + Assert.assertEquals(entry.getMethod(), ZipEntry.STORED); temporaryFolder.delete(); } @Test - public void testShaderWithDuplicateService() throws Exception - { + public void testShaderWithDuplicateService() throws Exception { TemporaryFolder temporaryFolder = new TemporaryFolder(); temporaryFolder.create(); String serviceEntryName = "META-INF/services/my.foo.Service"; String serviceEntryValue = "my.foo.impl.Service1"; - File innerJar1 = temporaryFolder.newFile( "inner1.jar" ); - try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream( innerJar1.toPath() ) ) ) - { - jos.putNextEntry( new JarEntry(serviceEntryName) ); - jos.write( ( serviceEntryValue + NEWLINE ).getBytes( StandardCharsets.UTF_8 ) ); + File innerJar1 = temporaryFolder.newFile("inner1.jar"); + try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(innerJar1.toPath()))) { + jos.putNextEntry(new JarEntry(serviceEntryName)); + jos.write((serviceEntryValue + NEWLINE).getBytes(StandardCharsets.UTF_8)); jos.closeEntry(); } - File innerJar2 = temporaryFolder.newFile( "inner2.jar" ); - try ( JarOutputStream jos = new JarOutputStream( Files.newOutputStream( innerJar2.toPath() ) ) ) - { - jos.putNextEntry( new JarEntry(serviceEntryName) ); - jos.write( ( serviceEntryValue + NEWLINE ).getBytes( StandardCharsets.UTF_8 ) ); + File innerJar2 = temporaryFolder.newFile("inner2.jar"); + try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(innerJar2.toPath()))) { + jos.putNextEntry(new JarEntry(serviceEntryName)); + jos.write((serviceEntryValue + NEWLINE).getBytes(StandardCharsets.UTF_8)); jos.closeEntry(); } ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( new LinkedHashSet<>( Arrays.asList( innerJar1, innerJar2 ) ) ); - shadeRequest.setFilters( Collections.emptyList() ); - shadeRequest.setRelocators( Collections.emptyList() ); - shadeRequest.setResourceTransformers( Collections.singletonList( new ServicesResourceTransformer() ) ); - File shadedFile = temporaryFolder.newFile( "shaded.jar" ); - shadeRequest.setUberJar( shadedFile ); + shadeRequest.setJars(new LinkedHashSet<>(Arrays.asList(innerJar1, innerJar2))); + shadeRequest.setFilters(Collections.emptyList()); + shadeRequest.setRelocators(Collections.emptyList()); + shadeRequest.setResourceTransformers(Collections.singletonList(new ServicesResourceTransformer())); + File shadedFile = temporaryFolder.newFile("shaded.jar"); + shadeRequest.setUberJar(shadedFile); DefaultShader shader = newShader(); - shader.shade( shadeRequest ); + shader.shade(shadeRequest); - JarFile shadedJarFile = new JarFile( shadedFile ); + JarFile shadedJarFile = new JarFile(shadedFile); JarEntry entry = shadedJarFile.getJarEntry(serviceEntryName); - List lines = new BufferedReader( new InputStreamReader( shadedJarFile.getInputStream( entry ), StandardCharsets.UTF_8 ) ) - .lines().collect( Collectors.toList() ); + List lines = new BufferedReader( + new InputStreamReader(shadedJarFile.getInputStream(entry), StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.toList()); - //After shading, there should be a single input - Assert.assertEquals( Collections.singletonList( serviceEntryValue ), lines ); + // After shading, there should be a single input + Assert.assertEquals(Collections.singletonList(serviceEntryValue), lines); temporaryFolder.delete(); } @Test - public void testShaderWithSmallEntries() throws Exception - { + public void testShaderWithSmallEntries() throws Exception { TemporaryFolder temporaryFolder = new TemporaryFolder(); final String innerJarFileName = "inner.jar"; int len; temporaryFolder.create(); - File innerJar = temporaryFolder.newFile( innerJarFileName ); - try ( JarOutputStream jos = new JarOutputStream( new FileOutputStream( innerJar ) ) ) - { - jos.putNextEntry( new JarEntry( "foo.txt" ) ); + File innerJar = temporaryFolder.newFile(innerJarFileName); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(innerJar))) { + jos.putNextEntry(new JarEntry("foo.txt")); byte[] bytes = "c1".getBytes(StandardCharsets.UTF_8); len = bytes.length; - jos.write( bytes ); + jos.write(bytes); jos.closeEntry(); } ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( new LinkedHashSet<>( Collections.singleton( innerJar ) ) ); - shadeRequest.setFilters( new ArrayList() ); - shadeRequest.setRelocators( new ArrayList() ); - shadeRequest.setResourceTransformers( new ArrayList() ); - File shadedFile = temporaryFolder.newFile( "shaded.jar" ); - shadeRequest.setUberJar( shadedFile ); + shadeRequest.setJars(new LinkedHashSet<>(Collections.singleton(innerJar))); + shadeRequest.setFilters(new ArrayList()); + shadeRequest.setRelocators(new ArrayList()); + shadeRequest.setResourceTransformers(new ArrayList()); + File shadedFile = temporaryFolder.newFile("shaded.jar"); + shadeRequest.setUberJar(shadedFile); DefaultShader shader = newShader(); - shader.shade( shadeRequest ); + shader.shade(shadeRequest); - JarFile shadedJarFile = new JarFile( shadedFile ); - JarEntry entry = shadedJarFile.getJarEntry( "foo.txt" ); + JarFile shadedJarFile = new JarFile(shadedFile); + JarEntry entry = shadedJarFile.getJarEntry("foo.txt"); - //After shading, entry compression method should not be changed. - Assert.assertEquals( entry.getSize(), len ); + // After shading, entry compression method should not be changed. + Assert.assertEquals(entry.getSize(), len); temporaryFolder.delete(); } - private void writeEntryWithoutCompression( String entryName, byte[] entryBytes, JarOutputStream jos ) throws IOException - { - final JarEntry entry = new JarEntry( entryName ); + private void writeEntryWithoutCompression(String entryName, byte[] entryBytes, JarOutputStream jos) + throws IOException { + final JarEntry entry = new JarEntry(entryName); final int size = entryBytes.length; final CRC32 crc = new CRC32(); - crc.update( entryBytes, 0, size ); - entry.setSize( size ); - entry.setCompressedSize( size ); - entry.setMethod( ZipEntry.STORED ); - entry.setCrc( crc.getValue() ); - jos.putNextEntry( entry ); - jos.write( entryBytes ); + crc.update(entryBytes, 0, size); + entry.setSize(size); + entry.setCompressedSize(size); + entry.setMethod(ZipEntry.STORED); + entry.setCrc(crc.getValue()); + jos.putNextEntry(entry); + jos.write(entryBytes); jos.closeEntry(); } - private void shaderWithPattern( String shadedPattern, File jar, String[] excludes ) throws Exception - { + private void shaderWithPattern(String shadedPattern, File jar, String[] excludes) throws Exception { Set set = new LinkedHashSet<>(); - set.add( new File( "src/test/jars/test-project-1.0-SNAPSHOT.jar" ) ); - set.add( new File( "src/test/jars/plexus-utils-1.4.1.jar" ) ); - shaderWithPattern( shadedPattern, jar, excludes, set ); + set.add(new File("src/test/jars/test-project-1.0-SNAPSHOT.jar")); + set.add(new File("src/test/jars/plexus-utils-1.4.1.jar")); + shaderWithPattern(shadedPattern, jar, excludes, set); } - private void shaderWithPattern( String shadedPattern, File jar, String[] excludes, Set set ) - throws Exception - { + private void shaderWithPattern(String shadedPattern, File jar, String[] excludes, Set set) throws Exception { DefaultShader s = newShader(); List relocators = new ArrayList<>(); - relocators.add( new SimpleRelocator( "org/codehaus/plexus/util", shadedPattern, null, Arrays.asList( excludes ) ) ); + relocators.add(new SimpleRelocator("org/codehaus/plexus/util", shadedPattern, null, Arrays.asList(excludes))); List resourceTransformers = new ArrayList<>(); - resourceTransformers.add( new ComponentsXmlResourceTransformer() ); + resourceTransformers.add(new ComponentsXmlResourceTransformer()); List filters = new ArrayList<>(); ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( set ); - shadeRequest.setUberJar( jar ); - shadeRequest.setFilters( filters ); - shadeRequest.setRelocators( relocators ); - shadeRequest.setResourceTransformers( resourceTransformers ); + shadeRequest.setJars(set); + shadeRequest.setUberJar(jar); + shadeRequest.setFilters(filters); + shadeRequest.setRelocators(relocators); + shadeRequest.setResourceTransformers(resourceTransformers); - s.shade( shadeRequest ); + s.shade(shadeRequest); } - private DefaultShader newShader() - { + private DefaultShader newShader() { return new DefaultShader(mockLogger()); } @@ -637,8 +603,7 @@ private DefaultShader newShader() private ArgumentCaptor warnMessages; - private Logger mockLogger() - { + private Logger mockLogger() { debugMessages = ArgumentCaptor.forClass(String.class); warnMessages = ArgumentCaptor.forClass(String.class); Logger logger = mock(Logger.class); @@ -649,20 +614,17 @@ private Logger mockLogger() return logger; } - private boolean areEqual( final JarFile jar1, final JarFile jar2, final String entry ) throws IOException - { - return areEqual( jar1, jar2, entry, entry ); + private boolean areEqual(final JarFile jar1, final JarFile jar2, final String entry) throws IOException { + return areEqual(jar1, jar2, entry, entry); } - private boolean areEqual( final JarFile jar1, final JarFile jar2, final String entry1, String entry2 ) - throws IOException - { - try ( final InputStream s1 = jar1.getInputStream( - requireNonNull(jar1.getJarEntry(entry1), entry1 + " in " + jar1.getName() ) ); - final InputStream s2 = jar2.getInputStream( - requireNonNull(jar2.getJarEntry(entry2), entry2 + " in " + jar2.getName() ) )) - { - return Arrays.equals( IOUtil.toByteArray( s1 ), IOUtil.toByteArray( s2 ) ); + private boolean areEqual(final JarFile jar1, final JarFile jar2, final String entry1, String entry2) + throws IOException { + try (final InputStream s1 = jar1.getInputStream( + requireNonNull(jar1.getJarEntry(entry1), entry1 + " in " + jar1.getName())); + final InputStream s2 = jar2.getInputStream( + requireNonNull(jar2.getJarEntry(entry2), entry2 + " in " + jar2.getName()))) { + return Arrays.equals(IOUtil.toByteArray(s1), IOUtil.toByteArray(s2)); } } } diff --git a/src/test/java/org/apache/maven/plugins/shade/MockShader.java b/src/test/java/org/apache/maven/plugins/shade/MockShader.java index 436edc37..f57dd867 100644 --- a/src/test/java/org/apache/maven/plugins/shade/MockShader.java +++ b/src/test/java/org/apache/maven/plugins/shade/MockShader.java @@ -1,4 +1,3 @@ -package org.apache.maven.plugins.shade; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -17,25 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade; -import org.apache.maven.plugin.MojoExecutionException; +import javax.inject.Named; +import javax.inject.Singleton; import java.io.IOException; -import javax.inject.Named; -import javax.inject.Singleton; +import org.apache.maven.plugin.MojoExecutionException; /** * @author Olivier Lamy */ @Singleton -@Named( "mock" ) -public class MockShader - implements Shader -{ - public void shade( ShadeRequest shadeRequest ) - throws IOException, MojoExecutionException - { - System.out.println( "Executing MockShader#shade" ); +@Named("mock") +public class MockShader implements Shader { + public void shade(ShadeRequest shadeRequest) throws IOException, MojoExecutionException { + System.out.println("Executing MockShader#shade"); } } diff --git a/src/test/java/org/apache/maven/plugins/shade/custom/CustomReproducibleResourceTransformer.java b/src/test/java/org/apache/maven/plugins/shade/custom/CustomReproducibleResourceTransformer.java index eef5744c..fadbb034 100644 --- a/src/test/java/org/apache/maven/plugins/shade/custom/CustomReproducibleResourceTransformer.java +++ b/src/test/java/org/apache/maven/plugins/shade/custom/CustomReproducibleResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.custom; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.custom; import java.io.IOException; import java.io.InputStream; @@ -31,12 +30,9 @@ * Custom ReproducibleResourceTransformer for MSHADE-363_old-plugin IT, to check that it can be run with * an older maven-shade-plugin that does not contain the ReproducibleResourceTransformer interface. */ -public class CustomReproducibleResourceTransformer - implements ReproducibleResourceTransformer -{ +public class CustomReproducibleResourceTransformer implements ReproducibleResourceTransformer { @Override - public boolean canTransformResource( final String resource ) - { + public boolean canTransformResource(final String resource) { return true; } @@ -44,35 +40,30 @@ public boolean canTransformResource( final String resource ) * old non-reproducible RessourceTransformer API that will be used by maven-shade-plugin up to 3.2.2. */ @Override - public final void processResource( final String resource, final InputStream is, final List relocators ) - throws IOException - { - System.out.println( "Custom ResourceTransformer called through old API" ); + public final void processResource(final String resource, final InputStream is, final List relocators) + throws IOException { + System.out.println("Custom ResourceTransformer called through old API"); // call new ReproducibleRessourceTransformer API using a conventional timestamp - processResource( resource, is, relocators, 0 ); + processResource(resource, is, relocators, 0); } /** * new reproducible API */ @Override - public void processResource( final String resource, final InputStream is, final List relocators, - long time ) - throws IOException - { - System.out.println( "Custom ResourceTransformer called through new Reprodcible API" ); + public void processResource( + final String resource, final InputStream is, final List relocators, long time) + throws IOException { + System.out.println("Custom ResourceTransformer called through new Reprodcible API"); } @Override - public boolean hasTransformedResource() - { + public boolean hasTransformedResource() { return true; } @Override - public void modifyOutputStream( JarOutputStream os ) - throws IOException - { + public void modifyOutputStream(JarOutputStream os) throws IOException { // do-op for this test } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/shade/filter/MinijarFilterTest.java b/src/test/java/org/apache/maven/plugins/shade/filter/MinijarFilterTest.java index 9f13a12d..5ec9fd14 100644 --- a/src/test/java/org/apache/maven/plugins/shade/filter/MinijarFilterTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/filter/MinijarFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,9 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +package org.apache.maven.plugins.shade.filter; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; @@ -52,11 +40,19 @@ import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentCaptor; -public class MinijarFilterTest -{ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeFalse; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class MinijarFilterTest { @Rule - public TemporaryFolder tempFolder = TemporaryFolder.builder().assureDeletion().build(); + public TemporaryFolder tempFolder = + TemporaryFolder.builder().assureDeletion().build(); private File outputDirectory; private File emptyFile; @@ -65,9 +61,7 @@ public class MinijarFilterTest private ArgumentCaptor logCaptor; @Before - public void init() - throws IOException - { + public void init() throws IOException { this.outputDirectory = tempFolder.newFolder(); this.emptyFile = tempFolder.newFile(); this.jarFile = tempFolder.newFile(); @@ -80,79 +74,73 @@ public void init() * This test will fail on JDK 7 because jdependency needs at least JDK 8. */ @Test - public void testWithMockProject() - throws IOException - { - assumeFalse( "Expected to run under JDK8+", System.getProperty("java.version").startsWith("1.7") ); + public void testWithMockProject() throws IOException { + assumeFalse( + "Expected to run under JDK8+", + System.getProperty("java.version").startsWith("1.7")); - MavenProject mavenProject = mockProject( outputDirectory, emptyFile ); + MavenProject mavenProject = mockProject(outputDirectory, emptyFile); - MinijarFilter mf = new MinijarFilter( mavenProject, log ); + MinijarFilter mf = new MinijarFilter(mavenProject, log); mf.finished(); - verify( log, times( 1 ) ).info( logCaptor.capture() ); - - assertEquals( "Minimized 0 -> 0", logCaptor.getValue() ); + verify(log, times(1)).info(logCaptor.capture()); + assertEquals("Minimized 0 -> 0", logCaptor.getValue()); } @Test - public void testWithPomProject() - throws IOException - { + public void testWithPomProject() throws IOException { // project with pom packaging and no artifact. - MavenProject mavenProject = mockProject( outputDirectory, null ); - mavenProject.setPackaging( "pom" ); + MavenProject mavenProject = mockProject(outputDirectory, null); + mavenProject.setPackaging("pom"); - MinijarFilter mf = new MinijarFilter( mavenProject, log ); + MinijarFilter mf = new MinijarFilter(mavenProject, log); mf.finished(); - verify( log, times( 1 ) ).info( logCaptor.capture() ); + verify(log, times(1)).info(logCaptor.capture()); // verify no access to project's artifacts - verify( mavenProject, times( 0 ) ).getArtifacts(); - - assertEquals( "Minimized 0 -> 0", logCaptor.getValue() ); + verify(mavenProject, times(0)).getArtifacts(); + assertEquals("Minimized 0 -> 0", logCaptor.getValue()); } - private MavenProject mockProject( File outputDirectory, File file, String... classPathElements ) - { - MavenProject mavenProject = mock( MavenProject.class ); + private MavenProject mockProject(File outputDirectory, File file, String... classPathElements) { + MavenProject mavenProject = mock(MavenProject.class); - Artifact artifact = mock( Artifact.class ); - when( artifact.getGroupId() ).thenReturn( "com" ); - when( artifact.getArtifactId() ).thenReturn( "aid" ); - when( artifact.getVersion() ).thenReturn( "1.9" ); - when( artifact.getClassifier() ).thenReturn( "classifier1" ); - when( artifact.getScope() ).thenReturn( Artifact.SCOPE_COMPILE ); + Artifact artifact = mock(Artifact.class); + when(artifact.getGroupId()).thenReturn("com"); + when(artifact.getArtifactId()).thenReturn("aid"); + when(artifact.getVersion()).thenReturn("1.9"); + when(artifact.getClassifier()).thenReturn("classifier1"); + when(artifact.getScope()).thenReturn(Artifact.SCOPE_COMPILE); - when( mavenProject.getArtifact() ).thenReturn( artifact ); + when(mavenProject.getArtifact()).thenReturn(artifact); DefaultArtifact dependencyArtifact = - new DefaultArtifact( "dep.com", "dep.aid", "1.0", "compile", "jar", "classifier2", null ); - dependencyArtifact.setFile( file ); + new DefaultArtifact("dep.com", "dep.aid", "1.0", "compile", "jar", "classifier2", null); + dependencyArtifact.setFile(file); Set artifacts = new TreeSet<>(); - artifacts.add( dependencyArtifact ); + artifacts.add(dependencyArtifact); - when( mavenProject.getArtifacts() ).thenReturn( artifacts ); + when(mavenProject.getArtifacts()).thenReturn(artifacts); - when( mavenProject.getArtifact().getFile() ).thenReturn( file ); + when(mavenProject.getArtifact().getFile()).thenReturn(file); Build build = new Build(); - build.setOutputDirectory( outputDirectory.toString() ); + build.setOutputDirectory(outputDirectory.toString()); List classpath = new ArrayList<>(); - classpath.add( outputDirectory.toString() ); - if ( file != null ) - { + classpath.add(outputDirectory.toString()); + if (file != null) { classpath.add(file.toString()); } - classpath.addAll( Arrays.asList( classPathElements ) ); - when( mavenProject.getBuild() ).thenReturn( build ); + classpath.addAll(Arrays.asList(classPathElements)); + when(mavenProject.getBuild()).thenReturn(build); try { when(mavenProject.getRuntimeClasspathElements()).thenReturn(classpath); } catch (DependencyResolutionRequiredException e) { @@ -163,29 +151,24 @@ private MavenProject mockProject( File outputDirectory, File file, String... cla } @Test - public void finsishedShouldProduceMessageForClassesTotalNonZero() - { - MinijarFilter m = new MinijarFilter( 1, 50, log ); + public void finsishedShouldProduceMessageForClassesTotalNonZero() { + MinijarFilter m = new MinijarFilter(1, 50, log); m.finished(); - verify( log, times( 1 ) ).info( logCaptor.capture() ); - - assertEquals( "Minimized 51 -> 1 (1%)", logCaptor.getValue() ); + verify(log, times(1)).info(logCaptor.capture()); + assertEquals("Minimized 51 -> 1 (1%)", logCaptor.getValue()); } @Test - public void finishedShouldProduceMessageForClassesTotalZero() - { - MinijarFilter m = new MinijarFilter( 0, 0, log ); + public void finishedShouldProduceMessageForClassesTotalZero() { + MinijarFilter m = new MinijarFilter(0, 0, log); m.finished(); - verify( log, times( 1 ) ).info( logCaptor.capture() ); - - assertEquals( "Minimized 0 -> 0", logCaptor.getValue() ); + verify(log, times(1)).info(logCaptor.capture()); + assertEquals("Minimized 0 -> 0", logCaptor.getValue()); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/filter/SimpleFilterTest.java b/src/test/java/org/apache/maven/plugins/shade/filter/SimpleFilterTest.java index a508435b..0ff7b27e 100644 --- a/src/test/java/org/apache/maven/plugins/shade/filter/SimpleFilterTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/filter/SimpleFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,81 +16,81 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +package org.apache.maven.plugins.shade.filter; import java.util.Collections; import org.apache.maven.plugins.shade.mojo.ArchiveFilter; import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * @author Benjamin Bentmann */ -public class SimpleFilterTest -{ +public class SimpleFilterTest { @Test - public void testIsFiltered() - { + public void testIsFiltered() { SimpleFilter filter; - filter = new SimpleFilter( null, null, null ); - assertFalse( filter.isFiltered( "a.properties" ) ); - assertFalse( filter.isFiltered( "org/Test.class" ) ); - - filter = new SimpleFilter( null, Collections. emptySet(), Collections. emptySet() ); - assertFalse( filter.isFiltered( "a.properties" ) ); - assertFalse( filter.isFiltered( "org/Test.class" ) ); - - filter = new SimpleFilter( null, Collections.singleton( "org/Test.class" ), Collections. emptySet() ); - assertTrue( filter.isFiltered( "a.properties" ) ); - assertFalse( filter.isFiltered( "org/Test.class" ) ); - assertTrue( filter.isFiltered( "org/Test.properties" ) ); - - filter = new SimpleFilter( null, Collections. emptySet(), Collections.singleton( "org/Test.class" ) ); - assertFalse( filter.isFiltered( "a.properties" ) ); - assertTrue( filter.isFiltered( "org/Test.class" ) ); - assertFalse( filter.isFiltered( "org/Test.properties" ) ); - - filter = new SimpleFilter( null, Collections.singleton( "**/a.properties" ), Collections. emptySet() ); - assertFalse( filter.isFiltered( "a.properties" ) ); - assertFalse( filter.isFiltered( "org/a.properties" ) ); - assertFalse( filter.isFiltered( "org/maven/a.properties" ) ); - assertTrue( filter.isFiltered( "org/maven/a.class" ) ); - - filter = new SimpleFilter( null, Collections. emptySet(), Collections.singleton( "org/*" ) ); - assertFalse( filter.isFiltered( "Test.class" ) ); - assertTrue( filter.isFiltered( "org/Test.class" ) ); - assertFalse( filter.isFiltered( "org/apache/Test.class" ) ); - - filter = new SimpleFilter( null, Collections. emptySet(), Collections.singleton( "org/**" ) ); - assertFalse( filter.isFiltered( "Test.class" ) ); - assertTrue( filter.isFiltered( "org/Test.class" ) ); - assertTrue( filter.isFiltered( "org/apache/Test.class" ) ); - - filter = new SimpleFilter( null, Collections. emptySet(), Collections.singleton( "org/" ) ); - assertFalse( filter.isFiltered( "Test.class" ) ); - assertTrue( filter.isFiltered( "org/Test.class" ) ); - assertTrue( filter.isFiltered( "org/apache/Test.class" ) ); - - // given defaults shall be excluded and a specific include is given when filtering then only specific file must be included - final ArchiveFilter archiveFilter = mock( ArchiveFilter.class ); - when( archiveFilter.getIncludes() ).thenReturn( Collections.singleton( "specific include" ) ); - when( archiveFilter.getExcludes() ).thenReturn( Collections. emptySet() ); - when( archiveFilter.getExcludeDefaults() ).thenReturn( true ); - filter = new SimpleFilter( null, archiveFilter ); - assertFalse( filter.isFiltered( "specific include" ) ); - assertTrue( filter.isFiltered( "some other file matched by default include" ) ); - - // given defaults shall be included and a specific include is given when filtering then all files must be included - when( archiveFilter.getExcludeDefaults() ).thenReturn( false ); - filter = new SimpleFilter( null, archiveFilter ); - assertFalse( filter.isFiltered( "specific include" ) ); - assertFalse( filter.isFiltered( "some other file matched by default include" ) ); + filter = new SimpleFilter(null, null, null); + assertFalse(filter.isFiltered("a.properties")); + assertFalse(filter.isFiltered("org/Test.class")); + + filter = new SimpleFilter(null, Collections.emptySet(), Collections.emptySet()); + assertFalse(filter.isFiltered("a.properties")); + assertFalse(filter.isFiltered("org/Test.class")); + + filter = new SimpleFilter(null, Collections.singleton("org/Test.class"), Collections.emptySet()); + assertTrue(filter.isFiltered("a.properties")); + assertFalse(filter.isFiltered("org/Test.class")); + assertTrue(filter.isFiltered("org/Test.properties")); + + filter = new SimpleFilter(null, Collections.emptySet(), Collections.singleton("org/Test.class")); + assertFalse(filter.isFiltered("a.properties")); + assertTrue(filter.isFiltered("org/Test.class")); + assertFalse(filter.isFiltered("org/Test.properties")); + + filter = new SimpleFilter(null, Collections.singleton("**/a.properties"), Collections.emptySet()); + assertFalse(filter.isFiltered("a.properties")); + assertFalse(filter.isFiltered("org/a.properties")); + assertFalse(filter.isFiltered("org/maven/a.properties")); + assertTrue(filter.isFiltered("org/maven/a.class")); + + filter = new SimpleFilter(null, Collections.emptySet(), Collections.singleton("org/*")); + assertFalse(filter.isFiltered("Test.class")); + assertTrue(filter.isFiltered("org/Test.class")); + assertFalse(filter.isFiltered("org/apache/Test.class")); + + filter = new SimpleFilter(null, Collections.emptySet(), Collections.singleton("org/**")); + assertFalse(filter.isFiltered("Test.class")); + assertTrue(filter.isFiltered("org/Test.class")); + assertTrue(filter.isFiltered("org/apache/Test.class")); + + filter = new SimpleFilter(null, Collections.emptySet(), Collections.singleton("org/")); + assertFalse(filter.isFiltered("Test.class")); + assertTrue(filter.isFiltered("org/Test.class")); + assertTrue(filter.isFiltered("org/apache/Test.class")); + + // given defaults shall be excluded and a specific include is given when filtering then only specific file must + // be included + final ArchiveFilter archiveFilter = mock(ArchiveFilter.class); + when(archiveFilter.getIncludes()).thenReturn(Collections.singleton("specific include")); + when(archiveFilter.getExcludes()).thenReturn(Collections.emptySet()); + when(archiveFilter.getExcludeDefaults()).thenReturn(true); + filter = new SimpleFilter(null, archiveFilter); + assertFalse(filter.isFiltered("specific include")); + assertTrue(filter.isFiltered("some other file matched by default include")); + + // given defaults shall be included and a specific include is given when filtering then all files must be + // included + when(archiveFilter.getExcludeDefaults()).thenReturn(false); + filter = new SimpleFilter(null, archiveFilter); + assertFalse(filter.isFiltered("specific include")); + assertFalse(filter.isFiltered("some other file matched by default include")); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactIdTest.java b/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactIdTest.java index 70d1d9dd..71133e34 100644 --- a/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactIdTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactIdTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; import org.junit.Test; @@ -28,147 +27,143 @@ /** * @author Benjamin Bentmann */ -public class ArtifactIdTest -{ +public class ArtifactIdTest { @Test - public void testIdParsing() - { + public void testIdParsing() { ArtifactId id; - id = new ArtifactId( (String) null ); - assertEquals( "", id.getGroupId() ); - - id = new ArtifactId( "" ); - assertEquals( "", id.getGroupId() ); - - id = new ArtifactId( "gid" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "*", id.getArtifactId() ); - assertEquals( "*", id.getType() ); - assertEquals( "*", id.getClassifier() ); - - id = new ArtifactId( "gid:" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "", id.getArtifactId() ); - assertEquals( "*", id.getType() ); - assertEquals( "*", id.getClassifier() ); - - id = new ArtifactId( ":aid" ); - assertEquals( "", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "*", id.getType() ); - assertEquals( "*", id.getClassifier() ); - - id = new ArtifactId( "gid:aid" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "*", id.getType() ); - assertEquals( "*", id.getClassifier() ); - - id = new ArtifactId( "gid:aid:" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "*", id.getType() ); - assertEquals( "", id.getClassifier() ); - - id = new ArtifactId( "gid:aid:cls" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "*", id.getType() ); - assertEquals( "cls", id.getClassifier() ); - - id = new ArtifactId( "gid:aid:type:cls" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "type", id.getType() ); - assertEquals( "cls", id.getClassifier() ); - - id = new ArtifactId( "gid:aid::cls" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "", id.getType() ); - assertEquals( "cls", id.getClassifier() ); - - id = new ArtifactId( "gid:aid::" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "", id.getType() ); - assertEquals( "", id.getClassifier() ); - - id = new ArtifactId( "*:aid:type:cls" ); - assertEquals( "*", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "type", id.getType() ); - assertEquals( "cls", id.getClassifier() ); - - id = new ArtifactId( "gid:*:type:cls" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "*", id.getArtifactId() ); - assertEquals( "type", id.getType() ); - assertEquals( "cls", id.getClassifier() ); - - id = new ArtifactId( "gid:aid:*:cls" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "*", id.getType() ); - assertEquals( "cls", id.getClassifier() ); - - id = new ArtifactId( "gid:aid:type:*" ); - assertEquals( "gid", id.getGroupId() ); - assertEquals( "aid", id.getArtifactId() ); - assertEquals( "type", id.getType() ); - assertEquals( "*", id.getClassifier() ); + id = new ArtifactId((String) null); + assertEquals("", id.getGroupId()); + + id = new ArtifactId(""); + assertEquals("", id.getGroupId()); + + id = new ArtifactId("gid"); + assertEquals("gid", id.getGroupId()); + assertEquals("*", id.getArtifactId()); + assertEquals("*", id.getType()); + assertEquals("*", id.getClassifier()); + + id = new ArtifactId("gid:"); + assertEquals("gid", id.getGroupId()); + assertEquals("", id.getArtifactId()); + assertEquals("*", id.getType()); + assertEquals("*", id.getClassifier()); + + id = new ArtifactId(":aid"); + assertEquals("", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("*", id.getType()); + assertEquals("*", id.getClassifier()); + + id = new ArtifactId("gid:aid"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("*", id.getType()); + assertEquals("*", id.getClassifier()); + + id = new ArtifactId("gid:aid:"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("*", id.getType()); + assertEquals("", id.getClassifier()); + + id = new ArtifactId("gid:aid:cls"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("*", id.getType()); + assertEquals("cls", id.getClassifier()); + + id = new ArtifactId("gid:aid:type:cls"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("type", id.getType()); + assertEquals("cls", id.getClassifier()); + + id = new ArtifactId("gid:aid::cls"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("", id.getType()); + assertEquals("cls", id.getClassifier()); + + id = new ArtifactId("gid:aid::"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("", id.getType()); + assertEquals("", id.getClassifier()); + + id = new ArtifactId("*:aid:type:cls"); + assertEquals("*", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("type", id.getType()); + assertEquals("cls", id.getClassifier()); + + id = new ArtifactId("gid:*:type:cls"); + assertEquals("gid", id.getGroupId()); + assertEquals("*", id.getArtifactId()); + assertEquals("type", id.getType()); + assertEquals("cls", id.getClassifier()); + + id = new ArtifactId("gid:aid:*:cls"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("*", id.getType()); + assertEquals("cls", id.getClassifier()); + + id = new ArtifactId("gid:aid:type:*"); + assertEquals("gid", id.getGroupId()); + assertEquals("aid", id.getArtifactId()); + assertEquals("type", id.getType()); + assertEquals("*", id.getClassifier()); } @Test - public void testMatches() - { - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:aid:type:cls" ) ) ); - assertFalse( new ArtifactId( "Gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:aid:type:cls" ) ) ); - assertFalse( new ArtifactId( "gid", "Aid", "type", "cls" ).matches( new ArtifactId( "gid:aid:type:cls" ) ) ); - assertFalse( new ArtifactId( "gid", "aid", "Type", "cls" ).matches( new ArtifactId( "gid:aid:type:cls" ) ) ); - assertFalse( new ArtifactId( "gid", "aid", "type", "Cls" ).matches( new ArtifactId( "gid:aid:type:cls" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "any", "cls" ).matches( new ArtifactId( "gid:aid:cls" ) ) ); - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:aid:cls" ) ) ); - assertFalse( new ArtifactId( "id", "aid", "type", "cls" ).matches( new ArtifactId( "gid:aid:cls" ) ) ); - assertFalse( new ArtifactId( "gid", "id", "type", "cls" ).matches( new ArtifactId( "gid:aid:cls" ) ) ); - assertFalse( new ArtifactId( "gid", "id", "type", "ls" ).matches( new ArtifactId( "gid:aid:cls" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "" ).matches( new ArtifactId( "gid:aid" ) ) ); - assertTrue( new ArtifactId( "gid", "aid", "any", "tests" ).matches( new ArtifactId( "gid:aid" ) ) ); - assertFalse( new ArtifactId( "id", "aid", "type", "" ).matches( new ArtifactId( "gid:aid" ) ) ); - assertFalse( new ArtifactId( "gid", "id", "type", "" ).matches( new ArtifactId( "gid:aid" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "" ).matches( new ArtifactId( "gid" ) ) ); - assertTrue( new ArtifactId( "gid", "id", "any", "any" ).matches( new ArtifactId( "gid" ) ) ); - assertFalse( new ArtifactId( "id", "aid", "type", "" ).matches( new ArtifactId( "gid" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "*:aid:type:cls" ) ) ); - assertTrue( new ArtifactId( "any", "aid", "type", "cls" ).matches( new ArtifactId( "*:aid:type:cls" ) ) ); - assertFalse( new ArtifactId( "any", "id", "type", "cls" ).matches( new ArtifactId( "*:aid:type:cls" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:*:type:cls" ) ) ); - assertTrue( new ArtifactId( "gid", "any", "type", "cls" ).matches( new ArtifactId( "gid:*:type:cls" ) ) ); - assertFalse( new ArtifactId( "id", "any", "type", "cls" ).matches( new ArtifactId( "gid:*:type:cls" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:aid:*:cls" ) ) ); - assertTrue( new ArtifactId( "gid", "aid", "any", "cls" ).matches( new ArtifactId( "gid:aid:*:cls" ) ) ); - assertFalse( new ArtifactId( "id", "aid", "any", "cls" ).matches( new ArtifactId( "gid:aid:*:cls" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:aid:type:*" ) ) ); - assertTrue( new ArtifactId( "gid", "aid", "type", "any" ).matches( new ArtifactId( "gid:aid:type:*" ) ) ); - assertFalse( new ArtifactId( "id", "aid", "type", "any" ).matches( new ArtifactId( "gid:aid:type:*" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:a*d" ) ) ); - assertTrue( new ArtifactId( "gid", "ad", "type", "cls" ).matches( new ArtifactId( "gid:a*d" ) ) ); - assertTrue( new ArtifactId( "gid", "a---d", "type", "cls" ).matches( new ArtifactId( "gid:a*d" ) ) ); - - assertTrue( new ArtifactId( "gid", "aid", "type", "cls" ).matches( new ArtifactId( "gid:a?d" ) ) ); - assertTrue( new ArtifactId( "gid", "a-d", "type", "cls" ).matches( new ArtifactId( "gid:a?d" ) ) ); - assertFalse( new ArtifactId( "gid", "ad", "type", "cls" ).matches( new ArtifactId( "gid:a?d" ) ) ); - assertFalse( new ArtifactId( "gid", "a---d", "type", "cls" ).matches( new ArtifactId( "gid:a?d" ) ) ); + public void testMatches() { + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("gid:aid:type:cls"))); + assertFalse(new ArtifactId("Gid", "aid", "type", "cls").matches(new ArtifactId("gid:aid:type:cls"))); + assertFalse(new ArtifactId("gid", "Aid", "type", "cls").matches(new ArtifactId("gid:aid:type:cls"))); + assertFalse(new ArtifactId("gid", "aid", "Type", "cls").matches(new ArtifactId("gid:aid:type:cls"))); + assertFalse(new ArtifactId("gid", "aid", "type", "Cls").matches(new ArtifactId("gid:aid:type:cls"))); + + assertTrue(new ArtifactId("gid", "aid", "any", "cls").matches(new ArtifactId("gid:aid:cls"))); + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("gid:aid:cls"))); + assertFalse(new ArtifactId("id", "aid", "type", "cls").matches(new ArtifactId("gid:aid:cls"))); + assertFalse(new ArtifactId("gid", "id", "type", "cls").matches(new ArtifactId("gid:aid:cls"))); + assertFalse(new ArtifactId("gid", "id", "type", "ls").matches(new ArtifactId("gid:aid:cls"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "").matches(new ArtifactId("gid:aid"))); + assertTrue(new ArtifactId("gid", "aid", "any", "tests").matches(new ArtifactId("gid:aid"))); + assertFalse(new ArtifactId("id", "aid", "type", "").matches(new ArtifactId("gid:aid"))); + assertFalse(new ArtifactId("gid", "id", "type", "").matches(new ArtifactId("gid:aid"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "").matches(new ArtifactId("gid"))); + assertTrue(new ArtifactId("gid", "id", "any", "any").matches(new ArtifactId("gid"))); + assertFalse(new ArtifactId("id", "aid", "type", "").matches(new ArtifactId("gid"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("*:aid:type:cls"))); + assertTrue(new ArtifactId("any", "aid", "type", "cls").matches(new ArtifactId("*:aid:type:cls"))); + assertFalse(new ArtifactId("any", "id", "type", "cls").matches(new ArtifactId("*:aid:type:cls"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("gid:*:type:cls"))); + assertTrue(new ArtifactId("gid", "any", "type", "cls").matches(new ArtifactId("gid:*:type:cls"))); + assertFalse(new ArtifactId("id", "any", "type", "cls").matches(new ArtifactId("gid:*:type:cls"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("gid:aid:*:cls"))); + assertTrue(new ArtifactId("gid", "aid", "any", "cls").matches(new ArtifactId("gid:aid:*:cls"))); + assertFalse(new ArtifactId("id", "aid", "any", "cls").matches(new ArtifactId("gid:aid:*:cls"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("gid:aid:type:*"))); + assertTrue(new ArtifactId("gid", "aid", "type", "any").matches(new ArtifactId("gid:aid:type:*"))); + assertFalse(new ArtifactId("id", "aid", "type", "any").matches(new ArtifactId("gid:aid:type:*"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("gid:a*d"))); + assertTrue(new ArtifactId("gid", "ad", "type", "cls").matches(new ArtifactId("gid:a*d"))); + assertTrue(new ArtifactId("gid", "a---d", "type", "cls").matches(new ArtifactId("gid:a*d"))); + + assertTrue(new ArtifactId("gid", "aid", "type", "cls").matches(new ArtifactId("gid:a?d"))); + assertTrue(new ArtifactId("gid", "a-d", "type", "cls").matches(new ArtifactId("gid:a?d"))); + assertFalse(new ArtifactId("gid", "ad", "type", "cls").matches(new ArtifactId("gid:a?d"))); + assertFalse(new ArtifactId("gid", "a---d", "type", "cls").matches(new ArtifactId("gid:a?d"))); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactSelectorTest.java b/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactSelectorTest.java index 752faca4..e8857da2 100644 --- a/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactSelectorTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/mojo/ArtifactSelectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.mojo; import java.util.Collection; import java.util.Collections; @@ -30,45 +29,41 @@ /** * @author Benjamin Bentmann */ -public class ArtifactSelectorTest -{ +public class ArtifactSelectorTest { - private ArtifactSelector newSelector( Collection includes, Collection excludes, String groupPrefix ) - { - return new ArtifactSelector( includes, excludes, groupPrefix ); + private ArtifactSelector newSelector(Collection includes, Collection excludes, String groupPrefix) { + return new ArtifactSelector(includes, excludes, groupPrefix); } @Test - public void testIsSelected() - { + public void testIsSelected() { ArtifactSelector selector; - selector = newSelector( null, null, null ); - assertTrue( selector.isSelected( new ArtifactId( "gid", "aid", "type", "cls" ) ) ); + selector = newSelector(null, null, null); + assertTrue(selector.isSelected(new ArtifactId("gid", "aid", "type", "cls"))); - selector = newSelector( null, null, "" ); - assertTrue( selector.isSelected( new ArtifactId( "gid", "aid", "type", "cls" ) ) ); + selector = newSelector(null, null, ""); + assertTrue(selector.isSelected(new ArtifactId("gid", "aid", "type", "cls"))); - selector = newSelector( null, null, "gid" ); - assertTrue( selector.isSelected( new ArtifactId( "gid", "aid", "type", "cls" ) ) ); - assertTrue( selector.isSelected( new ArtifactId( "gid.test", "aid", "type", "cls" ) ) ); - assertFalse( selector.isSelected( new ArtifactId( "id", "aid", "type", "cls" ) ) ); + selector = newSelector(null, null, "gid"); + assertTrue(selector.isSelected(new ArtifactId("gid", "aid", "type", "cls"))); + assertTrue(selector.isSelected(new ArtifactId("gid.test", "aid", "type", "cls"))); + assertFalse(selector.isSelected(new ArtifactId("id", "aid", "type", "cls"))); - selector = newSelector( Collections. emptySet(), Collections. emptySet(), null ); - assertTrue( selector.isSelected( new ArtifactId( "gid", "aid", "type", "cls" ) ) ); + selector = newSelector(Collections.emptySet(), Collections.emptySet(), null); + assertTrue(selector.isSelected(new ArtifactId("gid", "aid", "type", "cls"))); - selector = newSelector( Collections.singleton( "gid:aid" ), Collections. emptySet(), null ); - assertTrue( selector.isSelected( new ArtifactId( "gid", "aid", "type", "cls" ) ) ); - assertFalse( selector.isSelected( new ArtifactId( "gid", "id", "type", "cls" ) ) ); + selector = newSelector(Collections.singleton("gid:aid"), Collections.emptySet(), null); + assertTrue(selector.isSelected(new ArtifactId("gid", "aid", "type", "cls"))); + assertFalse(selector.isSelected(new ArtifactId("gid", "id", "type", "cls"))); - selector = newSelector( Collections. emptySet(), Collections.singleton( "gid:aid" ), null ); - assertFalse( selector.isSelected( new ArtifactId( "gid", "aid", "type", "cls" ) ) ); - assertTrue( selector.isSelected( new ArtifactId( "gid", "id", "type", "cls" ) ) ); + selector = newSelector(Collections.emptySet(), Collections.singleton("gid:aid"), null); + assertFalse(selector.isSelected(new ArtifactId("gid", "aid", "type", "cls"))); + assertTrue(selector.isSelected(new ArtifactId("gid", "id", "type", "cls"))); - selector = newSelector( Collections.singleton( "gid:*" ), Collections.singleton( "*:aid" ), null ); - assertTrue( selector.isSelected( new ArtifactId( "gid", "id", "type", "cls" ) ) ); - assertFalse( selector.isSelected( new ArtifactId( "gid", "aid", "type", "cls" ) ) ); - assertFalse( selector.isSelected( new ArtifactId( "gid.test", "id", "type", "cls" ) ) ); + selector = newSelector(Collections.singleton("gid:*"), Collections.singleton("*:aid"), null); + assertTrue(selector.isSelected(new ArtifactId("gid", "id", "type", "cls"))); + assertFalse(selector.isSelected(new ArtifactId("gid", "aid", "type", "cls"))); + assertFalse(selector.isSelected(new ArtifactId("gid.test", "id", "type", "cls"))); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/mojo/RelativizePathTest.java b/src/test/java/org/apache/maven/plugins/shade/mojo/RelativizePathTest.java index 6d61f068..bdce122e 100644 --- a/src/test/java/org/apache/maven/plugins/shade/mojo/RelativizePathTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/mojo/RelativizePathTest.java @@ -16,37 +16,40 @@ * specific language governing permissions and limitations * under the License. */ - package org.apache.maven.plugins.shade.mojo; -import static org.junit.Assert.assertEquals; - import java.io.File; import java.io.IOException; import org.junit.Test; -public class RelativizePathTest -{ - final static String[] PARENTS = { "rel-path-test-files/a/pom", "rel-path-test-files/a/b/pom", - "rel-path-test-files/a/b/c/pom", "rel-path-test-files/a/c/d/pom" }; +import static org.junit.Assert.assertEquals; + +public class RelativizePathTest { + static final String[] PARENTS = { + "rel-path-test-files/a/pom", + "rel-path-test-files/a/b/pom", + "rel-path-test-files/a/b/c/pom", + "rel-path-test-files/a/c/d/pom" + }; - final static String[] CHILDREN = { "rel-path-test-files/a/b/pom", "rel-path-test-files/a/pom", - "rel-path-test-files/a/b/c1/pom", "rel-path-test-files/a/c/d/pom" }; + static final String[] CHILDREN = { + "rel-path-test-files/a/b/pom", + "rel-path-test-files/a/pom", + "rel-path-test-files/a/b/c1/pom", + "rel-path-test-files/a/c/d/pom" + }; - final static String[] ANSWER = { "../pom", "b/pom", "../c/pom", "pom" }; + static final String[] ANSWER = {"../pom", "b/pom", "../c/pom", "pom"}; @Test - public void runTests() throws IOException - { - for ( int x = 0; x < PARENTS.length; x++ ) - { + public void runTests() throws IOException { + for (int x = 0; x < PARENTS.length; x++) { File parent = new File(PARENTS[x]).getCanonicalFile(); File child = new File(CHILDREN[x]).getCanonicalFile(); String answer = ANSWER[x]; - String r = RelativizePath.convertToRelativePath( parent, child ); - assertEquals(String.format("parent %s child %s", parent.toString(), child.toString()), answer, r ); + String r = RelativizePath.convertToRelativePath(parent, child); + assertEquals(String.format("parent %s child %s", parent.toString(), child.toString()), answer, r); } } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java b/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java index 86a0c5b3..739aa0ca 100644 --- a/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.mojo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +package org.apache.maven.plugins.shade.mojo; import java.io.File; import java.lang.reflect.Field; @@ -65,112 +57,100 @@ import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResult; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * @author Jason van Zyl * @author Mauro Talevi */ -public class ShadeMojoTest - extends AbstractMojoTestCase -{ +public class ShadeMojoTest extends AbstractMojoTestCase { @Override protected void customizeContainerConfiguration(final ContainerConfiguration configuration) { configuration.setClassPathScanning(PlexusConstants.SCANNING_INDEX); } - public void testManifestTransformerSelection() throws Exception - { + public void testManifestTransformerSelection() throws Exception { final ShadeMojo mojo = new ShadeMojo(); final Method m = ShadeMojo.class.getDeclaredMethod("toResourceTransformers", String.class, List.class); m.setAccessible(true); - final ManifestResourceTransformer defaultTfr = new ManifestResourceTransformer() - { + final ManifestResourceTransformer defaultTfr = new ManifestResourceTransformer() { @Override public String toString() // when test fails junit does a toString so easier to read errors this way - { + { return "default"; } }; - final ManifestResourceTransformer testsTfr1 = new ManifestResourceTransformer() - { + final ManifestResourceTransformer testsTfr1 = new ManifestResourceTransformer() { @Override - public String toString() - { + public String toString() { return "t1"; } }; testsTfr1.setForShade("tests"); - final ManifestResourceTransformer testsTfr2 = new ManifestResourceTransformer() - { + final ManifestResourceTransformer testsTfr2 = new ManifestResourceTransformer() { @Override - public String toString() - { + public String toString() { return "t2"; } }; testsTfr2.setForShade("tests"); - assertEquals( - singletonList( defaultTfr ), - m.invoke( mojo, "jar", asList( defaultTfr, testsTfr1, testsTfr2 ) )); - assertEquals( - asList( testsTfr1, testsTfr2 ), - m.invoke( mojo, "tests", asList( defaultTfr, testsTfr1, testsTfr2 ) )); - assertEquals( - asList( testsTfr1, testsTfr2 ), - m.invoke( mojo, "tests", asList( testsTfr1, defaultTfr, testsTfr2 ) )); - assertEquals( - asList( testsTfr1, testsTfr2 ), - m.invoke( mojo, "tests", asList( testsTfr1, testsTfr2, defaultTfr ) )); + assertEquals(singletonList(defaultTfr), m.invoke(mojo, "jar", asList(defaultTfr, testsTfr1, testsTfr2))); + assertEquals(asList(testsTfr1, testsTfr2), m.invoke(mojo, "tests", asList(defaultTfr, testsTfr1, testsTfr2))); + assertEquals(asList(testsTfr1, testsTfr2), m.invoke(mojo, "tests", asList(testsTfr1, defaultTfr, testsTfr2))); + assertEquals(asList(testsTfr1, testsTfr2), m.invoke(mojo, "tests", asList(testsTfr1, testsTfr2, defaultTfr))); } - public void testShaderWithDefaultShadedPattern() - throws Exception - { - shaderWithPattern( null, new File( "target/foo-default.jar" ) ); + public void testShaderWithDefaultShadedPattern() throws Exception { + shaderWithPattern(null, new File("target/foo-default.jar")); } - public void testShaderWithCustomShadedPattern() - throws Exception - { - shaderWithPattern( "org/shaded/plexus/util", new File( "target/foo-custom.jar" ) ); + public void testShaderWithCustomShadedPattern() throws Exception { + shaderWithPattern("org/shaded/plexus/util", new File("target/foo-custom.jar")); } - public void testShaderWithExclusions() - throws Exception - { - File jarFile = new File( getBasedir(), "target/unit/foo-bar.jar" ); + public void testShaderWithExclusions() throws Exception { + File jarFile = new File(getBasedir(), "target/unit/foo-bar.jar"); - Shader s = lookup( Shader.class ); + Shader s = lookup(Shader.class); Set set = new LinkedHashSet<>(); - set.add( new File( getBasedir(), "src/test/jars/test-artifact-1.0-SNAPSHOT.jar" ) ); + set.add(new File(getBasedir(), "src/test/jars/test-artifact-1.0-SNAPSHOT.jar")); List relocators = new ArrayList<>(); - relocators.add( new SimpleRelocator( "org.codehaus.plexus.util", "hidden", null, Arrays.asList( - "org.codehaus.plexus.util.xml.Xpp3Dom", "org.codehaus.plexus.util.xml.pull.*") ) ); + relocators.add(new SimpleRelocator( + "org.codehaus.plexus.util", + "hidden", + null, + Arrays.asList("org.codehaus.plexus.util.xml.Xpp3Dom", "org.codehaus.plexus.util.xml.pull.*"))); List resourceTransformers = new ArrayList<>(); List filters = new ArrayList<>(); ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( set ); - shadeRequest.setUberJar( jarFile ); - shadeRequest.setFilters( filters ); - shadeRequest.setRelocators( relocators ); - shadeRequest.setResourceTransformers( resourceTransformers ); - - s.shade( shadeRequest ); - - try ( URLClassLoader cl = new URLClassLoader( new URL[]{ jarFile.toURI().toURL() } ) ) { - Class c = cl.loadClass( "org.apache.maven.plugins.shade.Lib" ); - - Field field = c.getDeclaredField( "CLASS_REALM_PACKAGE_IMPORT" ); - assertEquals( "org.codehaus.plexus.util.xml.pull", field.get( null ) ); - - Method method = c.getDeclaredMethod( "getClassRealmPackageImport" ); - assertEquals( "org.codehaus.plexus.util.xml.pull", method.invoke( null ) ); + shadeRequest.setJars(set); + shadeRequest.setUberJar(jarFile); + shadeRequest.setFilters(filters); + shadeRequest.setRelocators(relocators); + shadeRequest.setResourceTransformers(resourceTransformers); + + s.shade(shadeRequest); + + try (URLClassLoader cl = new URLClassLoader(new URL[] {jarFile.toURI().toURL()})) { + Class c = cl.loadClass("org.apache.maven.plugins.shade.Lib"); + + Field field = c.getDeclaredField("CLASS_REALM_PACKAGE_IMPORT"); + assertEquals("org.codehaus.plexus.util.xml.pull", field.get(null)); + + Method method = c.getDeclaredMethod("getClassRealmPackageImport"); + assertEquals("org.codehaus.plexus.util.xml.pull", method.invoke(null)); } } @@ -179,98 +159,104 @@ public void testShaderWithExclusions() * * @throws Exception */ - public void testShadeWithFilter() - throws Exception - { + public void testShadeWithFilter() throws Exception { // create and configure MavenProject MavenProject project = new MavenProject(); - ArtifactHandler artifactHandler = lookup( ArtifactHandler.class ); - Artifact artifact = new DefaultArtifact( "org.apache.myfaces.core", "myfaces-impl", - VersionRange.createFromVersion( "2.0.1-SNAPSHOT" ), "compile", "jar", - null, artifactHandler ); - artifact.setFile( new File("myfaces-impl-2.0.1-SNAPSHOT.jar") ); - project.setArtifact( artifact ); - - ShadeMojo mojo = (ShadeMojo) lookupConfiguredMojo( project, "shade" ); + ArtifactHandler artifactHandler = lookup(ArtifactHandler.class); + Artifact artifact = new DefaultArtifact( + "org.apache.myfaces.core", + "myfaces-impl", + VersionRange.createFromVersion("2.0.1-SNAPSHOT"), + "compile", + "jar", + null, + artifactHandler); + artifact.setFile(new File("myfaces-impl-2.0.1-SNAPSHOT.jar")); + project.setArtifact(artifact); + + ShadeMojo mojo = (ShadeMojo) lookupConfiguredMojo(project, "shade"); DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils.newSession(); - repositorySystemSession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory() - .newInstance( repositorySystemSession, new LocalRepository( new File( "target/local-repo/" ) ) ) ); - MavenSession mavenSession = new MavenSession( getContainer(), repositorySystemSession, mock( - MavenExecutionRequest.class), mock( MavenExecutionResult.class) ); + repositorySystemSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repositorySystemSession, new LocalRepository(new File("target/local-repo/")))); + MavenSession mavenSession = new MavenSession( + getContainer(), + repositorySystemSession, + mock(MavenExecutionRequest.class), + mock(MavenExecutionResult.class)); - setVariableValueToObject( mojo, "session", mavenSession ); + setVariableValueToObject(mojo, "session", mavenSession); // set createSourcesJar = true - setVariableValueToObject( mojo, "createSourcesJar", true ); + setVariableValueToObject(mojo, "createSourcesJar", true); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - setVariableValueToObject( mojo, "repositorySystem", repositorySystem ); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + setVariableValueToObject(mojo, "repositorySystem", repositorySystem); - ArtifactResult artifactResult = new ArtifactResult( new ArtifactRequest( mock( - org.eclipse.aether.artifact.Artifact.class ), Collections.emptyList(), "" ) ); + ArtifactResult artifactResult = new ArtifactResult( + new ArtifactRequest(mock(org.eclipse.aether.artifact.Artifact.class), Collections.emptyList(), "")); org.eclipse.aether.artifact.Artifact result = new org.eclipse.aether.artifact.DefaultArtifact( - "org.apache.myfaces.core:myfaces-impl:jar:sources:2.0.1-SNAPSHOT" ) - .setFile( new File("myfaces-impl-2.0.1-SNAPSHOT-sources.jar") ); - artifactResult.setArtifact( result ); - when( repositorySystem.resolveArtifact( eq(mavenSession.getRepositorySession()), any( ArtifactRequest.class) ) ) - .thenReturn( artifactResult ); + "org.apache.myfaces.core:myfaces-impl:jar:sources:2.0.1-SNAPSHOT") + .setFile(new File("myfaces-impl-2.0.1-SNAPSHOT-sources.jar")); + artifactResult.setArtifact(result); + when(repositorySystem.resolveArtifact(eq(mavenSession.getRepositorySession()), any(ArtifactRequest.class))) + .thenReturn(artifactResult); // create and configure the ArchiveFilter ArchiveFilter archiveFilter = new ArchiveFilter(); - Field archiveFilterArtifact = ArchiveFilter.class.getDeclaredField( "artifact" ); - archiveFilterArtifact.setAccessible( true ); - archiveFilterArtifact.set( archiveFilter, "org.apache.myfaces.core:myfaces-impl" ); + Field archiveFilterArtifact = ArchiveFilter.class.getDeclaredField("artifact"); + archiveFilterArtifact.setAccessible(true); + archiveFilterArtifact.set(archiveFilter, "org.apache.myfaces.core:myfaces-impl"); // add ArchiveFilter to mojo - Field filtersField = ShadeMojo.class.getDeclaredField( "filters" ); - filtersField.setAccessible( true ); - filtersField.set( mojo, new ArchiveFilter[]{ archiveFilter } ); + Field filtersField = ShadeMojo.class.getDeclaredField("filters"); + filtersField.setAccessible(true); + filtersField.set(mojo, new ArchiveFilter[] {archiveFilter}); // invoke getFilters() - Method getFilters = ShadeMojo.class.getDeclaredMethod( "getFilters" ); - getFilters.setAccessible( true ); - List filters = (List) getFilters.invoke( mojo); + Method getFilters = ShadeMojo.class.getDeclaredMethod("getFilters"); + getFilters.setAccessible(true); + List filters = (List) getFilters.invoke(mojo); // assertions - there must be one filter - assertEquals( 1, filters.size() ); + assertEquals(1, filters.size()); // the filter must be able to filter the binary and the sources jar - Filter filter = filters.get( 0 ); - assertTrue( filter.canFilter( new File( "myfaces-impl-2.0.1-SNAPSHOT.jar" ) ) ); // binary jar - assertTrue( filter.canFilter( new File( "myfaces-impl-2.0.1-SNAPSHOT-sources.jar" ) ) ); // sources jar + Filter filter = filters.get(0); + assertTrue(filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT.jar"))); // binary jar + assertTrue(filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT-sources.jar"))); // sources jar } - public void shaderWithPattern( String shadedPattern, File jar ) - throws Exception - { - Shader s = lookup( Shader.class ); + public void shaderWithPattern(String shadedPattern, File jar) throws Exception { + Shader s = lookup(Shader.class); Set set = new LinkedHashSet<>(); - set.add( new File( getBasedir(), "src/test/jars/test-project-1.0-SNAPSHOT.jar" ) ); + set.add(new File(getBasedir(), "src/test/jars/test-project-1.0-SNAPSHOT.jar")); - set.add( new File( getBasedir(), "src/test/jars/plexus-utils-1.4.1.jar" ) ); + set.add(new File(getBasedir(), "src/test/jars/plexus-utils-1.4.1.jar")); List relocators = new ArrayList<>(); - relocators.add( new SimpleRelocator( "org/codehaus/plexus/util", shadedPattern, null, Arrays.asList( - "org/codehaus/plexus/util/xml/Xpp3Dom", "org/codehaus/plexus/util/xml/pull.*") ) ); + relocators.add(new SimpleRelocator( + "org/codehaus/plexus/util", + shadedPattern, + null, + Arrays.asList("org/codehaus/plexus/util/xml/Xpp3Dom", "org/codehaus/plexus/util/xml/pull.*"))); List resourceTransformers = new ArrayList<>(); - resourceTransformers.add( new ComponentsXmlResourceTransformer() ); + resourceTransformers.add(new ComponentsXmlResourceTransformer()); List filters = new ArrayList<>(); ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars( set ); - shadeRequest.setUberJar( jar ); - shadeRequest.setFilters( filters ); - shadeRequest.setRelocators( relocators ); - shadeRequest.setResourceTransformers( resourceTransformers ); + shadeRequest.setJars(set); + shadeRequest.setUberJar(jar); + shadeRequest.setFilters(filters); + shadeRequest.setRelocators(relocators); + shadeRequest.setResourceTransformers(resourceTransformers); - s.shade( shadeRequest ); + s.shade(shadeRequest); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorParameterTest.java b/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorParameterTest.java index 64f6da22..ec208eb6 100644 --- a/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorParameterTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorParameterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.relocation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,37 +16,32 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Test; +package org.apache.maven.plugins.shade.relocation; import java.util.Collections; +import org.junit.Test; + import static org.junit.Assert.fail; -public class SimpleRelocatorParameterTest -{ +public class SimpleRelocatorParameterTest { @Test - public void testThatNullPatternInConstructorShouldNotThrowNullPointerException() - { - constructThenFailOnNullPointerException( null, "" ); + public void testThatNullPatternInConstructorShouldNotThrowNullPointerException() { + constructThenFailOnNullPointerException(null, ""); } @Test - public void testThatNullShadedPatternInConstructorShouldNotThrowNullPointerException() - { - constructThenFailOnNullPointerException( "", null ); + public void testThatNullShadedPatternInConstructorShouldNotThrowNullPointerException() { + constructThenFailOnNullPointerException("", null); } - private void constructThenFailOnNullPointerException( String pattern, String shadedPattern ) - { - try - { - new SimpleRelocator( pattern, shadedPattern, Collections. emptyList(), Collections. emptyList() ); - } - catch ( NullPointerException e ) - { - fail( "Constructor should not throw null pointer exceptions" ); + private void constructThenFailOnNullPointerException(String pattern, String shadedPattern) { + try { + new SimpleRelocator( + pattern, shadedPattern, Collections.emptyList(), Collections.emptyList()); + } catch (NullPointerException e) { + fail("Constructor should not throw null pointer exceptions"); } } } diff --git a/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorTest.java b/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorTest.java index 699d1b33..0dfa0376 100644 --- a/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/relocation/SimpleRelocatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.relocation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ - - -import org.junit.Test; +package org.apache.maven.plugins.shade.relocation; import java.util.Arrays; import java.util.Collections; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -35,262 +33,244 @@ * @author Benjamin Bentmann * */ -public class SimpleRelocatorTest -{ +public class SimpleRelocatorTest { @Test - public void testNoNpeRelocateClass() - { - new SimpleRelocator( "foo", "bar", null, null, true ).relocateClass( "foo" ); + public void testNoNpeRelocateClass() { + new SimpleRelocator("foo", "bar", null, null, true).relocateClass("foo"); } @Test - public void testCanRelocatePath() - { + public void testCanRelocatePath() { SimpleRelocator relocator; - relocator = new SimpleRelocator( "org.foo", null, null, null ); - assertTrue( relocator.canRelocatePath( "org/foo/Class" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/Class.class" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/bar/Class" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/bar/Class.class" ) ); - assertFalse( relocator.canRelocatePath( "com/foo/bar/Class" ) ); - assertFalse( relocator.canRelocatePath( "com/foo/bar/Class.class" ) ); - assertFalse( relocator.canRelocatePath( "org/Foo/Class" ) ); - assertFalse( relocator.canRelocatePath( "org/Foo/Class.class" ) ); - - relocator = new SimpleRelocator( "org.foo", null, null, Arrays.asList( - "org.foo.Excluded", "org.foo.public.*", "org.foo.Public*Stuff") ); - assertTrue( relocator.canRelocatePath( "org/foo/Class" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/Class.class" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/excluded" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/Excluded" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/Excluded.class" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/public" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/public/Class" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/public/Class.class" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/publicRELOC/Class" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/PrivateStuff" ) ); - assertTrue( relocator.canRelocatePath( "org/foo/PrivateStuff.class" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/PublicStuff" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/PublicStuff.class" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/PublicUtilStuff" ) ); - assertFalse( relocator.canRelocatePath( "org/foo/PublicUtilStuff.class" ) ); + relocator = new SimpleRelocator("org.foo", null, null, null); + assertTrue(relocator.canRelocatePath("org/foo/Class")); + assertTrue(relocator.canRelocatePath("org/foo/Class.class")); + assertTrue(relocator.canRelocatePath("org/foo/bar/Class")); + assertTrue(relocator.canRelocatePath("org/foo/bar/Class.class")); + assertFalse(relocator.canRelocatePath("com/foo/bar/Class")); + assertFalse(relocator.canRelocatePath("com/foo/bar/Class.class")); + assertFalse(relocator.canRelocatePath("org/Foo/Class")); + assertFalse(relocator.canRelocatePath("org/Foo/Class.class")); + + relocator = new SimpleRelocator( + "org.foo", null, null, Arrays.asList("org.foo.Excluded", "org.foo.public.*", "org.foo.Public*Stuff")); + assertTrue(relocator.canRelocatePath("org/foo/Class")); + assertTrue(relocator.canRelocatePath("org/foo/Class.class")); + assertTrue(relocator.canRelocatePath("org/foo/excluded")); + assertFalse(relocator.canRelocatePath("org/foo/Excluded")); + assertFalse(relocator.canRelocatePath("org/foo/Excluded.class")); + assertFalse(relocator.canRelocatePath("org/foo/public")); + assertFalse(relocator.canRelocatePath("org/foo/public/Class")); + assertFalse(relocator.canRelocatePath("org/foo/public/Class.class")); + assertTrue(relocator.canRelocatePath("org/foo/publicRELOC/Class")); + assertTrue(relocator.canRelocatePath("org/foo/PrivateStuff")); + assertTrue(relocator.canRelocatePath("org/foo/PrivateStuff.class")); + assertFalse(relocator.canRelocatePath("org/foo/PublicStuff")); + assertFalse(relocator.canRelocatePath("org/foo/PublicStuff.class")); + assertFalse(relocator.canRelocatePath("org/foo/PublicUtilStuff")); + assertFalse(relocator.canRelocatePath("org/foo/PublicUtilStuff.class")); } @Test - public void testCanRelocateClass() - { + public void testCanRelocateClass() { SimpleRelocator relocator; - relocator = new SimpleRelocator( "org.foo", null, null, null ); - assertTrue( relocator.canRelocateClass( "org.foo.Class" ) ); - assertTrue( relocator.canRelocateClass( "org.foo.bar.Class" ) ); - assertFalse( relocator.canRelocateClass( "com.foo.bar.Class" ) ); - assertFalse( relocator.canRelocateClass( "org.Foo.Class" ) ); - - relocator = new SimpleRelocator( "org.foo", null, null, Arrays.asList( - "org.foo.Excluded", "org.foo.public.*", "org.foo.Public*Stuff") ); - assertTrue( relocator.canRelocateClass( "org.foo.Class" ) ); - assertTrue( relocator.canRelocateClass( "org.foo.excluded" ) ); - assertFalse( relocator.canRelocateClass( "org.foo.Excluded" ) ); - assertFalse( relocator.canRelocateClass( "org.foo.public" ) ); - assertFalse( relocator.canRelocateClass( "org.foo.public.Class" ) ); - assertTrue( relocator.canRelocateClass( "org.foo.publicRELOC.Class" ) ); - assertTrue( relocator.canRelocateClass( "org.foo.PrivateStuff" ) ); - assertFalse( relocator.canRelocateClass( "org.foo.PublicStuff" ) ); - assertFalse( relocator.canRelocateClass( "org.foo.PublicUtilStuff" ) ); + relocator = new SimpleRelocator("org.foo", null, null, null); + assertTrue(relocator.canRelocateClass("org.foo.Class")); + assertTrue(relocator.canRelocateClass("org.foo.bar.Class")); + assertFalse(relocator.canRelocateClass("com.foo.bar.Class")); + assertFalse(relocator.canRelocateClass("org.Foo.Class")); + + relocator = new SimpleRelocator( + "org.foo", null, null, Arrays.asList("org.foo.Excluded", "org.foo.public.*", "org.foo.Public*Stuff")); + assertTrue(relocator.canRelocateClass("org.foo.Class")); + assertTrue(relocator.canRelocateClass("org.foo.excluded")); + assertFalse(relocator.canRelocateClass("org.foo.Excluded")); + assertFalse(relocator.canRelocateClass("org.foo.public")); + assertFalse(relocator.canRelocateClass("org.foo.public.Class")); + assertTrue(relocator.canRelocateClass("org.foo.publicRELOC.Class")); + assertTrue(relocator.canRelocateClass("org.foo.PrivateStuff")); + assertFalse(relocator.canRelocateClass("org.foo.PublicStuff")); + assertFalse(relocator.canRelocateClass("org.foo.PublicUtilStuff")); } @Test - public void testCanRelocateRawString() - { + public void testCanRelocateRawString() { SimpleRelocator relocator; - relocator = new SimpleRelocator( "org/foo", null, null, null, true ); - assertTrue( relocator.canRelocatePath( "(I)org/foo/bar/Class;" ) ); + relocator = new SimpleRelocator("org/foo", null, null, null, true); + assertTrue(relocator.canRelocatePath("(I)org/foo/bar/Class;")); - relocator = new SimpleRelocator( "^META-INF/org.foo.xml$", null, null, null, true ); - assertTrue( relocator.canRelocatePath( "META-INF/org.foo.xml" ) ); + relocator = new SimpleRelocator("^META-INF/org.foo.xml$", null, null, null, true); + assertTrue(relocator.canRelocatePath("META-INF/org.foo.xml")); } - //MSHADE-119, make sure that the easy part of this works. + // MSHADE-119, make sure that the easy part of this works. @Test - public void testCanRelocateAbsClassPath() - { - SimpleRelocator relocator = new SimpleRelocator( "org.apache.velocity", "org.apache.momentum", null, null ); - assertEquals("/org/apache/momentum/mass.properties", relocator.relocatePath( "/org/apache/velocity/mass.properties" ) ); + public void testCanRelocateAbsClassPath() { + SimpleRelocator relocator = new SimpleRelocator("org.apache.velocity", "org.apache.momentum", null, null); + assertEquals( + "/org/apache/momentum/mass.properties", relocator.relocatePath("/org/apache/velocity/mass.properties")); } @Test - public void testCanRelocateAbsClassPathWithExcludes() - { - SimpleRelocator relocator = new SimpleRelocator( "org/apache/velocity", "org/apache/momentum", null, - Arrays.asList( "org/apache/velocity/excluded/*" ) ); - assertTrue( relocator.canRelocatePath( "/org/apache/velocity/mass.properties" ) ); - assertTrue( relocator.canRelocatePath( "org/apache/velocity/mass.properties" ) ); - assertFalse( relocator.canRelocatePath( "/org/apache/velocity/excluded/mass.properties" ) ); - assertFalse( relocator.canRelocatePath( "org/apache/velocity/excluded/mass.properties" ) ); + public void testCanRelocateAbsClassPathWithExcludes() { + SimpleRelocator relocator = new SimpleRelocator( + "org/apache/velocity", "org/apache/momentum", null, Arrays.asList("org/apache/velocity/excluded/*")); + assertTrue(relocator.canRelocatePath("/org/apache/velocity/mass.properties")); + assertTrue(relocator.canRelocatePath("org/apache/velocity/mass.properties")); + assertFalse(relocator.canRelocatePath("/org/apache/velocity/excluded/mass.properties")); + assertFalse(relocator.canRelocatePath("org/apache/velocity/excluded/mass.properties")); } @Test - public void testCanRelocateAbsClassPathWithIncludes() - { - SimpleRelocator relocator = new SimpleRelocator( "org/apache/velocity", "org/apache/momentum", - Arrays.asList( "org/apache/velocity/included/*" ), null ); - assertFalse( relocator.canRelocatePath( "/org/apache/velocity/mass.properties" ) ); - assertFalse( relocator.canRelocatePath( "org/apache/velocity/mass.properties" ) ); - assertTrue( relocator.canRelocatePath( "/org/apache/velocity/included/mass.properties" ) ); - assertTrue( relocator.canRelocatePath( "org/apache/velocity/included/mass.properties" ) ); + public void testCanRelocateAbsClassPathWithIncludes() { + SimpleRelocator relocator = new SimpleRelocator( + "org/apache/velocity", "org/apache/momentum", Arrays.asList("org/apache/velocity/included/*"), null); + assertFalse(relocator.canRelocatePath("/org/apache/velocity/mass.properties")); + assertFalse(relocator.canRelocatePath("org/apache/velocity/mass.properties")); + assertTrue(relocator.canRelocatePath("/org/apache/velocity/included/mass.properties")); + assertTrue(relocator.canRelocatePath("org/apache/velocity/included/mass.properties")); } @Test - public void testRelocatePath() - { + public void testRelocatePath() { SimpleRelocator relocator; - relocator = new SimpleRelocator( "org.foo", null, null, null ); - assertEquals( "hidden/org/foo/bar/Class.class", relocator.relocatePath( "org/foo/bar/Class.class" ) ); + relocator = new SimpleRelocator("org.foo", null, null, null); + assertEquals("hidden/org/foo/bar/Class.class", relocator.relocatePath("org/foo/bar/Class.class")); - relocator = new SimpleRelocator( "org.foo", "private.stuff", null, null ); - assertEquals( "private/stuff/bar/Class.class", relocator.relocatePath( "org/foo/bar/Class.class" ) ); + relocator = new SimpleRelocator("org.foo", "private.stuff", null, null); + assertEquals("private/stuff/bar/Class.class", relocator.relocatePath("org/foo/bar/Class.class")); } @Test - public void testRelocateClass() - { + public void testRelocateClass() { SimpleRelocator relocator; - relocator = new SimpleRelocator( "org.foo", null, null, null ); - assertEquals( "hidden.org.foo.bar.Class", relocator.relocateClass( "org.foo.bar.Class" ) ); + relocator = new SimpleRelocator("org.foo", null, null, null); + assertEquals("hidden.org.foo.bar.Class", relocator.relocateClass("org.foo.bar.Class")); - relocator = new SimpleRelocator( "org.foo", "private.stuff", null, null ); - assertEquals( "private.stuff.bar.Class", relocator.relocateClass( "org.foo.bar.Class" ) ); + relocator = new SimpleRelocator("org.foo", "private.stuff", null, null); + assertEquals("private.stuff.bar.Class", relocator.relocateClass("org.foo.bar.Class")); } @Test - public void testRelocateRawString() - { + public void testRelocateRawString() { SimpleRelocator relocator; - relocator = new SimpleRelocator( "Lorg/foo", "Lhidden/org/foo", null, null, true ); - assertEquals( "(I)Lhidden/org/foo/bar/Class;", relocator.relocatePath( "(I)Lorg/foo/bar/Class;" ) ); + relocator = new SimpleRelocator("Lorg/foo", "Lhidden/org/foo", null, null, true); + assertEquals("(I)Lhidden/org/foo/bar/Class;", relocator.relocatePath("(I)Lorg/foo/bar/Class;")); - relocator = new SimpleRelocator( "^META-INF/org.foo.xml$", "META-INF/hidden.org.foo.xml", null, null, true ); - assertEquals( "META-INF/hidden.org.foo.xml", relocator.relocatePath( "META-INF/org.foo.xml" ) ); + relocator = new SimpleRelocator("^META-INF/org.foo.xml$", "META-INF/hidden.org.foo.xml", null, null, true); + assertEquals("META-INF/hidden.org.foo.xml", relocator.relocatePath("META-INF/org.foo.xml")); } @Test - public void testRelocateMavenFiles() - { - SimpleRelocator relocator = - new SimpleRelocator( "META-INF/maven", "META-INF/shade/maven", null, - Collections.singletonList( "META-INF/maven/com.foo.bar/artifactId/pom.*" ) ); - assertFalse( relocator.canRelocatePath( "META-INF/maven/com.foo.bar/artifactId/pom.properties" ) ); - assertFalse( relocator.canRelocatePath( "META-INF/maven/com.foo.bar/artifactId/pom.xml" ) ); - assertTrue( relocator.canRelocatePath( "META-INF/maven/com/foo/bar/artifactId/pom.properties" ) ); - assertTrue( relocator.canRelocatePath( "META-INF/maven/com/foo/bar/artifactId/pom.xml" ) ); - assertTrue( relocator.canRelocatePath( "META-INF/maven/com-foo-bar/artifactId/pom.properties" ) ); - assertTrue( relocator.canRelocatePath( "META-INF/maven/com-foo-bar/artifactId/pom.xml" ) ); - + public void testRelocateMavenFiles() { + SimpleRelocator relocator = new SimpleRelocator( + "META-INF/maven", + "META-INF/shade/maven", + null, + Collections.singletonList("META-INF/maven/com.foo.bar/artifactId/pom.*")); + assertFalse(relocator.canRelocatePath("META-INF/maven/com.foo.bar/artifactId/pom.properties")); + assertFalse(relocator.canRelocatePath("META-INF/maven/com.foo.bar/artifactId/pom.xml")); + assertTrue(relocator.canRelocatePath("META-INF/maven/com/foo/bar/artifactId/pom.properties")); + assertTrue(relocator.canRelocatePath("META-INF/maven/com/foo/bar/artifactId/pom.xml")); + assertTrue(relocator.canRelocatePath("META-INF/maven/com-foo-bar/artifactId/pom.properties")); + assertTrue(relocator.canRelocatePath("META-INF/maven/com-foo-bar/artifactId/pom.xml")); } - private static final String sourceFile = - "package org.apache.maven.hello;\n" + - "package org.objectweb.asm;\n" + - "\n" + - "import foo.bar.Bar;\n" + - "import zot.baz.Baz;\n" + - "import org.apache.maven.exclude1.Ex1;\n" + - "import org.apache.maven.exclude1.a.b.Ex1AB;\n" + - "import org.apache.maven.sub.exclude2.Ex2;\n" + - "import org.apache.maven.sub.exclude2.c.d.Ex2CD;\n" + - "import org.apache.maven.In;\n" + - "import org.apache.maven.e.InE;\n" + - "import org.apache.maven.f.g.InFG;\n" + - "import java.io.IOException;\n" + - "\n" + - "/**\n" + - " * Also check out {@link org.apache.maven.hello.OtherClass} and {@link\n" + - " * org.apache.maven.hello.YetAnotherClass}\n" + - " */\n" + - "public class MyClass {\n" + - " private org.apache.maven.exclude1.x.X myX;\n" + - " private org.apache.maven.h.H h;\n" + - " private String ioInput;\n" + - "\n" + - " public void doSomething() {\n" + - " String io, val;\n" + - " String noRelocation = \"NoWordBoundaryXXXorg.apache.maven.In\";\n" + - " String relocationPackage = \"org.apache.maven.In\";\n" + - " String relocationPath = \"org/apache/maven/In\";\n" + - " }\n" + - "}\n"; - - private static final String relocatedFile = - "package com.acme.maven.hello;\n" + - "package aj.org.objectweb.asm;\n" + - "\n" + - "import foo.bar.Bar;\n" + - "import zot.baz.Baz;\n" + - "import org.apache.maven.exclude1.Ex1;\n" + - "import org.apache.maven.exclude1.a.b.Ex1AB;\n" + - "import org.apache.maven.sub.exclude2.Ex2;\n" + - "import org.apache.maven.sub.exclude2.c.d.Ex2CD;\n" + - "import com.acme.maven.In;\n" + - "import com.acme.maven.e.InE;\n" + - "import com.acme.maven.f.g.InFG;\n" + - "import java.io.IOException;\n" + - "\n" + - "/**\n" + - " * Also check out {@link com.acme.maven.hello.OtherClass} and {@link\n" + - " * com.acme.maven.hello.YetAnotherClass}\n" + - " */\n" + - "public class MyClass {\n" + - " private org.apache.maven.exclude1.x.X myX;\n" + - " private com.acme.maven.h.H h;\n" + - " private String ioInput;\n" + - "\n" + - " public void doSomething() {\n" + - " String io, val;\n" + - " String noRelocation = \"NoWordBoundaryXXXorg.apache.maven.In\";\n" + - " String relocationPackage = \"com.acme.maven.In\";\n" + - " String relocationPath = \"com/acme/maven/In\";\n" + - " }\n" + - "}\n"; + private static final String sourceFile = "package org.apache.maven.hello;\n" + "package org.objectweb.asm;\n" + + "\n" + + "import foo.bar.Bar;\n" + + "import zot.baz.Baz;\n" + + "import org.apache.maven.exclude1.Ex1;\n" + + "import org.apache.maven.exclude1.a.b.Ex1AB;\n" + + "import org.apache.maven.sub.exclude2.Ex2;\n" + + "import org.apache.maven.sub.exclude2.c.d.Ex2CD;\n" + + "import org.apache.maven.In;\n" + + "import org.apache.maven.e.InE;\n" + + "import org.apache.maven.f.g.InFG;\n" + + "import java.io.IOException;\n" + + "\n" + + "/**\n" + + " * Also check out {@link org.apache.maven.hello.OtherClass} and {@link\n" + + " * org.apache.maven.hello.YetAnotherClass}\n" + + " */\n" + + "public class MyClass {\n" + + " private org.apache.maven.exclude1.x.X myX;\n" + + " private org.apache.maven.h.H h;\n" + + " private String ioInput;\n" + + "\n" + + " public void doSomething() {\n" + + " String io, val;\n" + + " String noRelocation = \"NoWordBoundaryXXXorg.apache.maven.In\";\n" + + " String relocationPackage = \"org.apache.maven.In\";\n" + + " String relocationPath = \"org/apache/maven/In\";\n" + + " }\n" + + "}\n"; + + private static final String relocatedFile = "package com.acme.maven.hello;\n" + "package aj.org.objectweb.asm;\n" + + "\n" + + "import foo.bar.Bar;\n" + + "import zot.baz.Baz;\n" + + "import org.apache.maven.exclude1.Ex1;\n" + + "import org.apache.maven.exclude1.a.b.Ex1AB;\n" + + "import org.apache.maven.sub.exclude2.Ex2;\n" + + "import org.apache.maven.sub.exclude2.c.d.Ex2CD;\n" + + "import com.acme.maven.In;\n" + + "import com.acme.maven.e.InE;\n" + + "import com.acme.maven.f.g.InFG;\n" + + "import java.io.IOException;\n" + + "\n" + + "/**\n" + + " * Also check out {@link com.acme.maven.hello.OtherClass} and {@link\n" + + " * com.acme.maven.hello.YetAnotherClass}\n" + + " */\n" + + "public class MyClass {\n" + + " private org.apache.maven.exclude1.x.X myX;\n" + + " private com.acme.maven.h.H h;\n" + + " private String ioInput;\n" + + "\n" + + " public void doSomething() {\n" + + " String io, val;\n" + + " String noRelocation = \"NoWordBoundaryXXXorg.apache.maven.In\";\n" + + " String relocationPackage = \"com.acme.maven.In\";\n" + + " String relocationPath = \"com/acme/maven/In\";\n" + + " }\n" + + "}\n"; @Test - public void testRelocateSourceWithExcludesRaw() - { - SimpleRelocator relocator = new SimpleRelocator( "org.apache.maven", "com.acme.maven", - Arrays.asList( "foo.bar", "zot.baz" ), - Arrays.asList( "irrelevant.exclude", "org.apache.maven.exclude1", "org.apache.maven.sub.exclude2" ), - true ); - assertEquals( sourceFile, relocator.applyToSourceContent( sourceFile ) ); + public void testRelocateSourceWithExcludesRaw() { + SimpleRelocator relocator = new SimpleRelocator( + "org.apache.maven", + "com.acme.maven", + Arrays.asList("foo.bar", "zot.baz"), + Arrays.asList("irrelevant.exclude", "org.apache.maven.exclude1", "org.apache.maven.sub.exclude2"), + true); + assertEquals(sourceFile, relocator.applyToSourceContent(sourceFile)); } @Test - public void testRelocateSourceWithExcludes() - { + public void testRelocateSourceWithExcludes() { // Main relocator with in-/excludes - SimpleRelocator relocator = new SimpleRelocator( "org.apache.maven", "com.acme.maven", - Arrays.asList( "foo.bar", "zot.baz" ), - Arrays.asList( "irrelevant.exclude", "org.apache.maven.exclude1", "org.apache.maven.sub.exclude2" ) ); + SimpleRelocator relocator = new SimpleRelocator( + "org.apache.maven", + "com.acme.maven", + Arrays.asList("foo.bar", "zot.baz"), + Arrays.asList("irrelevant.exclude", "org.apache.maven.exclude1", "org.apache.maven.sub.exclude2")); // Make sure not to replace variables 'io' and 'ioInput', package 'java.io' - SimpleRelocator ioRelocator = new SimpleRelocator( "io", "shaded.io", null, null ); + SimpleRelocator ioRelocator = new SimpleRelocator("io", "shaded.io", null, null); // Check corner case which was not working in PR #100 - SimpleRelocator asmRelocator = new SimpleRelocator( "org.objectweb.asm", "aj.org.objectweb.asm", null, null ); + SimpleRelocator asmRelocator = new SimpleRelocator("org.objectweb.asm", "aj.org.objectweb.asm", null, null); // Make sure not to replace 'foo' package by path-like 'shaded/foo' - SimpleRelocator fooRelocator = new SimpleRelocator( "foo", "shaded.foo", null, Arrays.asList( "foo.bar" ) ); + SimpleRelocator fooRelocator = new SimpleRelocator("foo", "shaded.foo", null, Arrays.asList("foo.bar")); assertEquals( - relocatedFile, - fooRelocator.applyToSourceContent( - asmRelocator.applyToSourceContent( - ioRelocator.applyToSourceContent( - relocator.applyToSourceContent( sourceFile ) - ) - ) - ) - ); + relocatedFile, + fooRelocator.applyToSourceContent(asmRelocator.applyToSourceContent( + ioRelocator.applyToSourceContent(relocator.applyToSourceContent(sourceFile))))); } } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformerTest.java index f50d4308..6dd9e2a9 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ApacheLicenseResourceTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.util.Locale; @@ -29,37 +28,32 @@ /** * Test for {@link ApacheLicenseResourceTransformer}. - * + * * @author Benjamin Bentmann */ -public class ApacheLicenseResourceTransformerTest -{ +public class ApacheLicenseResourceTransformerTest { private ApacheLicenseResourceTransformer transformer; - static - { + static { /* * NOTE: The Turkish locale has an usual case transformation for the letters "I" and "i", making it a prime * choice to test for improper case-less string comparisions. */ - Locale.setDefault( new Locale( "tr" ) ); + Locale.setDefault(new Locale("tr")); } @Before - public void setUp() - { + public void setUp() { transformer = new ApacheLicenseResourceTransformer(); } @Test - public void testCanTransformResource() - { - assertTrue( transformer.canTransformResource( "META-INF/LICENSE" ) ); - assertTrue( transformer.canTransformResource( "META-INF/LICENSE.TXT" ) ); - assertTrue( transformer.canTransformResource( "META-INF/LICENSE.md" ) ); - assertTrue( transformer.canTransformResource( "META-INF/License.txt" ) ); - assertFalse( transformer.canTransformResource( "META-INF/MANIFEST.MF" ) ); + public void testCanTransformResource() { + assertTrue(transformer.canTransformResource("META-INF/LICENSE")); + assertTrue(transformer.canTransformResource("META-INF/LICENSE.TXT")); + assertTrue(transformer.canTransformResource("META-INF/LICENSE.md")); + assertTrue(transformer.canTransformResource("META-INF/License.txt")); + assertFalse(transformer.canTransformResource("META-INF/MANIFEST.MF")); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerParameterTests.java b/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerParameterTests.java index 64e01910..cd61ca36 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerParameterTests.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerParameterTests.java @@ -1,18 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - -import org.apache.maven.plugins.shade.relocation.Relocator; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.fail; - - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -22,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -31,84 +16,75 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.fail; /** * Tests {@link ApacheLicenseResourceTransformer} parameters. */ -public class ApacheNoticeResourceTransformerParameterTests -{ - - private static final String NOTICE_RESOURCE = "META-INF/NOTICE"; - private ApacheNoticeResourceTransformer subject; +public class ApacheNoticeResourceTransformerParameterTests { + + private static final String NOTICE_RESOURCE = "META-INF/NOTICE"; + private ApacheNoticeResourceTransformer subject; @Before - public void setUp() - { + public void setUp() { subject = new ApacheNoticeResourceTransformer(); } - + @Test - public void testNoParametersShouldNotThrowNullPointerWhenNoInput() - throws IOException - { - processAndFailOnNullPointer( "" ); + public void testNoParametersShouldNotThrowNullPointerWhenNoInput() throws IOException { + processAndFailOnNullPointer(""); } @Test - public void testNoParametersShouldNotThrowNullPointerWhenNoLinesOfInput() - throws IOException - { - processAndFailOnNullPointer( "Some notice text" ); + public void testNoParametersShouldNotThrowNullPointerWhenNoLinesOfInput() throws IOException { + processAndFailOnNullPointer("Some notice text"); } @Test - public void testNoParametersShouldNotThrowNullPointerWhenOneLineOfInput() - throws IOException - { - processAndFailOnNullPointer( "Some notice text\n" ); + public void testNoParametersShouldNotThrowNullPointerWhenOneLineOfInput() throws IOException { + processAndFailOnNullPointer("Some notice text\n"); } @Test - public void testNoParametersShouldNotThrowNullPointerWhenTwoLinesOfInput() - throws IOException - { - processAndFailOnNullPointer( "Some notice text\nSome notice text\n" ); + public void testNoParametersShouldNotThrowNullPointerWhenTwoLinesOfInput() throws IOException { + processAndFailOnNullPointer("Some notice text\nSome notice text\n"); } @Test - public void testNoParametersShouldNotThrowNullPointerWhenLineStartsWithSlashSlash() - throws IOException - { - processAndFailOnNullPointer( "Some notice text\n//Some notice text\n" ); + public void testNoParametersShouldNotThrowNullPointerWhenLineStartsWithSlashSlash() throws IOException { + processAndFailOnNullPointer("Some notice text\n//Some notice text\n"); } @Test - public void testNoParametersShouldNotThrowNullPointerWhenLineIsSlashSlash() - throws IOException - { - processAndFailOnNullPointer( "//\n" ); + public void testNoParametersShouldNotThrowNullPointerWhenLineIsSlashSlash() throws IOException { + processAndFailOnNullPointer("//\n"); } @Test - public void testNoParametersShouldNotThrowNullPointerWhenLineIsEmpty() - throws IOException - { - processAndFailOnNullPointer( "\n" ); + public void testNoParametersShouldNotThrowNullPointerWhenLineIsEmpty() throws IOException { + processAndFailOnNullPointer("\n"); } - private void processAndFailOnNullPointer( final String noticeText ) - throws IOException - { - try - { - final ByteArrayInputStream noticeInputStream = new ByteArrayInputStream( noticeText.getBytes() ); + private void processAndFailOnNullPointer(final String noticeText) throws IOException { + try { + final ByteArrayInputStream noticeInputStream = new ByteArrayInputStream(noticeText.getBytes()); final List emptyList = Collections.emptyList(); - subject.processResource( NOTICE_RESOURCE, noticeInputStream, emptyList, 0 ); + subject.processResource(NOTICE_RESOURCE, noticeInputStream, emptyList, 0); noticeInputStream.close(); - } - catch ( NullPointerException e ) - { - fail( "Null pointer should not be thrown when no parameters are set." ); + } catch (NullPointerException e) { + fail("Null pointer should not be thrown when no parameters are set."); } } } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerTest.java index ffc6f261..f1a569f4 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ApacheNoticeResourceTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.util.Locale; @@ -29,37 +28,32 @@ /** * Test for {@link ApacheNoticeResourceTransformer}. - * + * * @author Benjamin Bentmann */ -public class ApacheNoticeResourceTransformerTest -{ +public class ApacheNoticeResourceTransformerTest { private ApacheNoticeResourceTransformer transformer; - static - { + static { /* * NOTE: The Turkish locale has an usual case transformation for the letters "I" and "i", making it a prime * choice to test for improper case-less string comparisions. */ - Locale.setDefault( new Locale( "tr" ) ); + Locale.setDefault(new Locale("tr")); } @Before - public void setUp() - { + public void setUp() { transformer = new ApacheNoticeResourceTransformer(); } @Test - public void testCanTransformResource() - { - assertTrue( transformer.canTransformResource( "META-INF/NOTICE" ) ); - assertTrue( transformer.canTransformResource( "META-INF/NOTICE.TXT" ) ); - assertTrue( transformer.canTransformResource( "META-INF/NOTICE.md" ) ); - assertTrue( transformer.canTransformResource( "META-INF/Notice.txt" ) ); - assertFalse( transformer.canTransformResource( "META-INF/MANIFEST.MF" ) ); + public void testCanTransformResource() { + assertTrue(transformer.canTransformResource("META-INF/NOTICE")); + assertTrue(transformer.canTransformResource("META-INF/NOTICE.TXT")); + assertTrue(transformer.canTransformResource("META-INF/NOTICE.md")); + assertTrue(transformer.canTransformResource("META-INF/Notice.txt")); + assertFalse(transformer.canTransformResource("META-INF/MANIFEST.MF")); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/AppendingTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/AppendingTransformerTest.java index 2ecf09e2..346e6965 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/AppendingTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/AppendingTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.util.Locale; @@ -29,37 +28,32 @@ /** * Test for {@link AppendingTransformer}. - * + * * @author Benjamin Bentmann */ -public class AppendingTransformerTest -{ +public class AppendingTransformerTest { private AppendingTransformer transformer; - static - { + static { /* * NOTE: The Turkish locale has an usual case transformation for the letters "I" and "i", making it a prime * choice to test for improper case-less string comparisions. */ - Locale.setDefault( new Locale( "tr" ) ); + Locale.setDefault(new Locale("tr")); } @Before - public void setUp() - { + public void setUp() { transformer = new AppendingTransformer(); } @Test - public void testCanTransformResource() - { + public void testCanTransformResource() { transformer.resource = "abcdefghijklmnopqrstuvwxyz"; - assertTrue( transformer.canTransformResource( "abcdefghijklmnopqrstuvwxyz" ) ); - assertTrue( transformer.canTransformResource( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) ); - assertFalse( transformer.canTransformResource( "META-INF/MANIFEST.MF" ) ); + assertTrue(transformer.canTransformResource("abcdefghijklmnopqrstuvwxyz")); + assertTrue(transformer.canTransformResource("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + assertFalse(transformer.canTransformResource("META-INF/MANIFEST.MF")); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformerTest.java index 8e654316..97defa9e 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ComponentsXmlResourceTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; + +import java.io.InputStream; +import java.util.Collections; import org.apache.maven.plugins.shade.relocation.Relocator; import org.codehaus.plexus.util.IOUtil; @@ -27,47 +29,38 @@ import org.junit.Before; import org.junit.Test; -import java.io.InputStream; -import java.util.Collections; - /** * Test for {@link ComponentsXmlResourceTransformer}. * * @author Brett Porter * */ -public class ComponentsXmlResourceTransformerTest -{ +public class ComponentsXmlResourceTransformerTest { private ComponentsXmlResourceTransformer transformer; @Before - public void setUp() - { + public void setUp() { this.transformer = new ComponentsXmlResourceTransformer(); } @Test - public void testConfigurationMerging() - throws Exception - { + public void testConfigurationMerging() throws Exception { - XMLUnit.setNormalizeWhitespace( true ); + XMLUnit.setNormalizeWhitespace(true); - InputStream resourceAsStream = getClass().getResourceAsStream( "/components-1.xml" ); - transformer.processResource( "components-1.xml", resourceAsStream, - Collections. emptyList(), 0 ); + InputStream resourceAsStream = getClass().getResourceAsStream("/components-1.xml"); + transformer.processResource("components-1.xml", resourceAsStream, Collections.emptyList(), 0); resourceAsStream.close(); - InputStream resourceAsStream1 = getClass().getResourceAsStream( "/components-2.xml" ); - transformer.processResource( "components-1.xml", resourceAsStream1, - Collections. emptyList(), 0 ); + InputStream resourceAsStream1 = getClass().getResourceAsStream("/components-2.xml"); + transformer.processResource("components-1.xml", resourceAsStream1, Collections.emptyList(), 0); resourceAsStream1.close(); - final InputStream resourceAsStream2 = getClass().getResourceAsStream( "/components-expected.xml" ); + final InputStream resourceAsStream2 = getClass().getResourceAsStream("/components-expected.xml"); Diff diff = XMLUnit.compareXML( - IOUtil.toString( resourceAsStream2, "UTF-8" ), - IOUtil.toString( transformer.getTransformedResource(), "UTF-8" ) ); - //assertEquals( IOUtil.toString( getClass().getResourceAsStream( "/components-expected.xml" ), "UTF-8" ), + IOUtil.toString(resourceAsStream2, "UTF-8"), + IOUtil.toString(transformer.getTransformedResource(), "UTF-8")); + // assertEquals( IOUtil.toString( getClass().getResourceAsStream( "/components-expected.xml" ), "UTF-8" ), // IOUtil.toString( transformer.getTransformedResource(), "UTF-8" ).replaceAll("\r\n", "\n") ); resourceAsStream2.close(); - XMLAssert.assertXMLIdentical( diff, true ); + XMLAssert.assertXMLIdentical(diff, true); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformerTest.java index ce9dd8d6..153f2315 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/GroovyResourceTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; -import org.junit.Test; +package org.apache.maven.plugins.shade.resource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -33,6 +29,9 @@ import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; +import org.apache.maven.plugins.shade.relocation.Relocator; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -42,118 +41,108 @@ * Test for {@link GroovyResourceTransformer}. * */ -public class GroovyResourceTransformerTest -{ +public class GroovyResourceTransformerTest { - private static InputStream stream( Properties props ) - throws Exception - { + private static InputStream stream(Properties props) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - props.store( baos, null ); - return new ByteArrayInputStream( baos.toByteArray() ); - + props.store(baos, null); + return new ByteArrayInputStream(baos.toByteArray()); } - private static InputStream module( String name, String version, String extensionClasses, - String staticExtensionClasses ) - throws Exception - { + private static InputStream module( + String name, String version, String extensionClasses, String staticExtensionClasses) throws Exception { Properties desc = new Properties(); - desc.setProperty( "moduleName", name ); - desc.setProperty( "moduleVersion", version ); - if ( extensionClasses != null ) - { - desc.setProperty( "extensionClasses", extensionClasses ); + desc.setProperty("moduleName", name); + desc.setProperty("moduleVersion", version); + if (extensionClasses != null) { + desc.setProperty("extensionClasses", extensionClasses); } - if ( staticExtensionClasses != null ) - { - desc.setProperty( "staticExtensionClasses", staticExtensionClasses ); + if (staticExtensionClasses != null) { + desc.setProperty("staticExtensionClasses", staticExtensionClasses); } - return stream( desc ); + return stream(desc); } - private static Properties transform( GroovyResourceTransformer transformer ) - throws Exception - { - File tempJar = File.createTempFile( "shade.", ".jar" ); + private static Properties transform(GroovyResourceTransformer transformer) throws Exception { + File tempJar = File.createTempFile("shade.", ".jar"); tempJar.deleteOnExit(); - try ( FileOutputStream fos = new FileOutputStream( tempJar ); - JarOutputStream jaos = new JarOutputStream( fos ) ) - { - transformer.modifyOutputStream( jaos ); + try (FileOutputStream fos = new FileOutputStream(tempJar); + JarOutputStream jaos = new JarOutputStream(fos)) { + transformer.modifyOutputStream(jaos); } - + Properties desc = null; - try ( JarFile jar = new JarFile( tempJar ) ) - { - ZipEntry entry = jar.getEntry( GroovyResourceTransformer.EXT_MODULE_NAME ); - if ( entry != null ) - { + try (JarFile jar = new JarFile(tempJar)) { + ZipEntry entry = jar.getEntry(GroovyResourceTransformer.EXT_MODULE_NAME); + if (entry != null) { desc = new Properties(); - desc.load( jar.getInputStream( entry ) ); + desc.load(jar.getInputStream(entry)); } } return desc; } @Test - public void testFilter() - { + public void testFilter() { GroovyResourceTransformer transformer = new GroovyResourceTransformer(); - assertTrue( transformer.canTransformResource( GroovyResourceTransformer.EXT_MODULE_NAME ) ); - assertTrue( transformer.canTransformResource( GroovyResourceTransformer.EXT_MODULE_NAME_LEGACY ) ); - assertFalse( transformer.canTransformResource( "somethingElse" ) ); - assertFalse( transformer.canTransformResource( JarFile.MANIFEST_NAME ) ); + assertTrue(transformer.canTransformResource(GroovyResourceTransformer.EXT_MODULE_NAME)); + assertTrue(transformer.canTransformResource(GroovyResourceTransformer.EXT_MODULE_NAME_LEGACY)); + assertFalse(transformer.canTransformResource("somethingElse")); + assertFalse(transformer.canTransformResource(JarFile.MANIFEST_NAME)); } @Test - public void testEmpty() - throws Exception - { + public void testEmpty() throws Exception { GroovyResourceTransformer transformer = new GroovyResourceTransformer(); - assertFalse( transformer.hasTransformedResource() ); - assertNull( transform( transformer ) ); + assertFalse(transformer.hasTransformedResource()); + assertNull(transform(transformer)); } @Test - public void testSpecifyModuleName() - throws Exception - { + public void testSpecifyModuleName() throws Exception { GroovyResourceTransformer transformer = new GroovyResourceTransformer(); - transformer.setExtModuleName( "the-module-name" ); - transformer.setExtModuleVersion( "2.0" ); - transformer.processResource( GroovyResourceTransformer.EXT_MODULE_NAME, - module( "mod1", "1.0", "some.ext", "some.staticExt" ), - Collections.emptyList(), 0 ); - Properties desc = transform( transformer ); - assertEquals( "the-module-name", desc.getProperty( "moduleName" ) ); - assertEquals( "2.0", desc.getProperty( "moduleVersion" ) ); - assertEquals( "some.ext", desc.getProperty( "extensionClasses" ) ); - assertEquals( "some.staticExt", desc.getProperty( "staticExtensionClasses" ) ); + transformer.setExtModuleName("the-module-name"); + transformer.setExtModuleVersion("2.0"); + transformer.processResource( + GroovyResourceTransformer.EXT_MODULE_NAME, + module("mod1", "1.0", "some.ext", "some.staticExt"), + Collections.emptyList(), + 0); + Properties desc = transform(transformer); + assertEquals("the-module-name", desc.getProperty("moduleName")); + assertEquals("2.0", desc.getProperty("moduleVersion")); + assertEquals("some.ext", desc.getProperty("extensionClasses")); + assertEquals("some.staticExt", desc.getProperty("staticExtensionClasses")); } @Test - public void testConcatenation() - throws Exception - { + public void testConcatenation() throws Exception { GroovyResourceTransformer transformer = new GroovyResourceTransformer(); - transformer.processResource( GroovyResourceTransformer.EXT_MODULE_NAME, - module( "mod1", "1.0", "some.ext1", null ), - Collections.emptyList(), 0 ); - transformer.processResource( GroovyResourceTransformer.EXT_MODULE_NAME, - module( "mod2", "1.0", null, "some.staticExt1" ), - Collections.emptyList(), 0 ); - transformer.processResource( GroovyResourceTransformer.EXT_MODULE_NAME, - module( "mod3", "1.0", "", "" ), - Collections.emptyList(), 0 ); - transformer.processResource( GroovyResourceTransformer.EXT_MODULE_NAME, - module( "mod4", "1.0", "some.ext2", "some.staticExt2" ), - Collections.emptyList(), 0 ); - Properties desc = transform( transformer ); - assertEquals( "no-module-name", desc.getProperty( "moduleName" ) ); - assertEquals( "1.0", desc.getProperty( "moduleVersion" ) ); - assertEquals( "some.ext1,some.ext2", desc.getProperty( "extensionClasses" ) ); - assertEquals( "some.staticExt1,some.staticExt2", desc.getProperty( "staticExtensionClasses" ) ); + transformer.processResource( + GroovyResourceTransformer.EXT_MODULE_NAME, + module("mod1", "1.0", "some.ext1", null), + Collections.emptyList(), + 0); + transformer.processResource( + GroovyResourceTransformer.EXT_MODULE_NAME, + module("mod2", "1.0", null, "some.staticExt1"), + Collections.emptyList(), + 0); + transformer.processResource( + GroovyResourceTransformer.EXT_MODULE_NAME, + module("mod3", "1.0", "", ""), + Collections.emptyList(), + 0); + transformer.processResource( + GroovyResourceTransformer.EXT_MODULE_NAME, + module("mod4", "1.0", "some.ext2", "some.staticExt2"), + Collections.emptyList(), + 0); + Properties desc = transform(transformer); + assertEquals("no-module-name", desc.getProperty("moduleName")); + assertEquals("1.0", desc.getProperty("moduleVersion")); + assertEquals("some.ext1,some.ext2", desc.getProperty("extensionClasses")); + assertEquals("some.staticExt1,some.staticExt2", desc.getProperty("staticExtensionClasses")); } } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformerTest.java index 198d7e1f..48821ff7 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ManifestResourceTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.assertEquals; +package org.apache.maven.plugins.shade.resource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -39,132 +36,119 @@ import org.junit.Before; import org.junit.Test; -public class ManifestResourceTransformerTest -{ +import static org.junit.Assert.assertEquals; + +public class ManifestResourceTransformerTest { private ManifestResourceTransformer transformer; - + @Before - public void setUp() - { + public void setUp() { transformer = new ManifestResourceTransformer(); } @Test - public void rewriteDefaultAttributes() throws Exception - { + public void rewriteDefaultAttributes() throws Exception { final Manifest manifest = new Manifest(); final Attributes attributes = manifest.getMainAttributes(); attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); - attributes.putValue("Export-Package", - "javax.decorator;version=\"2.0\";uses:=\"javax.enterprise.inject\"," + - "javax.enterprise.context;version=\"2.0\";uses:=\"javax.enterprise.util,javax.inject\""); - attributes.putValue("Import-Package", - "javax.el,javax.enterprise.context;version=\"[2.0,3)\""); - attributes.putValue("Provide-Capability", - "osgi.contract;osgi.contract=JavaCDI;uses:=\"" + - "javax.enterprise.context,javax.enterprise.context.spi,javax.enterprise.context.control," + - "javax.enterprise.util,javax.enterprise.inject,javax.enterprise.inject.spi," + - "javax.enterprise.inject.spi.configurator,javax.enterprise.inject.literal," + - "javax.enterprise.inject.se,javax.enterprise.event,javax.decorator\";" + - "version:List=\"2.0,1.2,1.1,1.0\""); - attributes.putValue("Require-Capability", - "osgi.serviceloader;" + - "filter:=\"(osgi.serviceloader=javax.enterprise.inject.se.SeContainerInitializer)\";" + - "cardinality:=multiple," + - "osgi.serviceloader;" + - "filter:=\"(osgi.serviceloader=javax.enterprise.inject.spi.CDIProvider)\";" + - "cardinality:=multiple,osgi.extender;" + - "filter:=\"(osgi.extender=osgi.serviceloader.processor)\"," + - "osgi.contract;osgi.contract=JavaEL;filter:=\"(&(osgi.contract=JavaEL)(version=2.2.0))\"," + - "osgi.contract;osgi.contract=JavaInterceptor;" + - "filter:=\"(&(osgi.contract=JavaInterceptor)(version=1.2.0))\"," + - "osgi.contract;osgi.contract=JavaInject;" + - "filter:=\"(&(osgi.contract=JavaInject)(version=1.0.0))\"," + - "osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.8))\""); - - List relocators = - Collections.singletonList( new SimpleRelocator( "javax", "jakarta", - Collections.emptyList(), - Collections.emptyList() ) ); - - final ByteArrayOutputStream out = transform( manifest, relocators ); + attributes.putValue( + "Export-Package", + "javax.decorator;version=\"2.0\";uses:=\"javax.enterprise.inject\"," + + "javax.enterprise.context;version=\"2.0\";uses:=\"javax.enterprise.util,javax.inject\""); + attributes.putValue("Import-Package", "javax.el,javax.enterprise.context;version=\"[2.0,3)\""); + attributes.putValue( + "Provide-Capability", + "osgi.contract;osgi.contract=JavaCDI;uses:=\"" + + "javax.enterprise.context,javax.enterprise.context.spi,javax.enterprise.context.control," + + "javax.enterprise.util,javax.enterprise.inject,javax.enterprise.inject.spi," + + "javax.enterprise.inject.spi.configurator,javax.enterprise.inject.literal," + + "javax.enterprise.inject.se,javax.enterprise.event,javax.decorator\";" + + "version:List=\"2.0,1.2,1.1,1.0\""); + attributes.putValue( + "Require-Capability", + "osgi.serviceloader;" + + "filter:=\"(osgi.serviceloader=javax.enterprise.inject.se.SeContainerInitializer)\";" + + "cardinality:=multiple," + + "osgi.serviceloader;" + + "filter:=\"(osgi.serviceloader=javax.enterprise.inject.spi.CDIProvider)\";" + + "cardinality:=multiple,osgi.extender;" + + "filter:=\"(osgi.extender=osgi.serviceloader.processor)\"," + + "osgi.contract;osgi.contract=JavaEL;filter:=\"(&(osgi.contract=JavaEL)(version=2.2.0))\"," + + "osgi.contract;osgi.contract=JavaInterceptor;" + + "filter:=\"(&(osgi.contract=JavaInterceptor)(version=1.2.0))\"," + + "osgi.contract;osgi.contract=JavaInject;" + + "filter:=\"(&(osgi.contract=JavaInject)(version=1.0.0))\"," + + "osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.8))\""); + + List relocators = Collections.singletonList(new SimpleRelocator( + "javax", "jakarta", Collections.emptyList(), Collections.emptyList())); + + final ByteArrayOutputStream out = transform(manifest, relocators); - try ( final JarInputStream jis = new JarInputStream( new ByteArrayInputStream( out.toByteArray() ) ) ) - { + try (final JarInputStream jis = new JarInputStream(new ByteArrayInputStream(out.toByteArray()))) { final Attributes attrs = jis.getManifest().getMainAttributes(); assertEquals( - "jakarta.decorator;version=\"2.0\";uses:=\"jakarta.enterprise.inject\"," + - "jakarta.enterprise.context;version=\"2.0\";uses:=\"jakarta.enterprise.util," + - "jakarta.inject\"", + "jakarta.decorator;version=\"2.0\";uses:=\"jakarta.enterprise.inject\"," + + "jakarta.enterprise.context;version=\"2.0\";uses:=\"jakarta.enterprise.util," + + "jakarta.inject\"", attrs.getValue("Export-Package")); - assertEquals("jakarta.el,jakarta.enterprise.context;version=\"[2.0,3)\"", - attrs.getValue("Import-Package")); + assertEquals("jakarta.el,jakarta.enterprise.context;version=\"[2.0,3)\"", attrs.getValue("Import-Package")); assertEquals( - "osgi.contract;osgi.contract=JavaCDI;" + - "uses:=\"jakarta.enterprise.context," + - "jakarta.enterprise.context.spi,jakarta.enterprise.context.control," + - "jakarta.enterprise.util,jakarta.enterprise.inject,jakarta.enterprise.inject.spi," + - "jakarta.enterprise.inject.spi.configurator,jakarta.enterprise.inject.literal," + - "jakarta.enterprise.inject.se,jakarta.enterprise.event," + - "jakarta.decorator\";version:List=\"2.0,1.2,1.1,1.0\"", + "osgi.contract;osgi.contract=JavaCDI;" + "uses:=\"jakarta.enterprise.context," + + "jakarta.enterprise.context.spi,jakarta.enterprise.context.control," + + "jakarta.enterprise.util,jakarta.enterprise.inject,jakarta.enterprise.inject.spi," + + "jakarta.enterprise.inject.spi.configurator,jakarta.enterprise.inject.literal," + + "jakarta.enterprise.inject.se,jakarta.enterprise.event," + + "jakarta.decorator\";version:List=\"2.0,1.2,1.1,1.0\"", attrs.getValue("Provide-Capability")); assertEquals( - "osgi.serviceloader;" + - "filter:=\"(osgi.serviceloader=jakarta.enterprise.inject.se.SeContainerInitializer)\";" + - "cardinality:=multiple,osgi.serviceloader;" + - "filter:=\"(osgi.serviceloader=jakarta.enterprise.inject.spi.CDIProvider)\";" + - "cardinality:=multiple,osgi.extender;" + - "filter:=\"(osgi.extender=osgi.serviceloader.processor)\"," + - "osgi.contract;osgi.contract=JavaEL;filter:=\"(&(osgi.contract=JavaEL)(version=2.2.0))\"," + - "osgi.contract;osgi.contract=JavaInterceptor;" + - "filter:=\"(&(osgi.contract=JavaInterceptor)(version=1.2.0))\"," + - "osgi.contract;osgi.contract=JavaInject;" + - "filter:=\"(&(osgi.contract=JavaInject)(version=1.0.0))\"," + - "osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.8))\"", + "osgi.serviceloader;" + + "filter:=\"(osgi.serviceloader=jakarta.enterprise.inject.se.SeContainerInitializer)\";" + + "cardinality:=multiple,osgi.serviceloader;" + + "filter:=\"(osgi.serviceloader=jakarta.enterprise.inject.spi.CDIProvider)\";" + + "cardinality:=multiple,osgi.extender;" + + "filter:=\"(osgi.extender=osgi.serviceloader.processor)\"," + + "osgi.contract;osgi.contract=JavaEL;filter:=\"(&(osgi.contract=JavaEL)(version=2.2.0))\"," + + "osgi.contract;osgi.contract=JavaInterceptor;" + + "filter:=\"(&(osgi.contract=JavaInterceptor)(version=1.2.0))\"," + + "osgi.contract;osgi.contract=JavaInject;" + + "filter:=\"(&(osgi.contract=JavaInject)(version=1.0.0))\"," + + "osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.8))\"", attrs.getValue("Require-Capability")); } } - + @Test - public void rewriteAdditionalAttributes() throws Exception - { + public void rewriteAdditionalAttributes() throws Exception { final Manifest manifest = new Manifest(); final Attributes attributes = manifest.getMainAttributes(); attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); - attributes.putValue("description-custom", - "This jar uses javax packages"); - - List relocators = - Collections.singletonList( new SimpleRelocator( "javax", "jakarta", - Collections.emptyList(), - Collections.emptyList() ) ); - - transformer.setAdditionalAttributes( Arrays.asList("description-custom", "attribute-unknown") ); - final ByteArrayOutputStream out = transform( manifest, relocators ); + attributes.putValue("description-custom", "This jar uses javax packages"); + + List relocators = Collections.singletonList(new SimpleRelocator( + "javax", "jakarta", Collections.emptyList(), Collections.emptyList())); + + transformer.setAdditionalAttributes(Arrays.asList("description-custom", "attribute-unknown")); + final ByteArrayOutputStream out = transform(manifest, relocators); - try ( final JarInputStream jis = new JarInputStream( new ByteArrayInputStream( out.toByteArray() ) ) ) - { + try (final JarInputStream jis = new JarInputStream(new ByteArrayInputStream(out.toByteArray()))) { final Attributes attrs = jis.getManifest().getMainAttributes(); - assertEquals( "This jar uses jakarta packages", attrs.getValue( "description-custom" ) ); + assertEquals("This jar uses jakarta packages", attrs.getValue("description-custom")); } } - private ByteArrayOutputStream transform( final Manifest manifest, List relocators ) - throws IOException - { + private ByteArrayOutputStream transform(final Manifest manifest, List relocators) throws IOException { final ByteArrayOutputStream mboas = new ByteArrayOutputStream(); - try ( final OutputStream mos = mboas ) - { - manifest.write( mos ); + try (final OutputStream mos = mboas) { + manifest.write(mos); } - transformer.processResource( JarFile.MANIFEST_NAME, new ByteArrayInputStream( mboas.toByteArray() ), - relocators, 0 ); + transformer.processResource( + JarFile.MANIFEST_NAME, new ByteArrayInputStream(mboas.toByteArray()), relocators, 0); final ByteArrayOutputStream out = new ByteArrayOutputStream(); - try ( final JarOutputStream jarOutputStream = new JarOutputStream( out ) ) - { - transformer.modifyOutputStream( jarOutputStream ); + try (final JarOutputStream jarOutputStream = new JarOutputStream(out)) { + transformer.modifyOutputStream(jarOutputStream); } return out; } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java b/src/test/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java index c5b7ba8a..8b62b876 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ReproducibleResourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,26 +16,24 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugins.shade.relocation.Relocator; +package org.apache.maven.plugins.shade.resource; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.maven.plugins.shade.relocation.Relocator; + /** * Copy of original interface necessary to MSHADE-363_old-plugin IT: * CustomReproducibleResourceTransformer is built with ReproducibleResourceTransformer interface provided by * recent maven-shade-plugin, but older maven-shade-plugin 3.2.2 will be used at runtime in the * MSHADE-363_old-plugin IT, an older that does not provide the interface. Without the interface copy * in the custom resource transformer code, this would lead to ClassNotFoundException... - * + * * @since 3.2.4 * @see org.apache.maven.plugins.shade.custom.CustomReproducibleResourceTransformer */ -public interface ReproducibleResourceTransformer - extends ResourceTransformer -{ - void processResource( String resource, InputStream is, List relocators, long time ) - throws IOException; +public interface ReproducibleResourceTransformer extends ResourceTransformer { + void processResource(String resource, InputStream is, List relocators, long time) throws IOException; } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformerTest.java index 272685b7..11c9375e 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ResourceBundleAppendingTransformerTest.java @@ -1,55 +1,50 @@ -package org.apache.maven.plugins.shade.resource; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -public class ResourceBundleAppendingTransformerTest -{ - private ResourceBundleAppendingTransformer transformer; - - @Before - public void setUp() - { - transformer = new ResourceBundleAppendingTransformer(); - } - - @Test - public void testCanTransformResource() - { - transformer.setBasename( "a/b/c/ButtonLabel" ); - - assertTrue( transformer.canTransformResource( "a/b/c/ButtonLabel.properties" ) ); - assertTrue( transformer.canTransformResource( "a/b/c/ButtonLabel_en.properties" ) ); - assertTrue( transformer.canTransformResource( "a/b/c/ButtonLabel_en_US.properties" ) ); - assertTrue( transformer.canTransformResource( "a/b/c/ButtonLabel_fr.properties" ) ); - assertTrue( transformer.canTransformResource( "a/b/c/ButtonLabel_fr_CA.properties" ) ); - assertTrue( transformer.canTransformResource( "a/b/c/ButtonLabel_fr_CA_UNIX.properties" ) ); - - assertFalse( transformer.canTransformResource( "a/b/c/ButtonLabel.class" ) ); - assertFalse( transformer.canTransformResource( "c/ButtonLabel.properties" ) ); - assertFalse( transformer.canTransformResource( "ButtonLabel.properties" ) ); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.shade.resource; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ResourceBundleAppendingTransformerTest { + private ResourceBundleAppendingTransformer transformer; + + @Before + public void setUp() { + transformer = new ResourceBundleAppendingTransformer(); + } + + @Test + public void testCanTransformResource() { + transformer.setBasename("a/b/c/ButtonLabel"); + + assertTrue(transformer.canTransformResource("a/b/c/ButtonLabel.properties")); + assertTrue(transformer.canTransformResource("a/b/c/ButtonLabel_en.properties")); + assertTrue(transformer.canTransformResource("a/b/c/ButtonLabel_en_US.properties")); + assertTrue(transformer.canTransformResource("a/b/c/ButtonLabel_fr.properties")); + assertTrue(transformer.canTransformResource("a/b/c/ButtonLabel_fr_CA.properties")); + assertTrue(transformer.canTransformResource("a/b/c/ButtonLabel_fr_CA_UNIX.properties")); + + assertFalse(transformer.canTransformResource("a/b/c/ButtonLabel.class")); + assertFalse(transformer.canTransformResource("c/ButtonLabel.properties")); + assertFalse(transformer.canTransformResource("ButtonLabel.properties")); + } +} diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/ServiceResourceTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/ServiceResourceTransformerTest.java index 7310e072..693ba499 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/ServiceResourceTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/ServiceResourceTransformerTest.java @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -16,13 +16,8 @@ * specific language governing permissions and limitations * under the License. */ - package org.apache.maven.plugins.shade.resource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; @@ -41,6 +36,10 @@ import org.apache.maven.plugins.shade.relocation.SimpleRelocator; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + /** * Test for handling META-INF/service/... */ @@ -52,33 +51,32 @@ public class ServiceResourceTransformerTest { @Test public void relocatedClasses() throws Exception { SimpleRelocator relocator = - new SimpleRelocator( "org.foo", "borg.foo", null, Arrays.asList( "org.foo.exclude.*" ) ); - relocators.add( relocator ); + new SimpleRelocator("org.foo", "borg.foo", null, Arrays.asList("org.foo.exclude.*")); + relocators.add(relocator); String content = "org.foo.Service\norg.foo.exclude.OtherService\n"; - byte[] contentBytes = content.getBytes( StandardCharsets.UTF_8 ); - InputStream contentStream = new ByteArrayInputStream( contentBytes ); + byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); + InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentResource = "META-INF/services/org.foo.something.another"; String contentResourceShaded = "META-INF/services/borg.foo.something.another"; ServicesResourceTransformer xformer = new ServicesResourceTransformer(); - xformer.processResource( contentResource, contentStream, relocators, 0 ); + xformer.processResource(contentResource, contentStream, relocators, 0); contentStream.close(); File tempJar = File.createTempFile("shade.", ".jar"); tempJar.deleteOnExit(); - FileOutputStream fos = new FileOutputStream( tempJar ); - try ( JarOutputStream jos = new JarOutputStream( fos ) ) { - xformer.modifyOutputStream( jos ); + FileOutputStream fos = new FileOutputStream(tempJar); + try (JarOutputStream jos = new JarOutputStream(fos)) { + xformer.modifyOutputStream(jos); jos.close(); - - JarFile jarFile = new JarFile( tempJar ); - JarEntry jarEntry = jarFile.getJarEntry( contentResourceShaded ); - assertNotNull( jarEntry ); - try ( InputStream entryStream = jarFile.getInputStream( jarEntry ) ) { - String xformedContent = IOUtils.toString( entryStream, "utf-8" ); - assertEquals( "borg.foo.Service" + NEWLINE - + "org.foo.exclude.OtherService" + NEWLINE, xformedContent ); + + JarFile jarFile = new JarFile(tempJar); + JarEntry jarEntry = jarFile.getJarEntry(contentResourceShaded); + assertNotNull(jarEntry); + try (InputStream entryStream = jarFile.getInputStream(jarEntry)) { + String xformedContent = IOUtils.toString(entryStream, "utf-8"); + assertEquals("borg.foo.Service" + NEWLINE + "org.foo.exclude.OtherService" + NEWLINE, xformedContent); } finally { jarFile.close(); } @@ -90,38 +88,38 @@ public void relocatedClasses() throws Exception { @Test public void mergeRelocatedFiles() throws Exception { SimpleRelocator relocator = - new SimpleRelocator( "org.foo", "borg.foo", null, Collections.singletonList("org.foo.exclude.*")); - relocators.add( relocator ); + new SimpleRelocator("org.foo", "borg.foo", null, Collections.singletonList("org.foo.exclude.*")); + relocators.add(relocator); String content = "org.foo.Service" + NEWLINE + "org.foo.exclude.OtherService" + NEWLINE; String contentShaded = "borg.foo.Service" + NEWLINE + "org.foo.exclude.OtherService" + NEWLINE; - byte[] contentBytes = content.getBytes( StandardCharsets.UTF_8 ); + byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); String contentResource = "META-INF/services/org.foo.something.another"; String contentResourceShaded = "META-INF/services/borg.foo.something.another"; ServicesResourceTransformer xformer = new ServicesResourceTransformer(); - try (InputStream contentStream = new ByteArrayInputStream( contentBytes )) { + try (InputStream contentStream = new ByteArrayInputStream(contentBytes)) { xformer.processResource(contentResource, contentStream, relocators, 0); } - try (InputStream contentStream = new ByteArrayInputStream( contentBytes )) { + try (InputStream contentStream = new ByteArrayInputStream(contentBytes)) { xformer.processResource(contentResourceShaded, contentStream, relocators, 0); } File tempJar = File.createTempFile("shade.", ".jar"); tempJar.deleteOnExit(); - FileOutputStream fos = new FileOutputStream( tempJar ); - try ( JarOutputStream jos = new JarOutputStream( fos ) ) { - xformer.modifyOutputStream( jos ); + FileOutputStream fos = new FileOutputStream(tempJar); + try (JarOutputStream jos = new JarOutputStream(fos)) { + xformer.modifyOutputStream(jos); jos.close(); - JarFile jarFile = new JarFile( tempJar ); - JarEntry jarEntry = jarFile.getJarEntry( contentResourceShaded ); - assertNotNull( jarEntry ); - try ( InputStream entryStream = jarFile.getInputStream( jarEntry ) ) { - String xformedContent = IOUtils.toString( entryStream, StandardCharsets.UTF_8); - assertEquals( contentShaded, xformedContent ); + JarFile jarFile = new JarFile(tempJar); + JarEntry jarEntry = jarFile.getJarEntry(contentResourceShaded); + assertNotNull(jarEntry); + try (InputStream entryStream = jarFile.getInputStream(jarEntry)) { + String xformedContent = IOUtils.toString(entryStream, StandardCharsets.UTF_8); + assertEquals(contentShaded, xformedContent); } finally { jarFile.close(); } @@ -129,35 +127,34 @@ public void mergeRelocatedFiles() throws Exception { tempJar.delete(); } } - + @Test public void concatanationAppliedMultipleTimes() throws Exception { - SimpleRelocator relocator = - new SimpleRelocator( "org.eclipse", "org.eclipse1234", null, null ); - relocators.add( relocator ); - + SimpleRelocator relocator = new SimpleRelocator("org.eclipse", "org.eclipse1234", null, null); + relocators.add(relocator); + String content = "org.eclipse.osgi.launch.EquinoxFactory\n"; - byte[] contentBytes = content.getBytes( "UTF-8" ); - InputStream contentStream = new ByteArrayInputStream( contentBytes ); + byte[] contentBytes = content.getBytes("UTF-8"); + InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentResource = "META-INF/services/org.osgi.framework.launch.FrameworkFactory"; ServicesResourceTransformer xformer = new ServicesResourceTransformer(); - xformer.processResource( contentResource, contentStream, relocators, 0 ); + xformer.processResource(contentResource, contentStream, relocators, 0); contentStream.close(); File tempJar = File.createTempFile("shade.", ".jar"); tempJar.deleteOnExit(); - FileOutputStream fos = new FileOutputStream( tempJar ); - try ( JarOutputStream jos = new JarOutputStream( fos ) ) { - xformer.modifyOutputStream( jos ); + FileOutputStream fos = new FileOutputStream(tempJar); + try (JarOutputStream jos = new JarOutputStream(fos)) { + xformer.modifyOutputStream(jos); jos.close(); - - JarFile jarFile = new JarFile( tempJar ); - JarEntry jarEntry = jarFile.getJarEntry( contentResource ); - assertNotNull( jarEntry ); - try ( InputStream entryStream = jarFile.getInputStream( jarEntry ) ) { + + JarFile jarFile = new JarFile(tempJar); + JarEntry jarEntry = jarFile.getJarEntry(contentResource); + assertNotNull(jarEntry); + try (InputStream entryStream = jarFile.getInputStream(jarEntry)) { String xformedContent = IOUtils.toString(entryStream, StandardCharsets.UTF_8); - assertEquals( "org.eclipse1234.osgi.launch.EquinoxFactory" + NEWLINE, xformedContent ); + assertEquals("org.eclipse1234.osgi.launch.EquinoxFactory" + NEWLINE, xformedContent); } finally { jarFile.close(); } @@ -169,53 +166,49 @@ public void concatanationAppliedMultipleTimes() throws Exception { @Test public void concatenation() throws Exception { SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null, null); - relocators.add( relocator ); - + relocators.add(relocator); + String content = "org.foo.Service\n"; - byte[] contentBytes = content.getBytes( StandardCharsets.UTF_8 ); - InputStream contentStream = new ByteArrayInputStream( contentBytes ); + byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); + InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentResource = "META-INF/services/org.something.another"; ServicesResourceTransformer xformer = new ServicesResourceTransformer(); - xformer.processResource( contentResource, contentStream, relocators, 0 ); + xformer.processResource(contentResource, contentStream, relocators, 0); contentStream.close(); content = "org.blah.Service\n"; - contentBytes = content.getBytes( StandardCharsets.UTF_8 ); - contentStream = new ByteArrayInputStream( contentBytes ); + contentBytes = content.getBytes(StandardCharsets.UTF_8); + contentStream = new ByteArrayInputStream(contentBytes); contentResource = "META-INF/services/org.something.another"; - xformer.processResource( contentResource, contentStream, relocators, 0 ); + xformer.processResource(contentResource, contentStream, relocators, 0); contentStream.close(); File tempJar = File.createTempFile("shade.", ".jar"); tempJar.deleteOnExit(); - FileOutputStream fos = new FileOutputStream( tempJar ); - try ( JarOutputStream jos = new JarOutputStream( fos ) ) { - xformer.modifyOutputStream( jos ); + FileOutputStream fos = new FileOutputStream(tempJar); + try (JarOutputStream jos = new JarOutputStream(fos)) { + xformer.modifyOutputStream(jos); jos.close(); - JarFile jarFile = new JarFile( tempJar ); - JarEntry jarEntry = jarFile.getJarEntry( contentResource ); - assertNotNull( jarEntry ); - try ( InputStream entryStream = jarFile.getInputStream( jarEntry ) ) { + JarFile jarFile = new JarFile(tempJar); + JarEntry jarEntry = jarFile.getJarEntry(contentResource); + assertNotNull(jarEntry); + try (InputStream entryStream = jarFile.getInputStream(jarEntry)) { String xformedContent = IOUtils.toString(entryStream, "utf-8"); // must be two lines, with our two classes. String[] classes = xformedContent.split("\r?\n"); boolean h1 = false; boolean h2 = false; - for ( String name : classes ) - { - if ("org.blah.Service".equals( name )) - { + for (String name : classes) { + if ("org.blah.Service".equals(name)) { h1 = true; - } - else if ("borg.foo.Service".equals( name )) - { + } else if ("borg.foo.Service".equals(name)) { h2 = true; } } - assertTrue( h1 && h2 ); + assertTrue(h1 && h2); } finally { jarFile.close(); } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformerTest.java index a7793c45..9d4f391e 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/XmlAppendingTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.shade.resource; import java.util.Locale; @@ -29,38 +28,33 @@ /** * Test for {@link XmlAppendingTransformer}. - * + * * @author Benjamin Bentmann * */ -public class XmlAppendingTransformerTest -{ +public class XmlAppendingTransformerTest { private XmlAppendingTransformer transformer; - static - { + static { /* * NOTE: The Turkish locale has an usual case transformation for the letters "I" and "i", making it a prime * choice to test for improper case-less string comparisions. */ - Locale.setDefault( new Locale( "tr" ) ); + Locale.setDefault(new Locale("tr")); } @Before - public void setUp() - { + public void setUp() { transformer = new XmlAppendingTransformer(); } @Test - public void testCanTransformResource() - { + public void testCanTransformResource() { transformer.resource = "abcdefghijklmnopqrstuvwxyz"; - assertTrue( transformer.canTransformResource( "abcdefghijklmnopqrstuvwxyz" ) ); - assertTrue( transformer.canTransformResource( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) ); - assertFalse( transformer.canTransformResource( "META-INF/MANIFEST.MF" ) ); + assertTrue(transformer.canTransformResource("abcdefghijklmnopqrstuvwxyz")); + assertTrue(transformer.canTransformResource("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + assertFalse(transformer.canTransformResource("META-INF/MANIFEST.MF")); } - } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformerTest.java b/src/test/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformerTest.java index 330c3794..26b8af49 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformerTest.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/properties/PropertiesTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.properties; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +package org.apache.maven.plugins.shade.resource.properties; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; @@ -40,34 +35,34 @@ import org.junit.Test; import org.junit.rules.TestRule; -public class PropertiesTransformerTest -{ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PropertiesTransformerTest { @Rule public final TestRule tester = new TransformerTesterRule(); @Test - public void propertiesRewritingIsStable() throws IOException - { + public void propertiesRewritingIsStable() throws IOException { final Properties properties = new SortedProperties(); properties.setProperty("a", "1"); properties.setProperty("b", "2"); final ByteArrayOutputStream os = new ByteArrayOutputStream(); final BufferedWriter writer = new SkipPropertiesDateLineWriter( - new OutputStreamWriter( new NoCloseOutputStream( os ), StandardCharsets.ISO_8859_1 ) ); - properties.store( writer, " Merged by maven-shade-plugin" ); + new OutputStreamWriter(new NoCloseOutputStream(os), StandardCharsets.ISO_8859_1)); + properties.store(writer, " Merged by maven-shade-plugin"); writer.close(); os.close(); assertEquals( - "# Merged by maven-shade-plugin\n" + - "a=1\n" + - "b=2\n", os.toString("UTF-8").replace( System.lineSeparator(), "\n" ) ); + "# Merged by maven-shade-plugin\n" + "a=1\n" + "b=2\n", + os.toString("UTF-8").replace(System.lineSeparator(), "\n")); } @Test - public void canTransform() - { + public void canTransform() { final PropertiesTransformer transformer = new PropertiesTransformer(); transformer.setResource("foo/bar/my.properties"); assertTrue(transformer.canTransformResource("foo/bar/my.properties")); @@ -79,65 +74,53 @@ public void canTransform() transformer = PropertiesTransformer.class, configuration = @Property(name = "resource", value = "foo/bar/my.properties"), visited = { - @Resource(path = "foo/bar/my.properties", content = "a=b"), - @Resource(path = "foo/bar/my.properties", content = "c=d"), + @Resource(path = "foo/bar/my.properties", content = "a=b"), + @Resource(path = "foo/bar/my.properties", content = "c=d"), }, - expected = @Resource(path = "foo/bar/my.properties", content = "#.*\na=b\nc=d\n") - ) - public void mergeWithoutOverlap() - { - } + expected = @Resource(path = "foo/bar/my.properties", content = "#.*\na=b\nc=d\n")) + public void mergeWithoutOverlap() {} @Test @TransformerTest( transformer = PropertiesTransformer.class, configuration = { - @Property(name = "resource", value = "foo/bar/my.properties"), - @Property(name = "ordinalKey", value = "priority") + @Property(name = "resource", value = "foo/bar/my.properties"), + @Property(name = "ordinalKey", value = "priority") }, visited = { - @Resource(path = "foo/bar/my.properties", content = "a=d\npriority=3"), - @Resource(path = "foo/bar/my.properties", content = "a=b\npriority=1"), - @Resource(path = "foo/bar/my.properties", content = "a=c\npriority=2"), + @Resource(path = "foo/bar/my.properties", content = "a=d\npriority=3"), + @Resource(path = "foo/bar/my.properties", content = "a=b\npriority=1"), + @Resource(path = "foo/bar/my.properties", content = "a=c\npriority=2"), }, - expected = @Resource(path = "foo/bar/my.properties", content = "#.*\na=d\n") - ) - public void mergeWithOverlap() - { - } + expected = @Resource(path = "foo/bar/my.properties", content = "#.*\na=d\n")) + public void mergeWithOverlap() {} @Test @TransformerTest( transformer = PropertiesTransformer.class, configuration = { - @Property(name = "resource", value = "foo/bar/my.properties"), - @Property(name = "alreadyMergedKey", value = "complete") + @Property(name = "resource", value = "foo/bar/my.properties"), + @Property(name = "alreadyMergedKey", value = "complete") }, visited = { - @Resource(path = "foo/bar/my.properties", content = "a=b\ncomplete=true"), - @Resource(path = "foo/bar/my.properties", content = "a=c\npriority=2"), + @Resource(path = "foo/bar/my.properties", content = "a=b\ncomplete=true"), + @Resource(path = "foo/bar/my.properties", content = "a=c\npriority=2"), }, - expected = @Resource(path = "foo/bar/my.properties", content = "#.*\na=b\n") - ) - public void mergeWithAlreadyMerged() - { - } + expected = @Resource(path = "foo/bar/my.properties", content = "#.*\na=b\n")) + public void mergeWithAlreadyMerged() {} @Test @TransformerTest( transformer = PropertiesTransformer.class, configuration = { - @Property(name = "resource", value = "foo/bar/my.properties"), - @Property(name = "alreadyMergedKey", value = "complete") + @Property(name = "resource", value = "foo/bar/my.properties"), + @Property(name = "alreadyMergedKey", value = "complete") }, visited = { - @Resource(path = "foo/bar/my.properties", content = "a=b\ncomplete=true"), - @Resource(path = "foo/bar/my.properties", content = "a=c\ncomplete=true"), + @Resource(path = "foo/bar/my.properties", content = "a=b\ncomplete=true"), + @Resource(path = "foo/bar/my.properties", content = "a=c\ncomplete=true"), }, expected = {}, - expectedException = IllegalStateException.class - ) - public void alreadyMergeConflict() - { - } + expectedException = IllegalStateException.class) + public void alreadyMergeConflict() {} } diff --git a/src/test/java/org/apache/maven/plugins/shade/resource/rule/TransformerTesterRule.java b/src/test/java/org/apache/maven/plugins/shade/resource/rule/TransformerTesterRule.java index c1598418..afcba146 100644 --- a/src/test/java/org/apache/maven/plugins/shade/resource/rule/TransformerTesterRule.java +++ b/src/test/java/org/apache/maven/plugins/shade/resource/rule/TransformerTesterRule.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.shade.resource.rule; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +package org.apache.maven.plugins.shade.resource.rule; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -51,42 +44,36 @@ import org.junit.runner.Description; import org.junit.runners.model.Statement; -public class TransformerTesterRule - implements TestRule -{ +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class TransformerTesterRule implements TestRule { @Override - public Statement apply( final Statement base, final Description description ) - { - return new Statement() - { + public Statement apply(final Statement base, final Description description) { + return new Statement() { @Override - public void evaluate() throws Throwable - { - final TransformerTest spec = description.getAnnotation( TransformerTest.class ); - if ( spec == null ) - { + public void evaluate() throws Throwable { + final TransformerTest spec = description.getAnnotation(TransformerTest.class); + if (spec == null) { base.evaluate(); return; } final Map jar; - try - { - final ReproducibleResourceTransformer transformer = createTransformer( spec ); - visit( spec, transformer ); - jar = captureOutput( transformer ); - } - catch ( final Exception ex ) - { - if ( Exception.class.isAssignableFrom( spec.expectedException() ) ) - { + try { + final ReproducibleResourceTransformer transformer = createTransformer(spec); + visit(spec, transformer); + jar = captureOutput(transformer); + } catch (final Exception ex) { + if (Exception.class.isAssignableFrom(spec.expectedException())) { assertTrue( ex.getClass().getName(), - spec.expectedException().isAssignableFrom( ex.getClass() ) ); + spec.expectedException().isAssignableFrom(ex.getClass())); return; - } - else - { + } else { throw ex; } } @@ -95,88 +82,74 @@ public void evaluate() throws Throwable }; } - private void asserts( final TransformerTest spec, final Map jar) - { - if ( spec.strictMatch() && jar.size() != spec.expected().length ) - { - fail( "Strict match test failed: " + jar ); + private void asserts(final TransformerTest spec, final Map jar) { + if (spec.strictMatch() && jar.size() != spec.expected().length) { + fail("Strict match test failed: " + jar); } - for ( final Resource expected : spec.expected() ) - { - final String content = jar.get( expected.path() ); - assertNotNull( expected.path(), content ); + for (final Resource expected : spec.expected()) { + final String content = jar.get(expected.path()); + assertNotNull(expected.path(), content); assertTrue( expected.path() + ", expected=" + expected.content() + ", actual=" + content, - content.replace( System.lineSeparator(), "\n" ) .matches( expected.content() ) ); + content.replace(System.lineSeparator(), "\n").matches(expected.content())); } } - private Map captureOutput( final ReproducibleResourceTransformer transformer ) - throws IOException - { + private Map captureOutput(final ReproducibleResourceTransformer transformer) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); - try ( final JarOutputStream jar = new JarOutputStream( out ) ) - { - transformer.modifyOutputStream( jar ); + try (final JarOutputStream jar = new JarOutputStream(out)) { + transformer.modifyOutputStream(jar); } final Map created = new HashMap<>(); - try ( final JarInputStream jar = new JarInputStream( new ByteArrayInputStream( out.toByteArray() ) ) ) - { + try (final JarInputStream jar = new JarInputStream(new ByteArrayInputStream(out.toByteArray()))) { JarEntry entry; - while ( ( entry = jar.getNextJarEntry() ) != null ) - { - created.put( entry.getName(), read( jar ) ); + while ((entry = jar.getNextJarEntry()) != null) { + created.put(entry.getName(), read(jar)); } } return created; } - private void visit( final TransformerTest spec, final ReproducibleResourceTransformer transformer ) - throws IOException - { - for ( final Resource resource : spec.visited() ) - { - if ( transformer.canTransformResource( resource.path() ) ) - { + private void visit(final TransformerTest spec, final ReproducibleResourceTransformer transformer) + throws IOException { + for (final Resource resource : spec.visited()) { + if (transformer.canTransformResource(resource.path())) { transformer.processResource( resource.path(), - new ByteArrayInputStream( resource.content().getBytes(StandardCharsets.UTF_8) ), - Collections.emptyList(), 0 ); + new ByteArrayInputStream(resource.content().getBytes(StandardCharsets.UTF_8)), + Collections.emptyList(), + 0); } } } - private String read(final JarInputStream jar) throws IOException - { + private String read(final JarInputStream jar) throws IOException { final StringBuilder builder = new StringBuilder(); final byte[] buffer = new byte[512]; int read; - while ( (read = jar.read(buffer) ) >= 0 ) - { - builder.append( new String( buffer, 0, read ) ); + while ((read = jar.read(buffer)) >= 0) { + builder.append(new String(buffer, 0, read)); } return builder.toString(); } - private ReproducibleResourceTransformer createTransformer(final TransformerTest spec) - { + private ReproducibleResourceTransformer createTransformer(final TransformerTest spec) { final ConverterLookup lookup = new DefaultConverterLookup(); - try - { - final ConfigurationConverter converter = lookup.lookupConverterForType( spec.transformer() ); - final PlexusConfiguration configuration = new DefaultPlexusConfiguration( "configuration" ); - for ( final Property property : spec.configuration() ) - { - configuration.addChild( property.name(), property.value() ); + try { + final ConfigurationConverter converter = lookup.lookupConverterForType(spec.transformer()); + final PlexusConfiguration configuration = new DefaultPlexusConfiguration("configuration"); + for (final Property property : spec.configuration()) { + configuration.addChild(property.name(), property.value()); } - return ReproducibleResourceTransformer.class.cast( - converter.fromConfiguration( lookup, configuration, spec.transformer(), spec.transformer(), - Thread.currentThread().getContextClassLoader(), - new DefaultExpressionEvaluator() ) ); - } - catch (final ComponentConfigurationException e) - { + return ReproducibleResourceTransformer.class.cast(converter.fromConfiguration( + lookup, + configuration, + spec.transformer(), + spec.transformer(), + Thread.currentThread().getContextClassLoader(), + new DefaultExpressionEvaluator())); + } catch (final ComponentConfigurationException e) { throw new IllegalStateException(e); } } @@ -186,8 +159,7 @@ private ReproducibleResourceTransformer createTransformer(final TransformerTest */ @Target(METHOD) @Retention(RUNTIME) - public @interface TransformerTest - { + public @interface TransformerTest { /** * @return the list of resource the transformer will process. */ @@ -221,17 +193,17 @@ private ReproducibleResourceTransformer createTransformer(final TransformerTest @Target(METHOD) @Retention(RUNTIME) - public @interface Property - { + public @interface Property { String name(); + String value(); } @Target(METHOD) @Retention(RUNTIME) - public @interface Resource - { + public @interface Resource { String path(); + String content(); } }