Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

From source file:de.smartics.maven.plugin.jboss.modules.util.classpath.ClassPathDirectoryListing.java

private void traverseJarEntries(final String resourcePath, final List<String> contents, final JarFile jar) {
    final int resourcePathLength = resourcePath.length();

    final Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        final String name = entries.nextElement().getName();
        if (name.startsWith(resourcePath)) {
            final String entry = name.substring(resourcePathLength);
            final String normalized = normalize(entry);

            if (normalized != null && !contents.contains(normalized)) {
                contents.add(normalized);
            }/*  w  w  w.jav a 2 s  . c om*/
        }
    }
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.solr.server.IntactSolrHomeBuilder.java

public void install(File solrWorkingDir) throws IOException {
    if (log.isInfoEnabled())
        log.info("Installing Intact SOLR Home at: " + solrWorkingDir);

    // copy resource directory containing solr-home and war file
    File solrHomeToCreate = new File(solrWorkingDir, "home");
    File solrWarToCreate = new File(solrWorkingDir, "solr.war");

    // only copy solr-home when solr-home does not exist
    if (!solrHomeToCreate.exists() && getSolrHomeDir() == null) {
        solrHomeToCreate.mkdirs();//from w ww  .  ja  va2s. c  o m

        File solrHomeToCopy = new File(IntactSolrHomeBuilder.class.getResource("/home").getFile());
        // is in the resources
        if (solrHomeToCopy.exists()) {
            FileUtils.copyDirectory(solrHomeToCopy, solrHomeToCreate);

            if (!solrWarToCreate.exists() && getSolrWar() == null) {
                try (InputStream solrWarToCopy = IntactSolrHomeBuilder.class.getResourceAsStream("/solr.war")) {
                    FileUtils.copyInputStreamToFile(solrWarToCopy, solrWarToCreate);
                }
            }
        }
        // is in the jar in the dependencies
        else {

            String originalName = IntactSolrHomeBuilder.class.getResource("/home").getFile();
            String jarFileName = originalName.substring(0, originalName.indexOf("!")).replace("file:", "");

            JarFile jarFile = new JarFile(jarFileName);
            Enumeration<JarEntry> jarEntries = jarFile.entries();

            // write
            while (jarEntries.hasMoreElements()) {
                JarEntry entry = jarEntries.nextElement();

                // solr war file
                if (entry.getName().endsWith("solr.war") && !solrWarToCreate.exists()
                        && getSolrHomeDir() == null) {

                    InputStream inputStream = jarFile.getInputStream(entry);

                    try {
                        FileUtils.copyInputStreamToFile(inputStream, solrWarToCreate);
                    } finally {
                        inputStream.close();
                    }
                } else if (entry.toString().startsWith("home")) {
                    File fileToCreate = new File(solrWorkingDir, entry.toString());

                    if (entry.isDirectory()) {
                        fileToCreate.mkdirs();
                        continue;
                    }

                    try (InputStream inputStream = jarFile.getInputStream(entry)) {
                        FileUtils.copyInputStreamToFile(inputStream, fileToCreate);
                    }
                }
            }
        }

        setSolrHomeDir(solrHomeToCreate);
        setSolrWar(solrWarToCreate);
    }
    // only copy solr.war when solr.war does not exist
    else if (!solrWarToCreate.exists() && getSolrWar() == null) {

        File solrHomeToCopy = new File(IntactSolrHomeBuilder.class.getResource("/home").getFile());
        // is in the resources
        if (solrHomeToCopy.exists()) {
            try (InputStream solrWarToCopy = IntactSolrHomeBuilder.class.getResourceAsStream("/solr.war")) {
                FileUtils.copyInputStreamToFile(solrWarToCopy, new File(solrWorkingDir + "/solr.war"));
            }
        }
        // is in the jar in the dependencies
        else {

            String originalName = IntactSolrHomeBuilder.class.getResource("/home").getFile();
            String jarFileName = originalName.substring(0, originalName.indexOf("!")).replace("file:", "");

            JarFile jarFile = new JarFile(jarFileName);
            Enumeration<JarEntry> jarEntries = jarFile.entries();

            // write
            while (jarEntries.hasMoreElements()) {
                JarEntry entry = jarEntries.nextElement();

                // solr war file
                if (entry.getName().endsWith("solr.war")) {
                    File fileToCreate = new File(solrWorkingDir, entry.toString());

                    try (InputStream inputStream = jarFile.getInputStream(entry)) {
                        FileUtils.copyInputStreamToFile(inputStream, fileToCreate);
                    }
                }
            }
        }

        setSolrHomeDir(solrHomeToCreate);
        setSolrWar(solrWarToCreate);
    }

    if (log.isDebugEnabled()) {
        log.debug("\nIntact Solr Home: {}\nSolr WAR: {}", getSolrHomeDir().toString(), getSolrWar().toString());
    }
}

