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:org.datavyu.util.NativeLoader.java

/**
 * Unpacks a native application to a temporary location so that it can be
 * utilized from within java code./*from ww  w .  j  a v a2  s .  c om*/
 *
 * @param appJar The jar containing the native app that you want to unpack.
 * @return The path of the native app as unpacked to a temporary location.
 *
 * @throws Exception If unable to unpack the native app to a temporary
 * location.
 */
public static String unpackNativeApp(final String appJar) throws Exception {
    final String nativeLibraryPath;

    if (nativeLibFolder == null) {
        nativeLibraryPath = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "nativelibs";
        nativeLibFolder = new File(nativeLibraryPath);

        if (!nativeLibFolder.exists()) {
            nativeLibFolder.mkdir();
        }
    }

    // Search the class path for the application jar.
    JarFile jar = null;

    // BugID: 26178921 -- We need to inspect the surefire test class path as
    // well as the regular class path property so that we can scan dependencies
    // during tests.
    String searchPath = System.getProperty("surefire.test.class.path") + File.pathSeparator
            + System.getProperty("java.class.path");

    for (String s : searchPath.split(File.pathSeparator)) {
        // Success! We found a matching jar.
        if (s.endsWith(appJar + ".jar") || s.endsWith(appJar)) {
            jar = new JarFile(s);
        }
    }

    // If we found a jar - it should contain the desired application.
    // decompress as needed.
    if (jar != null) {
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry inFile = entries.nextElement();
            File outFile = new File(nativeLibFolder, inFile.getName());

            // If the file from the jar is a directory, create it.
            if (inFile.isDirectory()) {
                outFile.mkdir();

                // The file from the jar is regular - decompress it.
            } else {
                InputStream in = jar.getInputStream(inFile);

                // Create a temporary output location for the library.
                FileOutputStream out = new FileOutputStream(outFile);
                BufferedOutputStream dest = new BufferedOutputStream(out, BUFFER);
                int count;
                byte[] data = new byte[BUFFER];

                while ((count = in.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }

                dest.flush();
                dest.close();
                out.close();
                in.close();
            }

            loadedLibs.add(outFile);
        }

        // Unable to find jar file - abort decompression.
    } else {
        System.err.println("Unable to find jar file for unpacking: " + appJar + ". Java classpath is:");

        for (String s : System.getProperty("java.class.path").split(File.pathSeparator)) {
            System.err.println("    " + s);
        }

        throw new Exception("Unable to find '" + appJar + "' for unpacking.");
    }

    return nativeLibFolder.getAbsolutePath();
}

From source file:org.wso2.developerstudio.eclipse.utils.file.FileUtils.java

@SuppressWarnings("resource")
private static ArrayList<String> getPackages(File jarFile) {

    ArrayList<String> packages = new ArrayList<String>();

    JarFile jar = null;
    try {//from   www  .  ja  v  a2 s.  c  o  m
        jar = new JarFile(jarFile);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (jar != null) {
        Enumeration<? extends JarEntry> enumeration = jar.entries();
        // Iterates into the files in the jar file
        while (enumeration.hasMoreElements()) {

            ZipEntry zipEntry = enumeration.nextElement();
            if (zipEntry.getName().endsWith(".class")) {
                // Relative path of file into the jar.
                String className = zipEntry.getName();
                String packageName = new File(className).getParent();
                packageName = packageName.replace(File.separatorChar, '.');
                if (!packages.contains(packageName)) {
                    packages.add(packageName);
                }
            }
        }
    }
    return packages;
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Add the SHA1 of every file to the manifest, creating it if necessary. */
private static Manifest addDigestsToManifest(final JarFile jar) throws IOException, GeneralSecurityException {
    final Manifest input = jar.getManifest();
    final Manifest output = new Manifest();

    final Attributes main = output.getMainAttributes();
    main.putValue("Manifest-Version", MANIFEST_VERSION);
    main.putValue("Created-By", CREATED_BY);

    // We sort the input entries by name, and add them to the output manifest in sorted order.
    // We expect that the output map will be deterministic.
    final TreeMap<String, JarEntry> byName = new TreeMap<>();
    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        byName.put(entry.getName(), entry);
    }/*from  w ww.j  a va  2s  .  c om*/

    final MessageDigest md = MessageDigest.getInstance("SHA1");
    final byte[] buffer = new byte[4096];
    int num;

    for (JarEntry entry : byName.values()) {
        final String name = entry.getName();
        if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)
                && !name.equals(CERT_RSA_NAME)) {
            InputStream data = jar.getInputStream(entry);
            while ((num = data.read(buffer)) > 0) {
                md.update(buffer, 0, num);
            }

            Attributes attr = null;
            if (input != null) {
                attr = input.getAttributes(name);
            }
            attr = attr != null ? new Attributes(attr) : new Attributes();
            attr.putValue("SHA1-Digest", base64encode(md.digest()));
            output.getEntries().put(name, attr);
        }
    }

    return output;
}

From source file:org.sonar.server.util.ClassLoaderUtils.java

/**
 * Finds directories and files within a given directory and its subdirectories.
 *
 * @param classLoader//  www .j a v  a 2 s  . co m
 * @param rootPath    the root directory, for example org/sonar/sqale, or a file in this root directory, for example org/sonar/sqale/index.txt
 * @param predicate
 * @return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo", "org/sonar/sqale/foo/bar.txt}. Never null.
 */
