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:eu.trentorise.opendata.josman.Josmans.java

/**
 *
 * Extracts the files starting with dirPath from {@code file} to
 * {@code destDir}/*from   ww  w  .  ja  v a 2s .c  o m*/
 *
 * @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:com.taobao.android.builder.tools.classinject.CodeInjectByJavassist.java

/**
 * jar?//from w  w w .jav  a2  s. c om
 *
 * @param inJar
 * @param outJar
 * @throws IOException
 * @throws NotFoundException
 * @throws CannotCompileException
 */
public static List<String> inject(ClassPool pool, File inJar, File outJar, InjectParam injectParam)
        throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    JarFile jarFile = newJarFile(inJar);

    outJar.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(fileOutputStream));
    Enumeration<JarEntry> jarFileEntries = jarFile.entries();
    JarEntry jarEntry = null;
    while (jarFileEntries.hasMoreElements()) {
        jarEntry = jarFileEntries.nextElement();
        String name = jarEntry.getName();
        String className = StringUtils.replace(name, File.separator, "/");
        className = StringUtils.replace(className, "/", ".");
        className = StringUtils.substring(className, 0, className.length() - 6);
        if (!StringUtils.endsWithIgnoreCase(name, ".class")) {
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            copyStreamToJar(inputStream, jos, name, jarEntry.getTime(), jarEntry);
            IOUtils.closeQuietly(inputStream);
        } else {
            byte[] codes;

            codes = inject(pool, className, injectParam);
            InputStream classInstream = new ByteArrayInputStream(codes);
            copyStreamToJar(classInstream, jos, name, jarEntry.getTime(), jarEntry);

        }
    }
    jarFile.close();
    IOUtils.closeQuietly(jos);
    return errorFiles;
}

From source file:org.lpe.common.util.system.LpeSystemUtils.java

/**
 * Extracts a file/folder identified by the URL that resides in the
 * classpath, into the destiation folder.
 * /*  www .  j  a v a2s . c om*/
 * @param url
 *            URL of the JAR file
 * @param dirOfInterest
 *            the name of the directory of interest
 * @param dest
 *            destination folder
 * 
 * @throws IOException
 *             ...
 * @throws URISyntaxException
 *             ...
 */
