Search in sources :

Example 1 with Filter

use of org.apache.maven.plugins.shade.filter.Filter in project maven-plugins by apache.

the class ShadeMojoTest method testShadeWithFilter.

/**
 * Tests if a Filter is installed correctly, also if createSourcesJar is set to true.
 *
 * @throws Exception
 */
public void testShadeWithFilter() throws Exception {
    ShadeMojo mojo = new ShadeMojo();
    // set createSourcesJar = true
    Field createSourcesJar = ShadeMojo.class.getDeclaredField("createSourcesJar");
    createSourcesJar.setAccessible(true);
    createSourcesJar.set(mojo, Boolean.TRUE);
    // configure artifactResolver (mocked) for mojo
    ArtifactResolver mockArtifactResolver = new ArtifactResolver() {

        @Override
        public ArtifactResult resolveArtifact(ProjectBuildingRequest req, final Artifact art) throws ArtifactResolverException {
            return new ArtifactResult() {

                @Override
                public Artifact getArtifact() {
                    art.setResolved(true);
                    String fileName = art.getArtifactId() + "-" + art.getVersion() + (art.getClassifier() != null ? "-" + art.getClassifier() : "") + ".jar";
                    art.setFile(new File(fileName));
                    return art;
                }
            };
        }

        @Override
        public ArtifactResult resolveArtifact(ProjectBuildingRequest req, final ArtifactCoordinate coordinate) throws ArtifactResolverException {
            return new ArtifactResult() {

                @Override
                public Artifact getArtifact() {
                    Artifact art = mock(Artifact.class);
                    when(art.getGroupId()).thenReturn(coordinate.getGroupId());
                    when(art.getArtifactId()).thenReturn(coordinate.getArtifactId());
                    when(art.getType()).thenReturn(coordinate.getExtension());
                    when(art.getClassifier()).thenReturn(coordinate.getClassifier());
                    when(art.isResolved()).thenReturn(true);
                    String fileName = coordinate.getArtifactId() + "-" + coordinate.getVersion() + (coordinate.getClassifier() != null ? "-" + coordinate.getClassifier() : "") + ".jar";
                    when(art.getFile()).thenReturn(new File(fileName));
                    return art;
                }
            };
        }
    };
    Field artifactResolverField = ShadeMojo.class.getDeclaredField("artifactResolver");
    artifactResolverField.setAccessible(true);
    artifactResolverField.set(mojo, mockArtifactResolver);
    // create and configure MavenProject
    MavenProject project = new MavenProject();
    ArtifactHandler artifactHandler = (ArtifactHandler) lookup(ArtifactHandler.ROLE);
    Artifact artifact = new DefaultArtifact("org.apache.myfaces.core", "myfaces-impl", VersionRange.createFromVersion("2.0.1-SNAPSHOT"), "compile", "jar", null, artifactHandler);
    // setFile and setResolved
    artifact = mockArtifactResolver.resolveArtifact(null, artifact).getArtifact();
    project.setArtifact(artifact);
    Field projectField = ShadeMojo.class.getDeclaredField("project");
    projectField.setAccessible(true);
    projectField.set(mojo, project);
    // 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");
    // add ArchiveFilter to mojo
    Field filtersField = ShadeMojo.class.getDeclaredField("filters");
    filtersField.setAccessible(true);
    filtersField.set(mojo, new ArchiveFilter[] { archiveFilter });
    Field sessionField = ShadeMojo.class.getDeclaredField("session");
    sessionField.setAccessible(true);
    sessionField.set(mojo, mock(MavenSession.class));
    // invoke getFilters()
    Method getFilters = ShadeMojo.class.getDeclaredMethod("getFilters", new Class[0]);
    getFilters.setAccessible(true);
    List<Filter> filters = (List<Filter>) getFilters.invoke(mojo);
    // assertions - there must be one filter
    assertEquals(1, filters.size());
    // the filter must be able to filter the binary and the sources jar
    Filter filter = filters.get(0);
    // binary jar
    assertTrue(filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT.jar")));
    // sources jar
    assertTrue(filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT-sources.jar")));
}
Also used : ArtifactCoordinate(org.apache.maven.shared.artifact.ArtifactCoordinate) Method(java.lang.reflect.Method) ArtifactResolver(org.apache.maven.shared.artifact.resolve.ArtifactResolver) Artifact(org.apache.maven.artifact.Artifact) DefaultArtifact(org.apache.maven.artifact.DefaultArtifact) ArtifactResult(org.apache.maven.shared.artifact.resolve.ArtifactResult) Field(java.lang.reflect.Field) ProjectBuildingRequest(org.apache.maven.project.ProjectBuildingRequest) MavenSession(org.apache.maven.execution.MavenSession) ArtifactHandler(org.apache.maven.artifact.handler.ArtifactHandler) MavenProject(org.apache.maven.project.MavenProject) Filter(org.apache.maven.plugins.shade.filter.Filter) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) DefaultArtifact(org.apache.maven.artifact.DefaultArtifact)

Example 2 with Filter

use of org.apache.maven.plugins.shade.filter.Filter in project maven-plugins by apache.

the class ShadeMojoTest method shaderWithPattern.

public void shaderWithPattern(String shadedPattern, File jar) throws Exception {
    Shader s = (Shader) lookup(Shader.ROLE);
    Set<File> set = new LinkedHashSet<File>();
    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"));
    List<Relocator> relocators = new ArrayList<Relocator>();
    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<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>();
    resourceTransformers.add(new ComponentsXmlResourceTransformer());
    List<Filter> filters = new ArrayList<Filter>();
    ShadeRequest shadeRequest = new ShadeRequest();
    shadeRequest.setJars(set);
    shadeRequest.setUberJar(jar);
    shadeRequest.setFilters(filters);
    shadeRequest.setRelocators(relocators);
    shadeRequest.setResourceTransformers(resourceTransformers);
    s.shade(shadeRequest);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) Shader(org.apache.maven.plugins.shade.Shader) ShadeRequest(org.apache.maven.plugins.shade.ShadeRequest) SimpleRelocator(org.apache.maven.plugins.shade.relocation.SimpleRelocator) Relocator(org.apache.maven.plugins.shade.relocation.Relocator) SimpleRelocator(org.apache.maven.plugins.shade.relocation.SimpleRelocator) Filter(org.apache.maven.plugins.shade.filter.Filter) ComponentsXmlResourceTransformer(org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer) ResourceTransformer(org.apache.maven.plugins.shade.resource.ResourceTransformer) ComponentsXmlResourceTransformer(org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer) File(java.io.File)

Example 3 with Filter

use of org.apache.maven.plugins.shade.filter.Filter in project maven-plugins by apache.

the class DefaultShaderTest method testShaderWithRelocatedClassname.

public void testShaderWithRelocatedClassname() throws Exception {
    DefaultShader s = newShader();
    Set<File> set = new LinkedHashSet<File>();
    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"));
    List<Relocator> relocators = new ArrayList<Relocator>();
    relocators.add(new SimpleRelocator("org/codehaus/plexus/util/", "_plexus/util/__", null, Arrays.<String>asList()));
    List<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>();
    resourceTransformers.add(new ComponentsXmlResourceTransformer());
    List<Filter> filters = new ArrayList<Filter>();
    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);
    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]);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) ClassVisitor(org.objectweb.asm.ClassVisitor) Relocator(org.apache.maven.plugins.shade.relocation.Relocator) SimpleRelocator(org.apache.maven.plugins.shade.relocation.SimpleRelocator) SimpleRelocator(org.apache.maven.plugins.shade.relocation.SimpleRelocator) Filter(org.apache.maven.plugins.shade.filter.Filter) URLClassLoader(java.net.URLClassLoader) ComponentsXmlResourceTransformer(org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer) ClassReader(org.objectweb.asm.ClassReader) ResourceTransformer(org.apache.maven.plugins.shade.resource.ResourceTransformer) ComponentsXmlResourceTransformer(org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer) File(java.io.File)

