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:com.taobao.android.builder.tools.asm.ClazzBasicHandler.java

public void execute() throws IOException {

    logger.info("[ClazzReplacer] rewriteJar from " + jar.getAbsolutePath() + " to " + outJar.getAbsolutePath());

    JarFile jarFile = new JarFile(jar);

    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));

    Enumeration<JarEntry> jarFileEntries = jarFile.entries();

    while (jarFileEntries.hasMoreElements()) {

        JarEntry ze = jarFileEntries.nextElement();

        String pathName = ze.getName();

        logger.info(jar.getAbsolutePath() + "->" + pathName);

        if (!pathName.endsWith(".class")) {
            justCopy(jarFile, jos, ze, pathName);
            continue;
        }// ww w.ja v a 2  s .  c  o  m

        handleClazz(jarFile, jos, ze, pathName);

    }

    jarFile.close();
    //        IOUtils.closeQuietly(fileOutputStream);
    IOUtils.closeQuietly(jos);
}

From source file:org.twdata.pkgscanner.InternalScanner.java

/**
 * Finds matching classes within a jar files that contains a folder structure
 * matching the package structure.  If the File is not a JarFile or does not exist a warning
 * will be logged, but no error will be raised.
 *
 * @param test    a Test used to filter the classes that are discovered
 * @param file the jar file to be examined for classes
 * @return List of packages to export.//from  w ww .  j  a v  a 2s. c om
 */
List<ExportPackage> loadImplementationsInJar(Test test, File file) {

    final List<ExportPackage> localExports = new ArrayList<ExportPackage>();
    Set<String> packages = this.jarContentCache.get(file.getPath());
    if (packages == null) {
        packages = new HashSet<String>();
        try {
            final JarFile jarFile = new JarFile(file);

            for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
                final JarEntry entry = e.nextElement();
                final String name = entry.getName();
                if (!entry.isDirectory()) {
                    String pkg = name;
                    final int pos = pkg.lastIndexOf('/');
                    if (pos > -1) {
                        pkg = pkg.substring(0, pos);
                    }
                    pkg = pkg.replace('/', '.');
                    final boolean newlyAdded = packages.add(pkg);
                    if (newlyAdded && this.log.isDebugEnabled()) {
                        // Use newlyAdded as we don't want to log duplicates
                        this.log.debug(String.format("Found package '%s' in jar file [%s]", pkg, file));
                    }
                }
            }
        } catch (final IOException ioe) {
            this.log.error("Could not search jar file '" + file + "' for classes matching criteria: " + test
                    + " due to an IOException" + ioe);
            return Collections.emptyList();
        } finally {
            // set the cache, even if the scan produced an error
            this.jarContentCache.put(file.getPath(), packages);
        }
    }

    final Set<String> scanned = new HashSet<String>();
    for (final String pkg : packages) {
        if (!scanned.contains(pkg)) {
            if (test.matchesPackage(pkg)) {
                localExports.add(new ExportPackage(pkg, determinePackageVersion(file, pkg), file));
            }
            scanned.add(pkg);
        }
    }

    return localExports;
}

From source file:com.migratebird.script.repository.impl.ArchiveScriptLocation.java

protected SortedSet<Script> loadScriptsFromJar(final JarFile jarFile, String subPath) {
    SortedSet<Script> scripts = new TreeSet<Script>();
    for (Enumeration<JarEntry> jarEntries = jarFile.entries(); jarEntries.hasMoreElements();) {
        final JarEntry jarEntry = jarEntries.nextElement();
        String fileName = jarEntry.getName();
        if (LOCATION_PROPERTIES_FILENAME.equals(fileName) || !isScriptFileName(fileName)) {
            continue;
        }/*from   w w w  . j av  a2 s .c  o m*/

        String relativeScriptName = jarEntry.getName();
        if (subPath != null) {
            if (!fileName.startsWith(subPath)) {
                continue;
            }
            relativeScriptName = relativeScriptName.substring(subPath.length());
        }
        ScriptContentHandle scriptContentHandle = new ScriptContentHandle(scriptEncoding,
                ignoreCarriageReturnsWhenCalculatingCheckSum) {
            @Override
            protected InputStream getScriptInputStream() {
                try {
                    return jarFile.getInputStream(jarEntry);
                } catch (IOException e) {
                    throw new MigrateBirdException("Error while reading jar entry " + jarEntry, e);
                }
            }
        };
        Long fileLastModifiedAt = jarEntry.getTime();
        Script script = scriptFactory.createScriptWithContent(relativeScriptName, fileLastModifiedAt,
                scriptContentHandle);
        scripts.add(script);
    }
    return scripts;
}

