Example usage for java.util.jar JarFile getJarEntry

List of usage examples for java.util.jar JarFile getJarEntry

Introduction

In this page you can find the example usage for java.util.jar JarFile getJarEntry.

Prototype

public JarEntry getJarEntry(String name) 

Source Link

Document

Returns the JarEntry for the given base entry name or null if not found.

Usage

From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java

@Test
public void relocatedClasses() throws Exception {
    SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null,
            Arrays.asList("org.foo.exclude.*"));
    List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator);

    String content = "org.foo.Service\norg.foo.exclude.OtherService\n";
    byte[] contentBytes = content.getBytes("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);
    contentStream.close();// w w w . ja  v  a2  s  . c  om

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempJar);
    JarOutputStream jos = new JarOutputStream(fos);
    try {
        xformer.modifyOutputStream(jos, false);
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile(tempJar);
        JarEntry jarEntry = jarFile.getJarEntry(contentResourceShaded);
        assertNotNull(jarEntry);
        InputStream entryStream = jarFile.getInputStream(jarEntry);
        try {
            String xformedContent = IOUtils.toString(entryStream, "utf-8");
            assertEquals("borg.foo.Service" + System.getProperty("line.separator")
                    + "org.foo.exclude.OtherService" + System.getProperty("line.separator"), xformedContent);
        } finally {
            IOUtils.closeQuietly(entryStream);
            jarFile.close();
        }
    } finally {
        if (jos != null) {
            IOUtils.closeQuietly(jos);
        }
        tempJar.delete();
    }
}

From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java

@Test
public void concatenation() throws Exception {
    SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null, null);
    List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator);

    String content = "org.foo.Service\n";
    byte[] contentBytes = content.getBytes("UTF-8");
    InputStream contentStream = new ByteArrayInputStream(contentBytes);
    String contentResource = "META-INF/services/org.something.another";

    ServicesResourceTransformer xformer = new ServicesResourceTransformer();
    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();//w  w w . j  a  v a2 s.co m

    content = "org.blah.Service\n";
    contentBytes = content.getBytes("UTF-8");
    contentStream = new ByteArrayInputStream(contentBytes);
    contentResource = "META-INF/services/org.something.another";

    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempJar);
    JarOutputStream jos = new JarOutputStream(fos);
    try {
        xformer.modifyOutputStream(jos, false);
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile(tempJar);
        JarEntry jarEntry = jarFile.getJarEntry(contentResource);
        assertNotNull(jarEntry);
        InputStream entryStream = jarFile.getInputStream(jarEntry);
        try {
            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)) {
                    h1 = true;
                } else if ("borg.foo.Service".equals(name)) {
                    h2 = true;
                }
            }
            assertTrue(h1 && h2);
        } finally {
            IOUtils.closeQuietly(entryStream);
            jarFile.close();
        }
    } finally {
        if (jos != null) {
            IOUtils.closeQuietly(jos);
        }
        tempJar.delete();
    }
}

From source file:org.apache.nifi.web.server.JettyServer.java

/**
 * Returns the extension in the specified WAR using the specified path.
 *
 * @param war war/*from  ww  w. ja  v a 2 s.c  om*/
 * @param path path
 * @return extensions
 */
private List<String> getWarExtensions(final File war, final String path) {
    List<String> processorTypes = new ArrayList<>();

    // load the jar file and attempt to find the nifi-processor entry
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(war);
        JarEntry jarEntry = jarFile.getJarEntry(path);

        // ensure the nifi-processor entry was found
        if (jarEntry != null) {
            // get an input stream for the nifi-processor configuration file
            try (final BufferedReader in = new BufferedReader(
                    new InputStreamReader(jarFile.getInputStream(jarEntry)))) {

                // read in each configured type
                String rawProcessorType;
                while ((rawProcessorType = in.readLine()) != null) {
                    // extract the processor type
                    final String processorType = extractComponentType(rawProcessorType);
                    if (processorType != null) {
                        processorTypes.add(processorType);
                    }
                }
            }
        }
    } catch (IOException ioe) {
        logger.warn("Unable to inspect {} for a custom processor UI.", new Object[] { war, ioe });
    } finally {
        IOUtils.closeQuietly(jarFile);
    }

    return processorTypes;
}

From source file:org.apache.openejb.config.DeploymentLoader.java

