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:JarUtil.java

/**
 * Extracts the given resource from a jar-file to the specified directory.
 * //from ww  w. jav  a 2s  .c  om
 * @param jarFile
 *            The jar file which should be unpacked
 * @param resource
 *            The name of a resource in the jar
 * @param targetDir
 *            The directory to which the jar-content should be extracted.
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void unjar(File jarFile, String resource, File targetDir)
        throws FileNotFoundException, IOException {
    // clear target directory:
    if (targetDir.exists()) {
        targetDir.delete();
    }
    // create new target directory:
    targetDir.mkdirs();
    // read jar-file:
    String targetPath = targetDir.getAbsolutePath() + File.separatorChar;
    byte[] buffer = new byte[1024 * 1024];
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            // do not copy anything from the package cache:
            if (entry.getName().equals(resource)) {
                String path = targetPath + entry.getName();
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream out = new FileOutputStream(file);
                InputStream in = input.getInputStream(entry);
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                in.close();
                out.close();
            }
        }
    }
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojoTest.java

private static void compareJarContents(File orgJar, File actualJar) throws IOException {
    try (JarInputStream jis1 = new JarInputStream(new FileInputStream(orgJar));
            JarInputStream jis2 = new JarInputStream(new FileInputStream(actualJar))) {
        JarEntry je1 = null;
        while ((je1 = jis1.getNextJarEntry()) != null) {
            if (je1.isDirectory())
                continue;

            JarEntry je2 = null;//w w w  .  ja v a 2s  .  com
            while ((je2 = jis2.getNextJarEntry()) != null) {
                if (!je2.isDirectory())
                    break;
            }

            assertEquals(je1.getName(), je2.getName());
            assertEquals(je1.getSize(), je2.getSize());

            try {
                byte[] buf1 = IOUtils.toByteArray(jis1);
                byte[] buf2 = IOUtils.toByteArray(jis2);

                assertArrayEquals("Contents not equal: " + je1.getName(), buf1, buf2);
            } finally {
                jis1.closeEntry();
                jis2.closeEntry();
            }
        }
    }
}

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   www .j a  v a  2s . 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.orbisgis.core.plugin.BundleTools.java

private static void parseJar(File jarFilePath, Set<String> packages) throws IOException {
    JarFile jar = new JarFile(jarFilePath);
    Enumeration<? extends JarEntry> entryEnum = jar.entries();
    while (entryEnum.hasMoreElements()) {
        JarEntry entry = entryEnum.nextElement();
        if (!entry.isDirectory()) {
            final String path = entry.getName();
            if (path.endsWith(".class")) {
                // Extract folder
                String parentPath = (new File(path)).getParent();
                if (parentPath != null) {
                    packages.add(parentPath.replace(File.separator, "."));
                }// w w  w  .  j  a v  a  2 s.  c om
            }
        }
    }
}

From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java

private static void expandJarTo(JarFile jarFile, String outputPath) throws IOException {
    List<JarEntry> entries = CollectionUtil.toCollection(ArrayList.class, jarFile.entries());
    for (JarEntry entry : entries) {
        if (entry.isDirectory()) {
            // ignore directory
        } else {/*from  ww  w.  ja v  a  2 s. c  o  m*/
            // 
            File efile = new File(outputPath, entry.getName());
            efile.getParentFile().mkdirs();
            InputStream in = new BufferedInputStream(jarFile.getInputStream(entry));
            OutputStream out = new BufferedOutputStream(new FileOutputStream(efile));
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:org.apache.wiki.util.ClassUtil.java

/**
 * Searchs for all the files in classpath under a given package, for a given {@link JarURLConnection}.
 * /*w  w  w  .  j  a v a 2  s . c  om*/
 * @param results collection in which the found entries are stored
 * @param jurlcon given {@link JarURLConnection} to search in.
 * @param rootPackage base package.
 */
static void jarEntriesUnder(List<String> results, JarURLConnection jurlcon, String rootPackage) {
    JarFile jar = null;
    try {
        jar = jurlcon.getJarFile();
        log.debug("scanning [" + jar.getName() + "]");
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(rootPackage) && !entry.isDirectory()) {
                results.add(entry.getName());
            }
        }
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ioe) {
                log.error(ioe.getMessage(), ioe);
            }
        }
    }
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

/**
 * Get a list of resources from class path directory. Attention: path must
 * be a path !/*from  ww w.j a  v  a2 s. c o  m*/
 *
 * @param path
 * @return
 * @throws IOException
 * @throws de.unibi.techfak.bibiserv.util.codegen.CodeGenParserException
 */