From source file:hotbeans.support.JarFileHotBeanModuleLoader.java

/**
 * Extracts all the files in the module jar file, including nested jar files. The reason for extracting the complete
 * contents of the jar file (and not just the nested jar files) is to make sure the module jar file isn't locked, and
 * thus may be deleted.//from   w  w w. ja  v a 2 s  .  c o  m
 */
private void extractLibs() throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Extracting module jar file '" + moduleJarFile + "'.");

    JarFile jarFile = new JarFile(this.moduleJarFile);
    Enumeration entries = jarFile.entries();
    JarEntry entry;
    String entryName;
    File extractedFile = null;
    FileOutputStream extractedFileOutputStream;

    while (entries.hasMoreElements()) {
        entry = (JarEntry) entries.nextElement();
        if ((entry != null) && (!entry.isDirectory())) {
            entryName = entry.getName();
            if (entryName != null) {
                // if( logger.isDebugEnabled() ) logger.debug("Extracting '" + entryName + "'.");

                // Copy nested jar file to temp dir
                extractedFile = new File(this.tempDir, entryName);
                extractedFile.getParentFile().mkdirs();

                extractedFileOutputStream = new FileOutputStream(extractedFile);
                FileCopyUtils.copy(jarFile.getInputStream(entry), extractedFileOutputStream);
                extractedFileOutputStream = null;

                if ((entryName.startsWith(LIB_PATH)) && (entryName.toLowerCase().endsWith(".jar"))) {
                    // Register nested jar file in "class path"
                    super.addURL(extractedFile.toURI().toURL());
                }
            }
        }
    }

    jarFile.close();
    jarFile = null;

    super.addURL(tempDir.toURI().toURL()); // Add temp dir as class path (note that this must be added after all the
                                           // files have been extracted)

    if (logger.isDebugEnabled())
        logger.debug("Done extracting module jar file '" + moduleJarFile + "'.");
}

From source file:net.ontopia.utils.ResourcesDirectoryReader.java

private void findResourcesFromJar(URL jarPath) {
    try {/*  w w  w  .j av  a 2s.c  o m*/
        JarURLConnection jarConnection = (JarURLConnection) jarPath.openConnection();
        JarFile jarFile = jarConnection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String resourcePath = entry.getName();
            if ((!entry.isDirectory()) && (resourcePath.startsWith(directoryPath))
                    && (searchSubdirectories || !resourcePath.substring(directoryPath.length()).contains("/"))
                    && (filtersApply(resourcePath))) {
                // cannot do new URL(jarPath, resourcePath), somehow leads to duplicated path
                // retest on java 8
                Enumeration<URL> urls = classLoader.getResources(resourcePath);
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();
                    if (url.toExternalForm().startsWith(jarPath.toExternalForm())) {
                        resources.add(url);
                    }
                }
            }
        }
    } catch (IOException e) {
    }
}

From source file:com.jayway.maven.plugins.android.phase04processclasses.DexMojo.java

