Example usage for java.util.jar JarEntry isDirectory

List of usage examples for java.util.jar JarEntry isDirectory

Introduction

In this page you can find the example usage for java.util.jar JarEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:org.apache.storm.utils.ServerUtils.java

/**
 * Unpack matching files from a jar. Entries inside the jar that do
 * not match the given pattern will be skipped.
 *
 * @param jarFile the .jar file to unpack
 * @param toDir the destination directory into which to unpack the jar
 *//*  ww  w  .  j av  a 2s  .c  o m*/
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    ensureDirectory(file.getParentFile());
                    OutputStream out = new FileOutputStream(file);
                    try {
                        copyBytes(in, out, 8192);
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:org.opoo.util.ClassPathUtils.java

/**
 * /*from   w w  w  . j  a va 2s .  c  o m*/
 * @param jarFileURL
 * @param sourcePath
 * @param destination
 * @param overwrite
 * @throws Exception
 */
protected static void copyJarPath(URL jarFileURL, String sourcePath, File destination, boolean overwrite)
        throws Exception {
    //URL jarFileURL = ResourceUtils.extractJarFileURL(url);
    if (!sourcePath.endsWith("/")) {
        sourcePath += "/";
    }
    String root = jarFileURL.toString() + "!/";
    if (!root.startsWith("jar:")) {
        root = "jar:" + root;
    }

    JarFile jarFile = new JarFile(new File(jarFileURL.toURI()));
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        String name = jarEntry.getName();
        //log.debug(name + "." + sourcePath + "." + name.startsWith(sourcePath));
        if (name.startsWith(sourcePath)) {
            String relativePath = name.substring(sourcePath.length());
            //log.debug("relativePath: " + relativePath);
            if (relativePath != null && relativePath.length() > 0) {
                File tmp = new File(destination, relativePath);
                //not exists or overwrite permitted
                if (overwrite || !tmp.exists()) {
                    if (jarEntry.isDirectory()) {
                        tmp.mkdirs();
                        if (IS_DEBUG_ENABLED) {
                            log.debug("Create directory: " + tmp);
                        }
                    } else {
                        File parent = tmp.getParentFile();
                        if (!parent.exists()) {
                            parent.mkdirs();
                        }
                        //1.FileCopyUtils.copy
                        //InputStream is = jarFile.getInputStream(jarEntry);
                        //FileCopyUtils.copy(is, new FileOutputStream(tmp));

                        //2. url copy
                        URL u = new URL(root + name);
                        //log.debug(u.toString());
                        FileUtils.copyURLToFile(u, tmp);
                        if (IS_DEBUG_ENABLED) {
                            log.debug("Copyed file '" + u + "' to '" + tmp + "'.");
                        }
                    }
                }
            }
        }
    }

    try {
        jarFile.close();
    } catch (Exception ie) {
    }
}

From source file:com.amalto.core.query.SystemStorageTest.java

private static Collection<String> getConfigFiles() throws Exception {
    URL data = InitDBUtil.class.getResource("data"); //$NON-NLS-1$
    List<String> result = new ArrayList<String>();
    if ("jar".equals(data.getProtocol())) { //$NON-NLS-1$
        JarURLConnection connection = (JarURLConnection) data.openConnection();
        JarEntry entry = connection.getJarEntry();
        JarFile file = connection.getJarFile();
        Enumeration<JarEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            JarEntry e = entries.nextElement();
            if (e.getName().startsWith(entry.getName()) && !e.isDirectory()) {
                result.add(IOUtils.toString(file.getInputStream(e)));
            }//from ww  w.ja va 2  s  .  c o m
        }
    } else {
        Collection<File> files = FileUtils.listFiles(new File(data.toURI()), new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                return true;
            }

            @Override
            public boolean accept(File file, String s) {
                return true;
            }
        }, new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                return !".svn".equals(file.getName()); //$NON-NLS-1$
            }

            @Override
            public boolean accept(File file, String s) {
                return !".svn".equals(file.getName()); //$NON-NLS-1$
            }
        });
        for (File f : files) {
            result.add(IOUtils.toString(new FileInputStream(f)));
        }
    }
    return result;
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