public static List<String> getClasspathEntriesByPath(String path) throws IOException, CodeGenParserException {

    try {
        List<String> tmp = new ArrayList<>();

        URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
        String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
        JarFile jarFile = new JarFile(jarPath);

        String prefix = path.startsWith("/") ? path.substring(1) : path;

        Enumeration<JarEntry> enu = jarFile.entries();
        while (enu.hasMoreElements()) {
            JarEntry je = enu.nextElement();
            if (!je.isDirectory()) {
                String name = je.getName();
                if (name.startsWith(prefix)) {
                    tmp.add("/" + name);
                }
            }
        }
        return tmp;
    } catch (Exception e) {
        // maybe we start Main.class not from Jar.
    }

    InputStream is = Main.class.getResourceAsStream(path);

    if (is == null) {
        throw new CodeGenParserException("Path '" + path + "' not found in Classpath!");
    }

    StringBuilder sb = new StringBuilder();

    byte[] buffer = new byte[1024];
    while (is.read(buffer) != -1) {
        sb.append(new String(buffer, Charset.defaultCharset()));
    }
    is.close();
    return Arrays.asList(sb.toString().split("\n")) // Convert StringBuilder to individual lines
            .stream() // Stream the list
            .filter(line -> line.trim().length() > 0) // Filter out empty lines
            .map(line -> path + "/" + line) // add path for each entry
            .collect(Collectors.toList()); // Collect remaining lines into a List again

}

From source file:com.wordnik.swagger.codegen.util.FileUtil.java

public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileUtil.copyStream(entryInputStream, f)) {
                    return false;
                }//from   ww  w . j a v a2  s.  co  m
                entryInputStream.close();
            } else {
                if (!FileUtil.ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:ArchiveUtil.java

/**
 * Extracts the file {@code archive} to the target dir {@code targetDir} and deletes the 
 * files extracted upon jvm exit if the flag {@code deleteOnExit} is true.
 *//*from   ww  w .j  av  a2 s  . c  o  m*/
public static boolean extract(URL archive, File targetDir, boolean deleteOnExit) throws IOException {
    String archiveStr = archive.toString();
    String jarEntry = null;
    int idx = archiveStr.indexOf("!/");
    if (idx != -1) {
        if (!archiveStr.startsWith("jar:") && archiveStr.length() == idx + 2)
            return false;
        archive = new URL(archiveStr.substring(4, idx));
        jarEntry = archiveStr.substring(idx + 2);
    } else if (!isSupported(archiveStr))
        return false;

    JarInputStream jis = new JarInputStream(archive.openConnection().getInputStream());
    if (!targetDir.exists())
        targetDir.mkdirs();
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        String entryName = entry.getName();
        File entryFile = new File(targetDir, entryName);
        if (!entry.isDirectory()) {
            if (jarEntry == null || entryName.startsWith(jarEntry)) {
                if (!entryFile.exists() || entryFile.lastModified() != entry.getTime())
                    extractEntry(entryFile, jis, entry, deleteOnExit);
            }
        }
    }
    try {
        jis.close();
    } catch (Exception e) {
    }
    return true;
}

From source file:WarUtil.java

/**
 * WAR???????????/*from  ww  w  .  j ava  2s. com*/
 * 
 * @param warFile
 * @param directory
 * @throws IOException
 */
public static void extractWar(File warFile, File directory) throws IOException {
    try {
        long timestamp = warFile.lastModified();
        File warModifiedTimeFile = new File(directory, LAST_MODIFIED_FILE);
        long lastModified = readLastModifiled(warModifiedTimeFile);

        if (timestamp == lastModified) {
            //      log.info("war file " + warFile.getName() + " not modified.");
            return;
        }
        if (directory.exists()) {
            //         IOUtil.forceRemoveDirectory(directory);
            directory.mkdir();
        }

        //         log.info("war extract start. warfile=" + warFile.getName());

        JarInputStream jin = new JarInputStream(new BufferedInputStream(new FileInputStream(warFile)));
        JarEntry entry = null;

        while ((entry = jin.getNextJarEntry()) != null) {
            File file = new File(directory, entry.getName());

            if (entry.isDirectory()) {
                if (!file.exists()) {
                    file.mkdirs();
                }
            } else {
                File dir = new File(file.getParent());
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(file);
                    ResourceUtil.copyStream(jin, fout);
                } finally {
                    fout.flush();
                    fout.close();
                    fout = null;
                }

                if (entry.getTime() >= 0) {
                    file.setLastModified(entry.getTime());
                }
            }
        }

        writeLastModifiled(warModifiedTimeFile, timestamp);

        //log.info("war extract success. lastmodified=" + timestamp);
    } catch (IOException ioe) {
        //log.info("war extract fail.");
        throw ioe;
    }
}