Example 4 with Filter

use of org.apache.maven.plugins.shade.filter.Filter in project maven-plugins by apache.

the class DefaultShader method shadeJars.

private void shadeJars(ShadeRequest shadeRequest, Set<String> resources, List<ResourceTransformer> transformers, RelocatorRemapper remapper, JarOutputStream jos, Multimap<String, File> duplicates) throws IOException, MojoExecutionException {
    for (File jar : shadeRequest.getJars()) {
        getLogger().debug("Processing JAR " + jar);
        List<Filter> jarFilters = getFilters(jar, shadeRequest.getFilters());
        JarFile jarFile = newJarFile(jar);
        try {
            for (Enumeration<JarEntry> j = jarFile.entries(); j.hasMoreElements(); ) {
                JarEntry entry = j.nextElement();
                String name = entry.getName();
                if ("META-INF/INDEX.LIST".equals(name)) {
                    // later
                    continue;
                }
                if ("module-info.class".equals(name)) {
                    getLogger().warn("Discovered module-info.class. " + "Shading will break its strong encapsulation.");
                    continue;
                }
                if (!entry.isDirectory() && !isFiltered(jarFilters, name)) {
                    shadeSingleJar(shadeRequest, resources, transformers, remapper, jos, duplicates, jar, jarFile, entry, name);
                }
            }
        } finally {
            jarFile.close();
        }
    }
}
Also used : Filter(org.apache.maven.plugins.shade.filter.Filter) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 5 with Filter