/**
 * Does the named signature already exist in the JAR file?
 *
 * @param jarFile//from  w  ww. j a  v  a 2s  .  co m
 *            JAR file
 * @param signatureName
 *            Signature name
 * @return True if it does, false otherwise
 * @throws IOException
 *             If an I/O problem occurs while examining the JAR file
 */
public static boolean hasSignature(File jarFile, String signatureName) throws IOException {
    JarFile jar = null;

    try {
        // Look for signature file (DSA or RSA)
        jar = new JarFile(jarFile);

        for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
            if (!jarEntry.isDirectory()) {
                if ((jarEntry.getName().equalsIgnoreCase(
                        MessageFormat.format(METAINF_FILE_LOCATION, signatureName, DSA_SIG_BLOCK_EXT)))
                        || (jarEntry.getName().equalsIgnoreCase(MessageFormat.format(METAINF_FILE_LOCATION,
                                signatureName, RSA_SIG_BLOCK_EXT)))) {
                    return true;
                }
            }
        }

        return false;
    } finally {
        IOUtils.closeQuietly(jar);
    }
}

From source file:AndroidUninstallStock.java

public static LinkedList<String> getLibsInApk(Path apk) throws IOException {
    LinkedList<String> libs = new LinkedList<String>();
    try (JarInputStream jar = new JarInputStream(
            Files.newInputStream(apk, new StandardOpenOption[] { StandardOpenOption.READ }))) {
        JarEntry jent;
        int pos;//from   w  w w  .  j  a v a  2 s.c  om
        while ((jent = jar.getNextJarEntry()) != null) {
            if (!jent.isDirectory() && ((pos = jent.getName().indexOf("lib/")) == 0 || pos == 1)) {
                libs.add(jent.getName());
            }
        }
    }
    return libs;
}

From source file:io.tempra.AppServer.java

public static void copyJarResourceToFolder(JarURLConnection jarConnection, File destDir) {

    try {/*from  w w w. ja v a  2 s  . com*/
        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:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static void writeJarEntries(JarFile jar, JarOutputStream jos, String signatureName) throws IOException {

    for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        if (!jarEntry.isDirectory()) {
            String entryName = jarEntry.getName();

            // Signature files not to write across
            String sigFileLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, SIGNATURE_EXT)
                    .toUpperCase();//from w  ww .j a  va 2s . com
            String dsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    DSA_SIG_BLOCK_EXT);
            String rsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    RSA_SIG_BLOCK_EXT);

            // Do not write across existing manifest or matching signature files
            if ((!entryName.equalsIgnoreCase(MANIFEST_LOCATION))
                    && (!entryName.equalsIgnoreCase(sigFileLocation))
                    && (!entryName.equalsIgnoreCase(dsaSigBlockLocation))
                    && (!entryName.equalsIgnoreCase(rsaSigBlockLocation))) {
                // New JAR entry based on original
                JarEntry newJarEntry = new JarEntry(jarEntry.getName());
                newJarEntry.setMethod(jarEntry.getMethod());
                newJarEntry.setCompressedSize(jarEntry.getCompressedSize());
                newJarEntry.setCrc(jarEntry.getCrc());
                jos.putNextEntry(newJarEntry);

                InputStream jis = null;

                try {
                    jis = jar.getInputStream(jarEntry);

                    byte[] buffer = new byte[2048];
                    int read = -1;

                    while ((read = jis.read(buffer)) != -1) {
                        jos.write(buffer, 0, read);
                    }

                    jos.closeEntry();
                } finally {
                    IOUtils.closeQuietly(jis);
                }
            }
        }
    }
}

From source file:eu.trentorise.opendata.josman.Josmans.java

/**
 *
 * Extracts the files starting with dirPath from {@code file} to
 * {@code destDir}//from   ww  w  . ja  v  a 2  s.com
 *
 * @param dirPath the prefix used for filtering. If empty the whole jar
 * content is extracted.
 */