private void unjar(JarFile jarFile, File outputDirectory) throws IOException {
    for (Enumeration en = jarFile.entries(); en.hasMoreElements();) {
        JarEntry entry = (JarEntry) en.nextElement();
        File entryFile = new File(outputDirectory, entry.getName());
        if (!entryFile.getParentFile().exists() && !entry.getName().startsWith("META-INF")) {
            entryFile.getParentFile().mkdirs();
        }//from   w  ww.  j  a v a  2  s  . co m
        if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
            final InputStream in = jarFile.getInputStream(entry);
            try {
                final OutputStream out = new FileOutputStream(entryFile);
                try {
                    IOUtil.copy(in, out);
                } finally {
                    IOUtils.closeQuietly(out);
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }
}

From source file:com.krikelin.spotifysource.AppInstaller.java

public void installJar() throws IOException, SAXException, ParserConfigurationException {

    java.util.jar.JarFile jar = new java.util.jar.JarFile(app_jar);
    // Get manifest
    java.util.Enumeration<JarEntry> enu = jar.entries();
    while (enu.hasMoreElements()) {
        JarEntry elm = enu.nextElement();
        if (elm.getName().equals("SpotifyAppManifest.xml")) {
            DataInputStream dis = new DataInputStream(jar.getInputStream(elm));
            Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(dis);
            dis.close();/*from w  w  w .  java  2s. c om*/
            // Get package name
            String package_name = d.getDocumentElement().getAttribute("package");

            addPackage(package_name, "packages");
            // Get all activities
            NodeList activities = d.getElementsByTagName("activity");
            for (int i = 0; i < activities.getLength(); i++) {
                Element activity = (Element) activities.item(i);
                String name = activity.getAttribute("name"); // Get the name
                // Append the previous name if it starts with .
                if (name.startsWith(".")) {
                    name = name.replace(".", "");

                }
                if (!name.startsWith(package_name)) {
                    name = package_name + "." + name;

                }
                //addPackage(name,"activities");
                NodeList intentFilters = activity.getElementsByTagName("intent-filter");
                for (int j = 0; j < intentFilters.getLength(); j++) {
                    NodeList actions = ((Element) intentFilters.item(0)).getElementsByTagName("action");
                    for (int k = 0; k < actions.getLength(); k++) {
                        String action_name = ((Element) actions.item(k)).getAttribute("name");
                        addPackage(name, "\\activities\\" + action_name);
                    }

                }
            }
            copyFile(app_jar.getAbsolutePath(), SPContainer.EXTENSION_DIR + "\\jar\\" + package_name + ".jar");
            // Runtime.getRuntime().exec("copy \""+app_jar+"\" \""+SPContainer.EXTENSION_DIR+"\\jar\\"+package_name+".jar\"");

        }
    }

}

From source file:org.openmrs.module.ModuleUtil.java

/**
 * This loops over all FILES in this jar to get the package names. If there is an empty
 * directory in this jar it is not returned as a providedPackage.
 *
 * @param file jar file to look into/*from   w ww. j a  v  a2s.  com*/
 * @return list of strings of package names in this jar
 */
public static Collection<String> getPackagesFromFile(File file) {

    // End early if we're given a non jar file
    if (!file.getName().endsWith(".jar")) {
        return Collections.<String>emptySet();
    }

    Set<String> packagesProvided = new HashSet<String>();

    JarFile jar = null;
    try {
        jar = new JarFile(file);

        Enumeration<JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (jarEntry.isDirectory()) {
                // skip over directory entries, we only care about files
                continue;
            }
            String name = jarEntry.getName();

            // Skip over some folders in the jar/omod
            if (name.startsWith("lib") || name.startsWith("META-INF") || name.startsWith("web/module")) {
                continue;
            }

            Integer indexOfLastSlash = name.lastIndexOf("/");
            if (indexOfLastSlash <= 0) {
                continue;
            }
            String packageName = name.substring(0, indexOfLastSlash);

            packageName = packageName.replaceAll("/", ".");

            if (packagesProvided.add(packageName)) {
                if (log.isTraceEnabled()) {
                    log.trace("Adding module's jarentry with package: " + packageName);
                }
            }
        }

        jar.close();
    } catch (IOException e) {
        log.error("Error while reading file: " + file.getAbsolutePath(), e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                // Ignore quietly
            }
        }
    }

    return packagesProvided;
}

From source file:org.paxle.gui.impl.StyleManager.java