From source file:com.stacksync.desktop.Environment.java

public void copyResourcesFromJar(JarURLConnection jarConnection, File destDir) {

    try {//from www  .ja  v a 2s  .co m
        JarFile jarFile = jarConnection.getJarFile();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:com.android.builder.testing.MockableJarGenerator.java

public void createMockableJar(File input, File output) throws IOException {
    Preconditions.checkState(output.createNewFile(), "Output file [%s] already exists.",
            output.getAbsolutePath());//  w ww .  j a  va2s. c  o  m

    JarFile androidJar = null;
    JarOutputStream outputStream = null;
    try {
        androidJar = new JarFile(input);
        outputStream = new JarOutputStream(new FileOutputStream(output));

        for (JarEntry entry : Collections.list(androidJar.entries())) {
            InputStream inputStream = androidJar.getInputStream(entry);

            if (entry.getName().endsWith(".class")) {
                if (!skipClass(entry.getName().replace("/", "."))) {
                    rewriteClass(entry, inputStream, outputStream);
                }
            } else {
                outputStream.putNextEntry(entry);
                ByteStreams.copy(inputStream, outputStream);
            }

            inputStream.close();
        }
    } finally {
        if (androidJar != null) {
            androidJar.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:org.nuxeo.osgi.application.FrameworkBootstrap.java

protected void extractNestedJars(File file, File tmpDir) throws IOException {
    JarFile jarFile = new JarFile(file);
    String fileName = file.getName();
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (entry.getName().endsWith(".jar")) {
            String name = path.replace('/', '_');
            File dest = new File(tmpDir, fileName + '-' + name);
            extractNestedJar(jarFile, entry, dest);
            loader.addURL(dest.toURI().toURL());
        }//from   w ww.  j  a  v  a  2 s .co  m
    }
}

From source file:org.apache.hyracks.maven.license.GenerateFileMojo.java

private SortedMap<String, JarEntry> gatherMatchingEntries(JarFile jarFile, Predicate<JarEntry> filter) {
    SortedMap<String, JarEntry> matches = new TreeMap<>();
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (filter.test(entry)) {
            matches.put(entry.getName(), entry);
        }//from   w  w  w .j a v a  2  s  .com
    }
    return matches;
}

From source file:com.izforge.izpack.compiler.packager.impl.Packager.java

private boolean isNotSignedJar(File file) throws IOException {
    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().startsWith("META-INF") && entry.getName().endsWith(".SF")) {
            jar.close();/*from   ww  w.j  av a  2  s.c o m*/
            return false;
        }
    }
    jar.close();
    return true;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private void indexJar(URL url, File jar) throws IOException {
    JarFile jarFile = new JarFile(jar);
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        cachedFiles.put(entry.getName(), url);
    }//from  w ww  . j a  va 2  s.  co m
    jarFile.close();
    cachedJars.put(url, jar);
}

From source file:com.kotcrab.vis.editor.module.editor.PluginLoaderModule.java

private void loadPluginsJars() throws IOException {
    Array<URL> urls = new Array<>();

    for (PluginDescriptor descriptor : pluginsToLoad) {
        for (FileHandle lib : descriptor.libs)
            urls.add(new URL("jar:file:" + lib.path() + "!/"));

        urls.add(new URL("jar:file:" + descriptor.file.path() + "!/"));
    }/*from   w  w  w.ja  va 2s  .co  m*/

    URLClassLoader classLoader = ChildFirstURLClassLoader.newInstance(urls.toArray(URL.class),
            Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(classLoader);

    for (PluginDescriptor descriptor : pluginsToLoad) {
        try {
            if (descriptor.compatibility != App.PLUGIN_COMPATIBILITY_CODE)
                Log.warn(TAG, "Loading: " + descriptor.folderName
                        + " (compatibility code mismatch! Will try to load anyway!)");
            else
                Log.debug(TAG, "Loading: " + descriptor.folderName);

            currentlyLoadingPlugin = descriptor.folderName;

            JarFile jarFile = new JarFile(descriptor.file.path());
            loadJarClasses(classLoader, descriptor, jarFile.entries());
            IOUtils.closeQuietly(jarFile);
        } catch (IOException | ReflectiveOperationException | LinkageError e) {
            loadingCurrentPluginFailed(e);
        }
    }
}