public static Collection<String> listResources(ClassLoader classLoader, String rootPath,
        Predicate<String> predicate) {
    String jarPath = null;
    JarFile jar = null;
    try {
        Collection<String> paths = Lists.newArrayList();
        URL root = classLoader.getResource(rootPath);
        if (root != null) {
            checkJarFile(root);

            // Path of the root directory
            // Examples :
            // org/sonar/sqale/index.txt -> rootDirectory is org/sonar/sqale
            // org/sonar/sqale/ -> rootDirectory is org/sonar/sqale
            // org/sonar/sqale -> rootDirectory is org/sonar/sqale
            String rootDirectory = rootPath;
            if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) {
                rootDirectory = StringUtils.substringBeforeLast(rootPath, "/");
            }
            // strip out only the JAR file
            jarPath = root.getPath().substring(5, root.getPath().indexOf('!'));
            jar = new JarFile(URLDecoder.decode(jarPath, CharEncoding.UTF_8));
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String name = entries.nextElement().getName();
                if (name.startsWith(rootDirectory) && predicate.test(name)) {
                    paths.add(name);
                }
            }
        }
        return paths;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    } finally {
        closeJar(jar, jarPath);
    }
}

From source file:nl.tue.gale.ae.config.GaleContextLoader.java

private void findInJar(ServletContext sc, String path, List<String> locations) {
    try {//  w  ww  . j  a  v  a  2s .c o  m
        JarFile jar = new JarFile(sc.getRealPath(path));
        for (JarEntry entry : enumIterable(jar.entries())) {
            if (entry.getName().endsWith("-galeconfig.xml"))
                locations.add("classpath:" + entry.getName());
        }
        jar.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.junit.extensions.dynamicsuite.engine.ClassPathScanner.java

private void loadJarEntries(JarFile jar) {
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {

        JarEntry element = entries.nextElement();
        String name = element.getName();
        if (name.toLowerCase().endsWith(".class")) {
            String className = StringUtils.replace(name, "/", ".");
            className = StringUtils.removeEnd(className, ".class");
            foundClasses.add(className);
        }/* w  w w .  j av a  2  s. c om*/
    }
}

From source file:org.sonar.server.platform.ClassLoaderUtils.java

/**
 * Finds directories and files within a given directory and its subdirectories.
 *
 * @param classLoader/*ww w.  j  a  va  2  s .  c  o m*/
 * @param rootPath    the root directory, for example org/sonar/sqale, or a file in this root directory, for example org/sonar/sqale/index.txt
 * @param predicate
 * @return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo", "org/sonar/sqale/foo/bar.txt}. Never null.
 */
static Collection<String> listResources(ClassLoader classLoader, String rootPath, Predicate<String> predicate) {
    String jarPath = null;
    JarFile jar = null;
    try {
        Collection<String> paths = Lists.newArrayList();
        URL root = classLoader.getResource(rootPath);
        if (root != null) {
            checkJarFile(root);

            // Path of the root directory
            // Examples :
            // org/sonar/sqale/index.txt  -> rootDirectory is org/sonar/sqale
            // org/sonar/sqale/  -> rootDirectory is org/sonar/sqale
            // org/sonar/sqale  -> rootDirectory is org/sonar/sqale
            String rootDirectory = rootPath;
            if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) {
                rootDirectory = StringUtils.substringBeforeLast(rootPath, "/");
            }
            //strip out only the JAR file
            jarPath = root.getPath().substring(5, root.getPath().indexOf("!"));
            jar = new JarFile(URLDecoder.decode(jarPath, CharEncoding.UTF_8));
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String name = entries.nextElement().getName();
                if (name.startsWith(rootDirectory) && predicate.apply(name)) {
                    paths.add(name);
                }
            }
        }
        return paths;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    } finally {
        closeJar(jar, jarPath);
    }
}

From source file:org.eclipse.licensing.eclipse_licensing_plugin.InjectLicensingMojo.java

private void extractLicensingBaseFiles() throws IOException {
    JarFile jar = new JarFile(getLicensingBasePlugin());
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.startsWith("org")) {
            File file = new File(classesDirectory, entryName);
            if (entry.isDirectory()) {
                file.mkdir();//from   w  w  w. j  a  v  a2s.co  m
            } else {
                InputStream is = jar.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(file);
                while (is.available() > 0) {
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            }
        }
    }
    jar.close();
}

From source file:org.netbeans.nbbuild.MakeJnlp2.java

/** return alias if signed, or null if not */
private static String isSigned(File f) throws IOException {
    JarFile jar = new JarFile(f);
    try {// ww w .j  ava2 s .co m
        Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            Matcher m = SF.matcher(en.nextElement().getName());
            if (m.matches()) {
                return m.group(1);
            }
        }
        return null;
    } finally {
        jar.close();
    }
}

From source file:rapture.plugin.app.JarBasedSandboxLoader.java

private String[] getResourceFiles(String path, String variant) throws Exception {
    URL dirURL = SelfInstaller.class.getClass().getResource(path);
    String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); // strip out only the JAR file
    JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in
                                                   // jar
    Set<String> result = new HashSet<String>(); // avoid duplicates in case
                                                // it is a subdirectory
    String checkPath = path.substring(1);
    String checkVariant = variant != null ? checkPath.replaceFirst(PluginSandbox.CONTENT, variant).concat("/")
            : null;//from ww w.  j a v a2s  .c o  m
    while (entries.hasMoreElements()) {
        String name = entries.nextElement().getName();
        if (!name.endsWith("/") && // don't return directories
                (name.startsWith(checkPath) || (checkVariant != null && name.startsWith(checkVariant)))) { // filter according to the path
            result.add(name);
        }
    }
    jar.close();
    return result.toArray(new String[result.size()]);

}