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:net.sourceforge.tess4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path./*from w ww  . j av a  2s  .  co m*/
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

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

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:org.mule.util.JarUtils.java

public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception {
    LinkedHashMap entries = new LinkedHashMap();
    JarFile jarFileWrapper = null;
    if (jarFile != null) {
        logger.debug("Reading jar entries from " + jarFile.getAbsolutePath());
        try {/*from w w w .j  a v a2  s  . co  m*/
            jarFileWrapper = new JarFile(jarFile);
            Enumeration iter = jarFileWrapper.entries();
            while (iter.hasMoreElements()) {
                ZipEntry zipEntry = (ZipEntry) iter.nextElement();
                InputStream entryStream = jarFileWrapper.getInputStream(zipEntry);
                ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
                try {
                    IOUtils.copy(entryStream, byteArrayStream);
                    entries.put(zipEntry.getName(), byteArrayStream.toByteArray());
                    logger.debug("Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath());
                } finally {
                    byteArrayStream.close();
                }
            }
        } finally {
            if (jarFileWrapper != null) {
                try {
                    jarFileWrapper.close();
                } catch (Exception ignore) {
                    logger.debug(ignore);
                }
            }
        }
    }
    return entries;
}

From source file:JarUtil.java

/**
 * Reads the package-names from the given jar-file.
 * //from   w  w  w .ja  v a2 s  .c om
 * @param jarFile
 *            the jar file
 * @return an array with all found package-names
 * @throws IOException
 *             when the jar-file could not be read
 */
public static String[] getPackageNames(File jarFile) throws IOException {
    HashMap<String, String> packageNames = new HashMap<String, String>();
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        String name = entry.getName();
        if (name.endsWith(".class")) {
            int endPos = name.lastIndexOf('/');
            boolean isWindows = false;
            if (endPos == -1) {
                endPos = name.lastIndexOf('\\');
                isWindows = true;
            }
            name = name.substring(0, endPos);
            name = name.replace('/', '.');
            if (isWindows) {
                name = name.replace('\\', '.');
            }
            packageNames.put(name, name);
        }
    }
    return (String[]) packageNames.values().toArray(new String[packageNames.size()]);
}

From source file:com.enderville.enderinstaller.util.InstallScript.java

/**
 * Unpacks all the contents of the old minecraft.jar to the temp directory.
 *
 * @param tmpdir The temp directory to unpack to.
 * @param mcjar The location of the old minecraft.jar
 * @throws IOException/*from w  w  w .  j  av  a 2 s. c  om*/
 */