use of org.apache.maven.plugins.shade.filter.Filter in project maven-plugins by apache.

the class DefaultShader method shade.

public void shade(ShadeRequest shadeRequest) throws IOException, MojoExecutionException {
    Set<String> resources = new HashSet<String>();
    ResourceTransformer manifestTransformer = null;
    List<ResourceTransformer> transformers = new ArrayList<ResourceTransformer>(shadeRequest.getResourceTransformers());
    for (Iterator<ResourceTransformer> it = transformers.iterator(); it.hasNext(); ) {
        ResourceTransformer transformer = it.next();
        if (transformer instanceof ManifestResourceTransformer) {
            manifestTransformer = transformer;
            it.remove();
        }
    }
    RelocatorRemapper remapper = new RelocatorRemapper(shadeRequest.getRelocators());
    // noinspection ResultOfMethodCallIgnored
    shadeRequest.getUberJar().getParentFile().mkdirs();
    JarOutputStream out = null;
    try {
        out = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(shadeRequest.getUberJar())));
        goThroughAllJarEntriesForManifestTransformer(shadeRequest, resources, manifestTransformer, out);
        // CHECKSTYLE_OFF: MagicNumber
        Multimap<String, File> duplicates = HashMultimap.create(10000, 3);
        // CHECKSTYLE_ON: MagicNumber
        shadeJars(shadeRequest, resources, transformers, remapper, out, duplicates);
        // CHECKSTYLE_OFF: MagicNumber
        Multimap<Collection<File>, String> overlapping = HashMultimap.create(20, 15);
        for (String clazz : duplicates.keySet()) {
            Collection<File> jarz = duplicates.get(clazz);
            if (jarz.size() > 1) {
                overlapping.put(jarz, clazz);
            }
        }
        // Log a summary of duplicates
        logSummaryOfDuplicates(overlapping);
        if (overlapping.keySet().size() > 0) {
            showOverlappingWarning();
        }
        for (ResourceTransformer transformer : transformers) {
            if (transformer.hasTransformedResource()) {
                transformer.modifyOutputStream(out);
            }
        }
        out.close();
        out = null;
    } finally {
        IOUtil.close(out);
    }
    for (Filter filter : shadeRequest.getFilters()) {
        filter.finished();
    }
}
Also used : ArrayList(java.util.ArrayList) JarOutputStream(java.util.jar.JarOutputStream) Filter(org.apache.maven.plugins.shade.filter.Filter) FileOutputStream(java.io.FileOutputStream) Collection(java.util.Collection) ManifestResourceTransformer(org.apache.maven.plugins.shade.resource.ManifestResourceTransformer) ResourceTransformer(org.apache.maven.plugins.shade.resource.ResourceTransformer) ManifestResourceTransformer(org.apache.maven.plugins.shade.resource.ManifestResourceTransformer) BufferedOutputStream(java.io.BufferedOutputStream) JarFile(java.util.jar.JarFile) File(java.io.File) HashSet(java.util.HashSet)

Aggregations

File (java.io.File)10 Filter (org.apache.maven.plugins.shade.filter.Filter)10 ArrayList (java.util.ArrayList)8 LinkedHashSet (java.util.LinkedHashSet)7 ResourceTransformer (org.apache.maven.plugins.shade.resource.ResourceTransformer)7 Relocator (org.apache.maven.plugins.shade.relocation.Relocator)6 SimpleRelocator (org.apache.maven.plugins.shade.relocation.SimpleRelocator)6 ComponentsXmlResourceTransformer (org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer)5 URLClassLoader (java.net.URLClassLoader)3 ShadeRequest (org.apache.maven.plugins.shade.ShadeRequest)3 IOException (java.io.IOException)2 Field (java.lang.reflect.Field)2 Method (java.lang.reflect.Method)2 HashSet (java.util.HashSet)2 JarFile (java.util.jar.JarFile)2 Artifact (org.apache.maven.artifact.Artifact)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 Shader (org.apache.maven.plugins.shade.Shader)2 MinijarFilter (org.apache.maven.plugins.shade.filter.MinijarFilter)2 SimpleFilter (org.apache.maven.plugins.shade.filter.SimpleFilter)2