public static void extractJARtoTemp(URL url, String dirOfInterest, String dest)
        throws IOException, URISyntaxException {
    if (!url.getProtocol().equals("jar")) {
        throw new IllegalArgumentException("Cannot locate the JAR file.");
    }

    // create a temp lib directory
    File tempJarDirFile = new File(dest);
    if (!tempJarDirFile.exists()) {
        boolean ok = tempJarDirFile.mkdir();
        if (!ok) {
            logger.warn("Could not create directory {}", tempJarDirFile.getAbsolutePath());
        }

    } else {
        FileUtils.cleanDirectory(tempJarDirFile);
    }

    String urlStr = url.getFile();
    // if (urlStr.startsWith("jar:file:") || urlStr.startsWith("jar:") ||
    // urlStr.startsWith("file:")) {
    // urlStr = urlStr.replaceFirst("jar:", "");
    // urlStr = urlStr.replaceFirst("file:", "");
    // }
    if (urlStr.contains("!")) {
        final int endIndex = urlStr.indexOf("!");
        urlStr = urlStr.substring(0, endIndex);
    }

    URI uri = new URI(urlStr);

    final File jarFile = new File(uri);

    logger.debug("Unpacking jar file {}...", jarFile.getAbsolutePath());

    java.util.jar.JarFile jar = null;
    InputStream is = null;
    OutputStream fos = null;
    try {
        jar = new JarFile(jarFile);
        java.util.Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            java.util.jar.JarEntry file = (JarEntry) entries.nextElement();

            String destFileName = dest + File.separator + file.getName();
            if (destFileName.indexOf(dirOfInterest + File.separator) < 0
                    && destFileName.indexOf(dirOfInterest + "/") < 0) {
                continue;
            }

            logger.debug("unpacking {}...", file.getName());

            java.io.File f = new java.io.File(destFileName);
            if (file.isDirectory()) { // if its a directory, create it
                boolean ok = f.mkdir();
                if (!ok) {
                    logger.warn("Could not create directory {}", f.getAbsolutePath());
                }
                continue;
            }
            is = new BufferedInputStream(jar.getInputStream(file));
            fos = new BufferedOutputStream(new FileOutputStream(f));

            LpeStreamUtils.pipe(is, fos);
        }

        logger.debug("Unpacking jar file done.");
    } catch (IOException e) {
        throw e;
    } finally {
        if (jar != null) {
            jar.close();
        }
        if (fos != null) {
            fos.close();
        }
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.mrgeo.utils.DependencyLoader.java

private static Set<Dependency> loadDependenciesFromJar(final String jarname) throws IOException {
    try {/*from   w ww.  j  a va  2 s  .  c  o m*/
        String jar = jarname;

        URL url;
        JarURLConnection conn;

        try {
            url = new URL(jar);
            conn = (JarURLConnection) url.openConnection();
        } catch (MalformedURLException e) {
            jar = (new File(jar)).toURI().toString();
            if (!jar.startsWith("jar:")) {
                jar = "jar:" + jar;
            }

            if (!jar.contains("!/")) {
                jar += "!/";
            }

            url = new URL(jar);
            conn = (JarURLConnection) url.openConnection();
        }

        log.debug("Looking in " + jar + " for dependency file");

        JarFile jf = conn.getJarFile();

        for (Enumeration<JarEntry> i = jf.entries(); i.hasMoreElements();) {
            JarEntry je = i.nextElement();
            String name = je.getName();
            if (name.endsWith("dependencies.properties")) {
                log.debug("Found dependency for " + jar + " -> " + name);
                URL resource = new URL(jar + name);
                InputStream is = resource.openStream();

                Set<Dependency> deps = readDependencies(is);

                is.close();
                return deps;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Error Loading dependency properties file", e);
    }

    throw new IOException("No dependency properties file found in " + jarname);
}

From source file:org.spoutcraft.launcher.util.Utils.java

public static void extractJar(JarFile jar, File dest, List<String> ignores) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();//from  ww w  . j a v  a 2s  .c  om
    } else {
        if (!dest.isDirectory()) {
            throw new IllegalArgumentException("The destination was not a directory");
        }
        FileUtils.cleanDirectory(dest);
    }
    Enumeration<JarEntry> entries = jar.entries();

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        File file = new File(dest, entry.getName());
        if (ignores != null) {
            boolean skip = false;
            for (String path : ignores) {
                if (entry.getName().startsWith(path)) {
                    skip = true;
                    break;
                }
            }
            if (skip) {
                continue;
            }
        }

        if (entry.getName().endsWith("/")) {
            if (!file.mkdir()) {
                if (ignores == null) {
                    ignores = new ArrayList<String>();
                }
                ignores.add(entry.getName());
            }
            continue;
        }

        if (file.exists()) {
            file.delete();
        }

        file.createNewFile();

        InputStream in = new BufferedInputStream(jar.getInputStream(entry));
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));

        byte buffer[] = new byte[1024];
        int len;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
    }
    jar.close();
}

From source file:io.stallion.utils.ResourceHelpers.java