public static void unpackMCJar(File tmpdir, File mcjar) throws IOException {
    byte[] dat = new byte[4 * 1024];
    JarFile jar = new JarFile(mcjar);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        //This gets rid of META-INF if it exists.
        if (name.startsWith("META-INF")) {
            continue;
        }
        InputStream in = jar.getInputStream(entry);
        File dest = new File(FilenameUtils.concat(tmpdir.getPath(), name));
        if (entry.isDirectory()) {
            //I don't think this actually happens
            LOGGER.warn("Found a directory while iterating over jar.");
            dest.mkdirs();
        } else if (!dest.getParentFile().exists()) {
            if (!dest.getParentFile().mkdirs()) {
                throw new IOException("Couldn't create directory for " + name);
            }
        }
        FileOutputStream out = new FileOutputStream(dest);
        int len = -1;
        while ((len = in.read(dat)) > 0) {
            out.write(dat, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }
}

From source file:eu.leads.processor.planner.ClassUtil.java

private static void findClasses(Set<Class> matchedClassSet, File root, File file, boolean includeJars,
        Class type, String packageFilter) {
    if (file.isDirectory()) {
        for (File child : file.listFiles()) {
            findClasses(matchedClassSet, root, child, includeJars, type, packageFilter);
        }//  ww  w.  j a  va2s.co  m
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
                LOG.error(ex.getMessage(), ex);
                return;
            }
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                int extIndex = name.lastIndexOf(".class");
                if (extIndex > 0) {
                    String qualifiedClassName = name.substring(0, extIndex).replace("/", ".");
                    if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                        try {
                            Class clazz = Class.forName(qualifiedClassName);

                            if (!clazz.isInterface() && isMatch(type, clazz)) {
                                matchedClassSet.add(clazz);
                            }
                        } catch (ClassNotFoundException e) {
                            LOG.error(e.getMessage(), e);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String qualifiedClassName = createClassName(root, file);
            // if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
            try {
                Class clazz = Class.forName(qualifiedClassName);
                if (!clazz.isInterface() && isMatch(type, clazz)) {
                    matchedClassSet.add(clazz);
                }
            } catch (ClassNotFoundException e) {
                LOG.error(e.getMessage(), e);
            }
            // }
        }
    }
}

From source file:net.servicefixture.util.ReflectionUtils.java

/**
 * Finds all the concrete subclasses for given class in the the SAME JAR
 * file where the baseClass is loaded from.
 * /*from  w  ww  .jav a 2 s . c o m*/
 * @param baseClass
 *            the base class
 */
public static Class[] findSubClasses(Class baseClass) {
    String packagePath = "/" + baseClass.getPackage().getName().replace('.', '/');
    URL url = baseClass.getResource(packagePath);
    if (url == null) {
        return new Class[0];
    }
    List<Class> derivedClasses = new ArrayList<Class>();
    try {
        URLConnection connection = url.openConnection();
        if (connection instanceof JarURLConnection) {
            JarFile jarFile = ((JarURLConnection) connection).getJarFile();
            Enumeration e = jarFile.entries();
            while (e.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                String entryName = entry.getName();
                if (entryName.endsWith(".class")) {
                    String clazzName = entryName.substring(0, entryName.length() - 6);

                    clazzName = clazzName.replace('/', '.');
                    try {
                        Class clazz = Class.forName(clazzName);
                        if (isConcreteSubclass(baseClass, clazz)) {
                            derivedClasses.add(clazz);
                        }
                    } catch (Throwable ignoreIt) {
                    }
                }
            }
        } else if (connection instanceof FileURLConnection) {
            File file = new File(url.getFile());
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                String filename = files[i].getName();
                if (filename.endsWith(".class")) {
                    filename = filename.substring(0, filename.length() - 6);
                    String clazzname = baseClass.getPackage().getName() + "." + filename;
                    try {
                        Class clazz = Class.forName(clazzname);
                        if (isConcreteSubclass(baseClass, clazz)) {
                            derivedClasses.add(clazz);
                        }
                    } catch (Throwable ignoreIt) {
                    }
                }
            }
        }
    } catch (IOException ignoreIt) {
    }
    return derivedClasses.toArray(new Class[derivedClasses.size()]);
}

From source file:com.github.sakserv.minicluster.impl.KnoxLocalCluster.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 (!copyStream(entryInputStream, f)) {
                    return false;
                }//w ww.j a v  a2 s. c  o  m
                entryInputStream.close();
            } else {
                if (!ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:JarUtil.java

/**
 * Extracts the given jar-file to the specified directory. The target
 * directory will be cleaned before the jar-file will be extracted.
 * /*from   w  w w. j  a v  a2s  . co  m*/
 * @param jarFile
 *            The jar file which should be unpacked
 * @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, 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().indexOf("package cache") == -1) {
                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:JarUtil.java

/**
 * Extracts the given resource from a jar-file to the specified directory.
 * //from   w  ww .j ava  2  s. c  o  m
 * @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.cocoon.portal.pluto.Deploy.java

/**
 * Deploy the archive/*  w  w w .  ja  v  a2  s  . c  o m*/
 * Unpack the archive in the servlet engine context directory
 */
public static void deployArchive(final String webAppsDir, final String warFile, final String warFileName)
        throws IOException {
    System.out.println("Deploying '" + warFileName + "' ...");

    final String destination = webAppsDir + warFileName;

    if (debug) {
        System.out.println("  unpacking '" + warFile + "' ...");
    }
    final JarFile jarFile = new JarFile(warFile);
    final Enumeration files = jarFile.entries();
    while (files.hasMoreElements()) {
        JarEntry entry = (JarEntry) files.nextElement();

        File file = new File(destination, entry.getName());
        File dirF = new File(file.getParent());
        dirF.mkdirs();
        if (entry.isDirectory()) {
            file.mkdirs();
        } else {
            byte[] buffer = new byte[1024];
            int length = 0;
            InputStream fis = jarFile.getInputStream(entry);
            FileOutputStream fos = new FileOutputStream(file);
            while ((length = fis.read(buffer)) >= 0) {
                fos.write(buffer, 0, length);
            }
            fos.close();
        }

    }

    if (debug) {
        System.out.println("Finished!");
    }
}