public void setStyle(String name) {
    if (name.equals("default")) {

        ((ServletManager) this.servletManager).unregisterAllResources();
        ((ServletManager) this.servletManager).addResources("/css", "/resources/templates/layout/css");
        ((ServletManager) this.servletManager).addResources("/js", "/resources/js");
        ((ServletManager) this.servletManager).addResources("/images", "/resources/images");

        return;/*from   w  ww .  j a  v a  2s .c om*/
    }

    try {
        File styleFile = new File(this.dataPath, name);
        HttpContext httpContextStyle = new HttpContextStyle(styleFile);

        JarFile styleJarFile = new JarFile(styleFile);
        Enumeration<?> jarEntryEnum = styleJarFile.entries();

        while (jarEntryEnum.hasMoreElements()) {
            JarEntry entry = (JarEntry) jarEntryEnum.nextElement();
            if (entry.isDirectory()) {
                String alias = "/" + entry.getName().substring(0, entry.getName().length() - 1);
                ((ServletManager) this.servletManager).removeResource(alias);
                ((ServletManager) this.servletManager).addResources(alias, alias, httpContextStyle);
            }
        }
    } catch (IOException e) {
        logger.error("io: " + e);
        e.printStackTrace();
    }
    return;
}

From source file:com.l2jserver.service.game.scripting.impl.ecj.EclipseCompilerScriptClassLoader.java

/**
 * AddsLibrary jar/*from  w  w w.j  a v  a 2 s.  c  o m*/
 * 
 * @param file
 *            jar file to add
 * @throws IOException
 *             if any I/O error occur
 */
@Override
public void addLibrary(File file) throws IOException {
    URL fileURL = file.toURI().toURL();
    addURL(fileURL);

    JarFile jarFile = new JarFile(file);

    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();

        String name = entry.getName();
        if (name.endsWith(".class")) {
            name = name.substring(0, name.length() - 6);
            name = name.replace('/', '.');
            libraryClasses.add(name);
        }
    }

    jarFile.close();
}

From source file:org.batfish.common.plugin.PluginConsumer.java

private void loadPluginJar(Path path) {
    /*/*from   www.j  a  v  a  2  s  . c  o  m*/
     * Adapted from
     * http://stackoverflow.com/questions/11016092/how-to-load-classes-at-
     * runtime-from-a-folder-or-jar Retrieved: 2016-08-31 Original Authors:
     * Kevin Crain http://stackoverflow.com/users/2688755/kevin-crain
     * Apfelsaft http://stackoverflow.com/users/1447641/apfelsaft License:
     * https://creativecommons.org/licenses/by-sa/3.0/
     */
    String pathString = path.toString();
    if (pathString.endsWith(".jar")) {
        try {
            URL[] urls = { new URL("jar:file:" + pathString + "!/") };
            URLClassLoader cl = URLClassLoader.newInstance(urls, _currentClassLoader);
            _currentClassLoader = cl;
            Thread.currentThread().setContextClassLoader(cl);
            JarFile jar = new JarFile(path.toFile());
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry element = entries.nextElement();
                String name = element.getName();
                if (element.isDirectory() || !name.endsWith(CLASS_EXTENSION)) {
                    continue;
                }
                String className = name.substring(0, name.length() - CLASS_EXTENSION.length()).replace("/",
                        ".");
                try {
                    cl.loadClass(className);
                    Class<?> pluginClass = Class.forName(className, true, cl);
                    if (!Plugin.class.isAssignableFrom(pluginClass)
                            || Modifier.isAbstract(pluginClass.getModifiers())) {
                        continue;
                    }
                    Constructor<?> pluginConstructor;
                    try {
                        pluginConstructor = pluginClass.getConstructor();
                    } catch (NoSuchMethodException | SecurityException e) {
                        throw new BatfishException(
                                "Could not find default constructor in plugin: '" + className + "'", e);
                    }
                    Object pluginObj;
                    try {
                        pluginObj = pluginConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        throw new BatfishException(
                                "Could not instantiate plugin '" + className + "' from constructor", e);
                    }
                    Plugin plugin = (Plugin) pluginObj;
                    plugin.initialize(this);

                } catch (ClassNotFoundException e) {
                    jar.close();
                    throw new BatfishException("Unexpected error loading classes from jar", e);
                }
            }
            jar.close();
        } catch (IOException e) {
            throw new BatfishException("Error loading plugin jar: '" + path.toString() + "'", e);
        }
    }
}