public static List<String> listFilesInDirectory(String plugin, String path) {
    String ending = "";
    String starting = "";
    if (path.contains("*")) {
        String[] parts = StringUtils.split(path, "*", 2);
        String base = parts[0];/*  w w w. ja va  2  s.  co  m*/
        if (!base.endsWith("/")) {
            path = new File(base).getParent();
            starting = FilenameUtils.getName(base);
        } else {
            path = base;
        }
        ending = parts[1];
    }

    Log.info("listFilesInDirectory Parsed Path {0} starting:{1} ending:{2}", path, starting, ending);
    URL url = PluginRegistry.instance().getJavaPluginByName().get(plugin).getClass().getResource(path);
    Log.info("URL: {0}", url);

    List<String> filenames = new ArrayList<>();
    URL dirURL = getClassForPlugin(plugin).getResource(path);
    Log.info("Dir URL is {0}", dirURL);
    // Handle file based resource folder
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        String fullPath = dirURL.toString().substring(5);
        File dir = new File(fullPath);
        // In devMode, use the source resource folder, rather than the compiled version
        if (Settings.instance().getDevMode()) {
            String devPath = fullPath.replace("/target/classes/", "/src/main/resources/");
            File devFolder = new File(devPath);
            if (devFolder.exists()) {
                dir = devFolder;
            }
        }
        Log.info("List files from folder {0}", dir.getAbsolutePath());
        List<String> files = list();
        for (String name : dir.list()) {
            if (!empty(ending) && !name.endsWith(ending)) {
                continue;
            }
            if (!empty(starting) && !name.endsWith("starting")) {
                continue;
            }
            // Skip special files, hidden files
            if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#")
                    || name.contains("_flymake.")) {
                continue;
            }
            filenames.add(path + name);
        }
        return filenames;
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = null;
        try {
            jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            Log.finer("Jar file entry: {0}", name);
            if (name.startsWith(path)) { //filter according to the path
                String entry = name.substring(path.length());
                int checkSubdir = entry.indexOf("/");
                if (checkSubdir >= 0) {
                    // if it is a subdirectory, we just return the directory name
                    entry = entry.substring(0, checkSubdir);
                }
                if (!empty(ending) && !name.endsWith(ending)) {
                    continue;
                }
                if (!empty(starting) && !name.endsWith("starting")) {
                    continue;
                }
                // Skip special files, hidden files
                if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#")
                        || name.contains("_flymake.")) {
                    continue;
                }
                result.add(entry);
            }
        }
        return new ArrayList<>(result);
    }
    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
    /*
    try {
    URL url1 = getClassForPlugin(plugin).getResource(path);
    Log.info("URL1 {0}", url1);
    if (url1 != null) {
        Log.info("From class folder contents {0}", IOUtils.toString(url1));
        Log.info("From class folder contents as stream {0}", IOUtils.toString(getClassForPlugin(plugin).getResourceAsStream(path)));
    }
    URL url2 = getClassLoaderForPlugin(plugin).getResource(path);
    Log.info("URL1 {0}", url2);
    if (url2 != null) {
        Log.info("From classLoader folder contents {0}", IOUtils.toString(url2));
        Log.info("From classLoader folder contents as stream {0}", IOUtils.toString(getClassLoaderForPlugin(plugin).getResourceAsStream(path)));
    }
            
    } catch (IOException e) {
    Log.exception(e, "error loading path " + path);
    }
    //  Handle jar based resource folder
    try(
        InputStream in = getResourceAsStream(plugin, path);
        BufferedReader br = new BufferedReader( new InputStreamReader( in ) ) ) {
    String resource;
    while( (resource = br.readLine()) != null ) {
        Log.finer("checking resource for inclusion in directory scan: {0}", resource);
        if (!empty(ending) && !resource.endsWith(ending)) {
            continue;
        }
        if (!empty(starting) && !resource.endsWith("starting")) {
            continue;
        }
        // Skip special files, hidden files
        if (resource.startsWith(".") || resource.startsWith("~") || resource.startsWith("#") || resource.contains("_flymake.")) {
            continue;
        }
        Log.finer("added resource during directory scan: {0}", resource);
        filenames.add(path + resource);
    }
    } catch (IOException e) {
    throw new RuntimeException(e);
    }
    return filenames;
    */
}

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
 *//*from   ww w  .  ja  v  a 2s.  co 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:edu.stanford.muse.email.JarDocCache.java