public static void copyDirFromJar(File jarFile, File destDir, String dirPath) {
    checkNotNull(jarFile);
    checkNotNull(destDir);
    checkNotNull(dirPath);

    String normalizedDirPath;
    if (dirPath.startsWith("/")) {
        normalizedDirPath = dirPath.substring(1);
    } else {
        normalizedDirPath = dirPath;
    }

    try {
        JarFile jar = new JarFile(jarFile);
        java.util.Enumeration enumEntries = jar.entries();
        while (enumEntries.hasMoreElements()) {
            JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
            if (jarEntry.getName().startsWith(normalizedDirPath)) {
                File f = new File(
                        destDir + File.separator + jarEntry.getName().substring(normalizedDirPath.length()));

                if (jarEntry.isDirectory()) { // if its a directory, create it
                    f.mkdirs();
                    continue;
                } else {
                    f.getParentFile().mkdirs();
                }

                InputStream is = jar.getInputStream(jarEntry); // get the input stream
                FileOutputStream fos = new FileOutputStream(f);
                IOUtils.copy(is, fos);
                fos.close();
                is.close();
            }

        }
    } catch (Exception ex) {
        throw new RuntimeException("Error while extracting jar file! Jar source: " + jarFile.getAbsolutePath()
                + " destDir = " + destDir.getAbsolutePath(), ex);
    }
}

From source file:net.aepik.alasca.core.ldap.Schema.java

/**
 * Retourne l'ensemble des syntaxes connues, qui sont
 * contenues dans le package 'ldap.syntax'.
 * @return String[] L'ensemble des noms de classes de syntaxes.
 *//* w  w w  .  j a v  a2s .c  om*/