private static void addConnectorModules(final AppModule appModule, final WebModule webModule)
        throws OpenEJBException {
    // WEB-INF/*  ww  w  . java 2  s .  c  o  m*/
    if (webModule.getAltDDs().containsKey("ra.xml")) {
        final String jarLocation = new File(webModule.getJarLocation(), "/WEB-INF/classes").getAbsolutePath();
        final ConnectorModule connectorModule = createConnectorModule(jarLocation, jarLocation,
                webModule.getClassLoader(), webModule.getModuleId() + "RA",
                (URL) webModule.getAltDDs().get("ra.xml"));
        appModule.getConnectorModules().add(connectorModule);
    }

    // .rar
    for (final URL url : webModule.getRarUrls()) {
        try {
            final File file = URLs.toFile(url);
            if (file.getName().endsWith(".rar")) {
                final String jarLocation = file.getAbsolutePath();
                final ConnectorModule connectorModule = createConnectorModule(jarLocation, jarLocation,
                        webModule.getClassLoader(), null);
                appModule.getConnectorModules().add(connectorModule);
            }
        } catch (final Exception e) {
            logger.error("error processing url " + url.toExternalForm(), e);
        }
    }

    for (final URL url : webModule.getScannableUrls()) {
        try {
            final File file = URLs.toFile(url);
            if (file.getName().endsWith(".jar")) {
                final JarFile jarFile = new JarFile(file);

                // TODO: better management of altdd
                String name = (ALTDD != null ? ALTDD + "." : "") + "ra.xml";

                JarEntry entry = jarFile.getJarEntry(name);
                if (entry == null) {
                    name = "META-INF/" + name;
                    entry = jarFile.getJarEntry(name);
                }
                if (entry == null) {
                    continue;
                }

                final String jarLocation = file.getAbsolutePath();
                final ConnectorModule connectorModule = createConnectorModule(jarLocation, jarLocation,
                        webModule.getClassLoader(), null);
                appModule.getConnectorModules().add(connectorModule);
            }
        } catch (final Exception e) {
            logger.error("error processing url " + url.toExternalForm(), e);
        }
    }
}

From source file:org.apache.servicemix.jbi.deployer.handler.JBIDeploymentListener.java

/**
 * Check if the file is a recognized JBI artifact that needs to be
 * processed.//  ww  w. j  a  va  2 s .  c o m
 *
 * @param artifact the file to check
 * @return <code>true</code> is the file is a JBI artifact that
 *         should be transformed into an OSGi bundle.
 */