/** returns a jar outputstream for the given filename.
 * copies over jar entries if the file was already existing.
 * unfortunately, we can't append to the end of a jar file easily.
 * see e.g.http://stackoverflow.com/questions/2223434/appending-files-to-a-zip-file-with-java
 * and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445
 * may consider using truezip at some point, but the doc is dense.
 *///  w w  w.j  ava2  s .c om
private static JarOutputStream appendOrCreateJar(String filename) throws IOException {
    JarOutputStream jos;
    File f = new File(filename);
    if (!f.exists())
        return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));

    // bak* is going to be all the previous file entries
    String bakFilename = filename + ".bak";
    File bakFile = new File(bakFilename);
    f.renameTo(new File(bakFilename));
    jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
    JarFile bakJF;
    try {
        bakJF = new JarFile(bakFilename);
    } catch (Exception e) {
        log.warn("Bad jar file! " + bakFilename + " size " + new File(filename).length() + " bytes");
        Util.print_exception(e, log);
        return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
    }

    // copy all entries from bakJF to jos
    Enumeration<JarEntry> bakEntries = bakJF.entries();
    while (bakEntries.hasMoreElements()) {
        JarEntry je = bakEntries.nextElement();
        jos.putNextEntry(je);
        InputStream is = bakJF.getInputStream(je);

        // copy over everything from is to jos
        byte buf[] = new byte[32 * 1024]; // randomly 32K
        int nBytes;
        while ((nBytes = is.read(buf)) != -1)
            jos.write(buf, 0, nBytes);

        jos.closeEntry();
    }
    bakFile.delete();

    return jos;
}

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   w  w  w  .j  a v a2s.  c om*/
        }
    } 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:org.mule.util.FileUtils.java

/**
 * Extract recources contain if jar (have to in classpath)
 *
 * @param connection          JarURLConnection to jar library
 * @param outputDir           Directory for unpack recources
 * @param keepParentDirectory true -  full structure of directories is kept; false - file - removed all directories, directory - started from resource point
 * @throws IOException if any error//from ww w.  jav a2 s . co  m
 */
private static void extractJarResources(JarURLConnection connection, File outputDir,
        boolean keepParentDirectory) throws IOException {
    JarFile jarFile = connection.getJarFile();
    JarEntry jarResource = connection.getJarEntry();
    Enumeration entries = jarFile.entries();
    InputStream inputStream = null;
    OutputStream outputStream = null;
    int jarResourceNameLenght = jarResource.getName().length();
    for (; entries.hasMoreElements();) {
        JarEntry entry = (JarEntry) entries.nextElement();
        if (entry.getName().startsWith(jarResource.getName())) {

            String path = outputDir.getPath() + File.separator + entry.getName();

            //remove directory struct for file and first dir for directory
            if (!keepParentDirectory) {
                if (entry.isDirectory()) {
                    if (entry.getName().equals(jarResource.getName())) {
                        continue;
                    }
                    path = outputDir.getPath() + File.separator
                            + entry.getName().substring(jarResourceNameLenght, entry.getName().length());
                } else {
                    if (entry.getName().length() > jarResourceNameLenght) {
                        path = outputDir.getPath() + File.separator
                                + entry.getName().substring(jarResourceNameLenght, entry.getName().length());
                    } else {
                        path = outputDir.getPath() + File.separator + entry.getName()
                                .substring(entry.getName().lastIndexOf("/"), entry.getName().length());
                    }
                }
            }

            File file = FileUtils.newFile(path);
            if (!file.getParentFile().exists()) {
                if (!file.getParentFile().mkdirs()) {
                    throw new IOException("Could not create directory: " + file.getParentFile());
                }
            }
            if (entry.isDirectory()) {
                if (!file.exists() && !file.mkdirs()) {
                    throw new IOException("Could not create directory: " + file);
                }

            } else {
                try {
                    inputStream = jarFile.getInputStream(entry);
                    outputStream = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(inputStream, outputStream);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }

        }
    }
}