public static String[] getSyntaxes() {
    String[] result = null;
    try {
        String packageName = getSyntaxPackageName();
        URL url = Schema.class.getResource("/" + packageName.replace('.', '/'));
        if (url == null) {
            return null;
        }
        if (url.getProtocol().equals("jar")) {
            Vector<String> vectTmp = new Vector<String>();
            int index = url.getPath().indexOf('!');
            String path = URLDecoder.decode(url.getPath().substring(index + 1), "UTF-8");
            JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8"));
            if (path.charAt(0) == '/') {
                path = path.substring(1);
            }
            Enumeration<JarEntry> jarFiles = jarFile.entries();
            while (jarFiles.hasMoreElements()) {
                JarEntry tmp = jarFiles.nextElement();
                //
                // Pour chaque fichier dans le jar, on regarde si c'est un
                // fichier de classe Java.
                //
                if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class")
                        && tmp.getName().startsWith(path)) {
                    int i = tmp.getName().lastIndexOf('/');
                    String classname = tmp.getName().substring(i + 1, tmp.getName().length() - 6);
                    vectTmp.add(classname);
                }
            }
            jarFile.close();
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                result[i] = vectTmp.elementAt(i);
            }
        } else if (url.getProtocol().equals("file")) {
            //
            // On cr le fichier associ pour parcourir son contenu.
            // En l'occurence, c'est un dossier.
            //
            File[] files = (new File(url.toURI())).listFiles();
            //
            // On liste tous les fichiers qui sont dedans.
            // On les stocke dans un vecteur ...
            //
            Vector<File> vectTmp = new Vector<File>();
            for (File f : files) {
                if (!f.isDirectory()) {
                    vectTmp.add(f);
                }
            }
            //
            // ... pour ensuite les mettres dans le tableau de resultat.
            //
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                String name = vectTmp.elementAt(i).getName();
                int a = name.indexOf('.');
                name = name.substring(0, a);
                result[i] = name;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (result != null) {
        Arrays.sort(result);
    }
    return result;
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

/**
 * Sign a JAR file outputting the signed JAR to a different file.
 *
 * @param jarFile//from ww  w  .ja  va 2 s.  c om
 *            JAR file to sign
 * @param signedJarFile
 *            Output file for signed JAR
 * @param privateKey
 *            Private key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param signatureType
 *            Signature type
 * @param signatureName
 *            Signature name
 * @param signer
 *            Signer
 * @param digestType
 *            Digest type
 * @param tsaUrl
 *            TSA URL
 * @throws IOException
 *             If an I/O problem occurs while signing the JAR file
 * @throws CryptoException
 *             If a crypto problem occurs while signing the JAR file
 */
public static void sign(File jarFile, File signedJarFile, PrivateKey privateKey,
        X509Certificate[] certificateChain, SignatureType signatureType, String signatureName, String signer,
        DigestType digestType, String tsaUrl, Provider provider) throws IOException, CryptoException {

    JarFile jar = null;
    JarOutputStream jos = null;

    try {
        // Replace illegal characters in signature name
        signatureName = convertSignatureName(signatureName);

        // Create Jar File accessor for JAR to be signed
        jar = new JarFile(jarFile);

        // Write manifest content to here
        StringBuilder sbManifest = new StringBuilder();

        // Write out main attributes to manifest
        String manifestMainAttrs = getManifestMainAttrs(jar, signer);
        sbManifest.append(manifestMainAttrs);

        // Write out all entries' attributes to manifest
        String entryManifestAttrs = getManifestEntriesAttrs(jar);

        if (entryManifestAttrs.length() > 0) {
            // Only output if there are any
            sbManifest.append(entryManifestAttrs);
            sbManifest.append(CRLF);
        }

        // Write signature file to here
        StringBuilder sbSf = new StringBuilder();

        // Write out digests to manifest and signature file

        // Sign each JAR entry...
        for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) jarEntries.nextElement();

            if (!jarEntry.isDirectory()) // Ignore directories
            {
                if (!ignoreJarEntry(jarEntry)) // Ignore some entries (existing signature files)
                {
                    // Get the digest of the entry as manifest attributes
                    String manifestEntry = getDigestManifestAttrs(jar, jarEntry, digestType);

                    // Add it to the manifest string buffer
                    sbManifest.append(manifestEntry);

                    // Get the digest of manifest entries created above
                    byte[] mdSf = DigestUtil.getMessageDigest(manifestEntry.getBytes(), digestType);
                    byte[] mdSf64 = Base64.encode(mdSf);
                    String mdSf64Str = new String(mdSf64);

                    // Write this digest as entries in signature file
                    sbSf.append(createAttributeText(NAME_ATTR, jarEntry.getName()));
                    sbSf.append(CRLF);
                    sbSf.append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()),
                            mdSf64Str));
                    sbSf.append(CRLF);
                    sbSf.append(CRLF);
                }
            }
        }

        // Manifest file complete - get base 64 encoded digest of its content for inclusion in signature file
        byte[] manifest = sbManifest.toString().getBytes();

        byte[] digestMf = DigestUtil.getMessageDigest(manifest, digestType);
        String digestMfStr = new String(Base64.encode(digestMf));

        // Get base 64 encoded digest of manifest's main attributes for inclusion in signature file
        byte[] mainfestMainAttrs = manifestMainAttrs.getBytes();

        byte[] digestMfMainAttrs = DigestUtil.getMessageDigest(mainfestMainAttrs, digestType);
        String digestMfMainAttrsStr = new String(Base64.encode(digestMfMainAttrs));

        // Write out Manifest Digest, Created By and Signature Version to start of signature file
        sbSf.insert(0, CRLF);
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(MessageFormat.format(DIGEST_MANIFEST_ATTR, digestType.jce()), digestMfStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(
                        MessageFormat.format(DIGEST_MANIFEST_MAIN_ATTRIBUTES_ATTR, digestType.jce()),
                        digestMfMainAttrsStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(CREATED_BY_ATTR, signer));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(SIGNATURE_VERSION_ATTR, SIGNATURE_VERSION));

        // Signature file complete
        byte[] sf = sbSf.toString().getBytes();

        // Create output stream to write signed JAR
        jos = new JarOutputStream(new FileOutputStream(signedJarFile));

        // Write JAR files from JAR to be signed to signed JAR
        writeJarEntries(jar, jos, signatureName);

        // Write manifest to signed JAR
        writeManifest(manifest, jos);

        // Write signature file to signed JAR
        writeSignatureFile(sf, signatureName, jos);

        // Create signature block and write it out to signed JAR
        byte[] sigBlock = createSignatureBlock(sf, privateKey, certificateChain, signatureType, tsaUrl,
                provider);
        writeSignatureBlock(sigBlock, signatureType, signatureName, jos);
    } finally {
        IOUtils.closeQuietly(jar);
        IOUtils.closeQuietly(jos);
    }
}