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:io.lightlink.utils.ClasspathScanUtils.java

public static List<String> getResourcesFromPackage(String packageName) throws IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> packageURLs;
    ArrayList<String> names = new ArrayList<String>();

    packageName = packageName.replace(".", "/");
    packageURLs = classLoader.getResources(packageName);

    while (packageURLs.hasMoreElements()) {
        URL packageURL = packageURLs.nextElement();
        // loop through files in classpath

        if (packageURL.getProtocol().equals("jar")) {
            String jarFileName;//from  w  ww.j av a2  s  . c o m
            JarFile jf;
            Enumeration<JarEntry> jarEntries;
            String entryName;

            // build jar file name, then loop through zipped entries
            jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8");
            jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
            jf = new JarFile(jarFileName);
            jarEntries = jf.entries();
            while (jarEntries.hasMoreElements()) {
                entryName = jarEntries.nextElement().getName();
                if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {
                    entryName = entryName.substring(packageName.length());
                    names.add(entryName);
                }
            }

        } else {

            findFromDirectory(packageURL, names);
        }
    }

    return names;
}

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  ww .j  a  v  a2  s .  c  o m
 * @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: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 w  w  w  .  java  2s .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:com.photon.phresco.service.util.ServerUtil.java

public static InputStream getArtifactPomStream(File artifactFile) throws PhrescoException {
    String pomFile = null;/*from   ww w.j av  a 2  s  .  c  om*/
    if (getFileExtension(artifactFile.getName()).equals(ServerConstants.JAR_FILE)) {
        try {
            JarFile jarfile = new JarFile(artifactFile);
            for (Enumeration<JarEntry> em = jarfile.entries(); em.hasMoreElements();) {
                JarEntry jarEntry = em.nextElement();
                if (jarEntry.getName().endsWith("pom.xml")) {
                    pomFile = jarEntry.getName();
                }
            }
            if (pomFile != null) {
                ZipEntry entry = jarfile.getEntry(pomFile);
                return jarfile.getInputStream(entry);
            }
        } catch (Exception e) {
            throw new PhrescoException(e);
        }
    }
    return null;
}

From source file:org.apache.hadoop.streaming.StreamUtil.java

static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {//from  www .j  a va 2  s.  co m
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    file.getParentFile().mkdirs();
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:com.flagleader.builder.BuilderConfig.java

public static void jarExtracting(String paramString1, String paramString2) {
    int i1 = 2048;
    BufferedOutputStream localBufferedOutputStream = null;
    BufferedInputStream localBufferedInputStream = null;
    JarEntry localJarEntry = null;
    JarFile localJarFile = null;
    Enumeration localEnumeration = null;
    try {//ww w  .  j av a  2s .c om
        localJarFile = new JarFile(paramString2);
        localEnumeration = localJarFile.entries();
        while (localEnumeration.hasMoreElements()) {
            localJarEntry = (JarEntry) localEnumeration.nextElement();
            if (localJarEntry.isDirectory()) {
                new File(paramString1 + localJarEntry.getName()).mkdirs();
            } else {
                localBufferedInputStream = new BufferedInputStream(localJarFile.getInputStream(localJarEntry));
                byte[] arrayOfByte = new byte[i1];
                FileOutputStream localFileOutputStream = new FileOutputStream(
                        paramString1 + localJarEntry.getName());
                localBufferedOutputStream = new BufferedOutputStream(localFileOutputStream, i1);
                int i2;
                while ((i2 = localBufferedInputStream.read(arrayOfByte, 0, i1)) != -1)
                    localBufferedOutputStream.write(arrayOfByte, 0, i2);
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
                localBufferedInputStream.close();
            }
        }
    } catch (Exception localException1) {
        localException1.printStackTrace();
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException2) {
            localException2.printStackTrace();
        }
    } finally {
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException3) {
            localException3.printStackTrace();
        }
    }
}