public boolean canHandle(File artifact) {
    try {
        // Accept jars and zips
        if (!artifact.getName().endsWith(".zip") && !artifact.getName().endsWith(".jar")) {
            return false;
        }
        JarFile jar = new JarFile(artifact);
        JarEntry entry = jar.getJarEntry(DescriptorFactory.DESCRIPTOR_FILE);
        // Only handle JBI artifacts
        if (entry == null) {
            return false;
        }
        // Only handle non OSGi bundles
        Manifest m = jar.getManifest();
        if (m != null && m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null
                && m.getMainAttributes().getValue(new Attributes.Name("Bundle-Version")) != null) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.apache.servicemix.war.deployer.WarDeploymentListener.java

public boolean canHandle(File artifact) {
    try {//from   w  ww  . ja v a2 s.  c o  m
        JarFile jar = new JarFile(artifact);
        JarEntry entry = jar.getJarEntry("WEB-INF/web.xml");
        // Only handle WAR artifacts
        if (entry == null) {
            return false;
        }
        // Only handle non OSGi bundles
        Manifest m = jar.getManifest();
        if (m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null
                && m.getMainAttributes().getValue(new Attributes.Name("Bundle-Version")) != null) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java

@Override
protected void enhanceContext(final Context context) throws MojoExecutionException {
    super.enhanceContext(context);

    try {//from   w w  w  .j  av a2s .com
        ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() //
                .setDependencies(dependencies) //
                .setLog(getLog()) //
                .setMavenProject(project) //
                .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) //
                .setUseTestClassPath(useTestClasspath);
        final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator
                .calculateClassPathEntries(request);
        final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries();
        final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories();

        final List<String> jarPaths = extractJars(classLoaderEntries);

        List<URL> urls = new ArrayList<URL>(jarPaths.size());

        for (String jarPath : jarPaths) {
            try {
                urls.add(new File(jarPath).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }

        getLog().debug("classLoaderEntriesCalculator urls: " + urls);

        final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

        final ClassRealm pluginRealm = getTomcatClassLoader();

        context.setResources(
                new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), //
                        getPath(), //
                        getLog()) {
                    @Override
                    public WebResource getClassLoaderResource(String path) {

                        log.debug("RunMojo#getClassLoaderResource: " + path);
                        URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/"));
                        // search in parent (plugin) classloader
                        if (url == null) {
                            url = pluginRealm.getResource(StringUtils.removeStart(path, "/"));
                        }

                        if (url == null) {
                            // try in reactors
                            List<WebResource> webResources = findResourcesInDirectories(path, //
                                    classLoaderEntriesCalculatorResult.getBuildDirectories());

                            // so we return the first one
                            if (!webResources.isEmpty()) {
                                return webResources.get(0);
                            }
                        }

                        if (url == null) {
                            return new EmptyResource(this, getPath());
                        }

                        return urlToWebResource(url, path);
                    }

                    @Override
                    public WebResource getResource(String path) {
                        log.debug("RunMojo#getResource: " + path);
                        return super.getResource(path);
                    }

                    @Override
                    public WebResource[] getResources(String path) {
                        log.debug("RunMojo#getResources: " + path);
                        return super.getResources(path);
                    }

                    @Override
                    protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) {
                        log.debug("RunMojo#getResourcesInternal: " + path);
                        return super.getResourcesInternal(path, useClassLoaderResources);
                    }

                    @Override
                    public WebResource[] getClassLoaderResources(String path) {
                        try {
                            Enumeration<URL> enumeration = urlClassLoader
                                    .findResources(StringUtils.removeStart(path, "/"));
                            List<URL> urlsFound = new ArrayList<URL>();
                            List<WebResource> webResources = new ArrayList<WebResource>();
                            while (enumeration.hasMoreElements()) {
                                URL url = enumeration.nextElement();
                                urlsFound.add(url);
                                webResources.add(urlToWebResource(url, path));
                            }
                            log.debug("RunMojo#getClassLoaderResources: " + path + " found : "
                                    + urlsFound.toString());

                            webResources.addAll(findResourcesInDirectories(path,
                                    classLoaderEntriesCalculatorResult.getBuildDirectories()));

                            return webResources.toArray(new WebResource[webResources.size()]);

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private List<WebResource> findResourcesInDirectories(String path,
                            List<String> directories) {
                        try {
                            List<WebResource> webResources = new ArrayList<WebResource>();

                            for (String directory : directories) {

                                File file = new File(directory, path);
                                if (file.exists()) {
                                    webResources.add(urlToWebResource(file.toURI().toURL(), path));
                                }

                            }

                            return webResources;
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private WebResource urlToWebResource(URL url, String path) {
                        JarFile jarFile = null;

                        try {
                            // url.getFile is
                            // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class

                            int idx = url.getFile().indexOf('!');

                            if (idx >= 0) {
                                String filePath = StringUtils.removeStart(url.getFile().substring(0, idx),
                                        "file:");

                                jarFile = new JarFile(filePath);

                                JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/"));

                                return new JarResource(this, //
                                        getPath(), //
                                        filePath, //
                                        url.getPath().substring(0, idx), //
                                        jarEntry, //
                                        "", //
                                        null);
                            } else {
                                return new FileResource(this, webAppPath, new File(url.getFile()), true);
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        } finally {
                            IOUtils.closeQuietly(jarFile);
                        }
                    }

                });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (File tmpDir : tmpDirectories) {
                    try {
                        FileUtils.deleteDirectory(tmpDir);
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        });

        if (classLoaderEntries != null) {
            WebResourceSet webResourceSet = new FileResourceSet() {
                @Override
                public WebResource getResource(String path) {

                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB"));
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new FileResource(context.getResources(), getPath(),
                                new File(project.getBuild().getOutputDirectory()), true);
                    }

                    File file = new File(project.getBuild().getOutputDirectory(), path);
                    if (file.exists()) {
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }

                    //if ( StringUtils.endsWith( path, ".class" ) )
                    {
                        // so we search the class file in the jars
                        for (String jarPath : jarPaths) {
                            File jar = new File(jarPath);
                            if (!jar.exists()) {
                                continue;
                            }

                            try (JarFile jarFile = new JarFile(jar)) {
                                JarEntry jarEntry = (JarEntry) jarFile
                                        .getEntry(StringUtils.removeStart(path, "/"));
                                if (jarEntry != null) {
                                    return new JarResource(context.getResources(), //
                                            getPath(), //
                                            jarFile.getName(), //
                                            jar.toURI().toString(), //
                                            jarEntry, //
                                            path, //
                                            jarFile.getManifest());
                                }
                            } catch (IOException e) {
                                getLog().debug("skip error building jar file: " + e.getMessage(), e);
                            }

                        }
                    }

                    return new EmptyResource(null, path);
                }

                @Override
                public String[] list(String path) {
                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        return jarPaths.toArray(new String[jarPaths.size()]);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() };
                    }
                    return super.list(path);
                }

                @Override
                public Set<String> listWebAppPaths(String path) {

                    if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) {
                        // adding outputDirectory as well?
                        return new HashSet<String>(jarPaths);
                    }

                    File filePath = new File(getWarSourceDirectory(), path);

                    if (filePath.isDirectory()) {
                        Set<String> paths = new HashSet<String>();

                        String[] files = filePath.list();
                        if (files == null) {
                            return paths;
                        }

                        for (String file : files) {
                            paths.add(file);
                        }

                        return paths;

                    } else {
                        return Collections.emptySet();
                    }
                }

                @Override
                public boolean mkdir(String path) {
                    return super.mkdir(path);
                }

                @Override
                public boolean write(String path, InputStream is, boolean overwrite) {
                    return super.write(path, is, overwrite);
                }

                @Override
                protected void checkType(File file) {
                    //super.checkType( file );
                }

            };

            context.getResources().addJarResources(webResourceSet);
        }

    } catch (TomcatRunException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:org.ebayopensource.turmeric.eclipse.maven.core.utils.MavenCoreUtils.java

/**
 * Gets the input stream from jar./*from  w ww .  java  2  s  . c o m*/
 *
 * @param mProject the m project
 * @param jarEntryPath the jar entry path
 * @return The input stream for the specified jar entry
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static InputStream getInputStreamFromJar(final MavenProject mProject, final String jarEntryPath)
        throws IOException {
    if (SOALogger.DEBUG)
        logger.entering(mProject, jarEntryPath);
    final File file = getJarFileForService(mProject);

    InputStream io = null;
    if (file.exists() && file.canRead()) {
        final JarFile jarFile = new JarFile(file);
        final JarEntry jarEntry = jarFile.getJarEntry(jarEntryPath);
        if (jarEntry != null) {
            io = jarFile.getInputStream(jarEntry);
        } else {
            logger.warning("Can not find the jar entry->" + jarEntryPath);
        }
    } else {
        logger.warning("Jar file is either not exist or not readable ->" + file);
    }
    if (SOALogger.DEBUG)
        logger.exiting(io);
    return io;
}

From source file:org.ebayopensource.turmeric.eclipse.utils.classloader.SOAPluginClassLoader.java

/**
 * {@inheritDoc}//from www .  j a  v  a2 s  .  c o m
 */
@Override
public URL findResource(String resourceName) {
    //logger.info("resource name in findresource is " + resourceName);
    try {
        URL retUrl = null;
        for (Bundle pluginBundle : pluginBundles) {
            retUrl = pluginBundle.getResource(resourceName);
            if (retUrl != null) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("found resource using bundle " + resourceName);
                }
                return retUrl;
            }
        }

    } catch (Exception exception) {
    }

    for (URL url : m_jarURLs) {

        try {
            File file = FileUtils.toFile(url);
            JarFile jarFile;
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(resourceName);
            if (jarEntry != null) {
                SOAToolFileUrlHandler handler = new SOAToolFileUrlHandler(jarFile, jarEntry);
                URL retUrl = new URL("jar", "", -1,
                        new File(jarFile.getName()).toURI().toURL() + "!/" + jarEntry.getName(), handler);
                handler.setExpectedUrl(retUrl);
                return retUrl;

            }
        } catch (IOException e) {
            e.printStackTrace(); // KEEPME
        }

    }

    return super.findResource(resourceName);
}

From source file:org.ebayopensource.turmeric.eclipse.utils.io.IOUtil.java

/**
 * Loads the properties file residing inside a jar. The enclosed jar file is
 * queried for the given jar entry path and is parsed into a properties
 * file. Most of the cases this is being used to load some SOA properties
 * file from a jar project which is not imported to the workspace but is
 * stored somewhere in the file system. But any client who wants to load a
 * properties file can use this. There is nothing SOA specific here in this
 * API.//from   ww  w.j a v  a 2 s  .c  om
 *
 * @param enclosedJarFile the enclosed jar file
 * @param jarEntryPath the jar entry path
 * @return the properties
 * @throws IOException This is a special case where we want the consumers to
 * continue without failures, because most of the cases consumes
 * this in a loop.
 */
public static Properties loadProperties(JarFile enclosedJarFile, String jarEntryPath) throws IOException {
    JarEntry jarEntry = enclosedJarFile.getJarEntry(jarEntryPath);
    InputStream inputStream = enclosedJarFile.getInputStream(jarEntry);
    Properties properties = new Properties();
    properties.load(inputStream);
    return properties;

}