From source file:com.app.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath/* w ww  . jav  a  2s .  co  m*/
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        log.info("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        log.info(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.web.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath//w w w. j a v a 2  s . c o m
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        System.out.println("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        System.out.println(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:net.kamhon.ieagle.util.ReflectionUtil.java

/**
 * <pre>//from   ww w. ja v a2 s.co m
 * This method finds all classes that are located in the package identified by
 * the given
 * &lt;code&gt;
 * packageName
 * &lt;/code&gt;
 * .
 * &lt;br&gt;
 * &lt;b&gt;ATTENTION:&lt;/b&gt;
 * &lt;br&gt;
 * This is a relative expensive operation. Depending on your classpath
 * multiple directories,JAR, and WAR files may need to scanned.
 * 
 * &#064;param packageName is the name of the {@link Package} to scan.
 * &#064;param includeSubPackages - if
 * &lt;code&gt;
 * true
 * &lt;/code&gt;
 *  all sub-packages of the
 *        specified {@link Package} will be included in the search.
 * &#064;return a {@link Set} will the fully qualified names of all requested
 *         classes.
 * &#064;throws IOException if the operation failed with an I/O error.
 * &#064;see http://m-m-m.svn.sourceforge.net/svnroot/m-m-m/trunk/mmm-util/mmm-util-reflect/src/main/java/net/sf/mmm/util/reflect/ReflectionUtil.java
 * </pre>
 */
public static Set<String> findFileNames(String packageName, boolean includeSubPackages, String packagePattern,
        String... endWiths) throws IOException {

    Set<String> classSet = new HashSet<String>();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String path = packageName.replace('.', '/');
    String pathWithPrefix = path + '/';
    Enumeration<URL> urls = classLoader.getResources(path);
    StringBuilder qualifiedNameBuilder = new StringBuilder(packageName);
    qualifiedNameBuilder.append('.');

    int qualifiedNamePrefixLength = qualifiedNameBuilder.length();

    while (urls.hasMoreElements()) {

        URL packageUrl = urls.nextElement();
        String urlString = URLDecoder.decode(packageUrl.getFile(), "UTF-8");
        String protocol = packageUrl.getProtocol().toLowerCase();
        log.debug(urlString);

        if ("file".equals(protocol)) {

            File packageDirectory = new File(urlString);

            if (packageDirectory.isDirectory()) {
                if (includeSubPackages) {
                    findClassNamesRecursive(packageDirectory, classSet, qualifiedNameBuilder,
                            qualifiedNamePrefixLength, packagePattern);
                } else {
                    for (String fileName : packageDirectory.list()) {
                        String simpleClassName = fixClassName(fileName);
                        if (simpleClassName != null) {
                            qualifiedNameBuilder.setLength(qualifiedNamePrefixLength);
                            qualifiedNameBuilder.append(simpleClassName);
                            if (qualifiedNameBuilder.toString().matches(packagePattern))
                                classSet.add(qualifiedNameBuilder.toString());
                        }
                    }
                }
            }
        } else if ("jar".equals(protocol)) {
            // somehow the connection has no close method and can NOT be
            // disposed
            JarURLConnection connection = (JarURLConnection) packageUrl.openConnection();
            JarFile jarFile = connection.getJarFile();
            Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
            while (jarEntryEnumeration.hasMoreElements()) {
                JarEntry jarEntry = jarEntryEnumeration.nextElement();
                String absoluteFileName = jarEntry.getName();
                // if (absoluteFileName.endsWith(".class")) { //original
                if (endWith(absoluteFileName, endWiths)) { // modified
                    if (absoluteFileName.startsWith("/")) {
                        absoluteFileName.substring(1);
                    }
                    // special treatment for WAR files...
                    // "WEB-INF/lib/" entries should be opened directly in
                    // contained jar
                    if (absoluteFileName.startsWith("WEB-INF/classes/")) {
                        // "WEB-INF/classes/".length() == 16
                        absoluteFileName = absoluteFileName.substring(16);
                    }
                    boolean accept = true;
                    if (absoluteFileName.startsWith(pathWithPrefix)) {
                        String qualifiedName = absoluteFileName.replace('/', '.');
                        if (!includeSubPackages) {
                            int index = absoluteFileName.indexOf('/', qualifiedNamePrefixLength + 1);
                            if (index != -1) {
                                accept = false;
                            }
                        }
                        if (accept) {
                            String className = fixClassName(qualifiedName);

                            if (className != null) {
                                if (qualifiedNameBuilder.toString().matches(packagePattern))
                                    classSet.add(className);
                            }
                        }
                    }
                }
            }
        } else {
            log.debug("unknown protocol -> " + protocol);
        }
    }
    return classSet;
}

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   w  w w  .j  a v a 2  s  . c om
 *
 * @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

}