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:javadepchecker.Main.java

private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    Collection<String> jars = getPackageJars(pkg);
    // We have a virtual with VM provider here
    if (jars.size() == 0)
        return true;
    for (String jarName : jars) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }//  w  w  w . j  a va  2s .  c  o  m
        }
    }
    return false;
}

From source file:info.dolezel.fatrat.plugins.helpers.NativeHelpers.java

private static Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = loader.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);//from   w w  w  .  j  a va 2  s .  c o m
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = loader.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

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

public static List<URL> loadJar(String path, URL resource) throws IOException {
    JarURLConnection conn = (JarURLConnection) resource.openConnection();
    JarFile jarFile = conn.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    List<URL> result = new LinkedList<URL>();

    String p = path;/*from w  w  w  .j ava2s. c  om*/
    if (p.endsWith("/") == false) {
        p = p + "/";
    }

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if ((!entry.getName().equals(p))
                && (entry.getName().startsWith(p) || entry.getName().startsWith("WEB-INF/classes/" + p))) {
            URL url = new URL("jar:" + new URL("file", null, jarFile.getName() + "!/" + entry.getName()));
            result.add(url);
        }
    }

    return result;
}

From source file:org.jahia.utils.maven.plugin.jarscan.JarsToSkipListMojo.java

private static boolean hasTLDFiles(File file) throws IOException {
    String name = file.getName();
    if (!file.isFile() || !name.endsWith(".jar")) {
        return false;
    }//from   w ww  .  j a  v a  2 s .c  o m

    boolean tldPresent = false;
    JarFile jar = null;
    try {
        jar = new JarFile(file);
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            String entry = entries.nextElement().getName();
            if (entry != null && entry.startsWith("META-INF/") && entry.endsWith(".tld")) {
                tldPresent = true;
                break;
            }
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }

    return tldPresent;
}

From source file:org.panthercode.arctic.core.reflect.ReflectionUtils.java

/**
 * Reads all names of classes as path from a specific jar file.
 *
 * @param path filepath to jar file/*from w ww  .  java2  s.com*/
 * @return Returns a list of class paths
 * @throws IOException              Is thrown if an error occurs while reading the .jar file.
 * @throws IllegalArgumentException Is thrown if path is null.
 */
public static List<String> extractClassNamesFromJar(String path) throws NullPointerException, IOException {
    ArgumentUtils.assertNotNull(path, "path");

    JarFile jarFile = new JarFile(path);

    List<String> classNameList = new ArrayList<>();

    Enumeration<JarEntry> entries = jarFile.entries();

    for (JarEntry currentEntry = entries.nextElement(); entries
            .hasMoreElements(); currentEntry = entries.nextElement()) {
        if (currentEntry != null && currentEntry.getName().endsWith(".class")) {
            classNameList.add(currentEntry.getName().replace("/", ".").split("\\.class", 2)[0]);
        }
    }

    return classNameList;
}

From source file:SerialVersionUID.java

/**
 * Build a TreeMap of the class name to ClassVersionInfo
 * //from  w  ww .  j  av a  2 s.c o m
 * @param jar
 * @param classVersionMap
 *          TreeMap<String, ClassVersionInfo> for serializable classes
 * @param cl -
 *          the class loader to use
 * @throws IOException
 *           thrown if the jar cannot be opened
 */
static void generateJarSerialVersionUIDs(URL jar, TreeMap classVersionMap, ClassLoader cl, String pkgPrefix)
        throws IOException {
    String jarName = jar.getFile();
    JarFile jf = new JarFile(jarName);
    Enumeration entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String name = entry.getName();
        if (name.endsWith(".class") && name.startsWith(pkgPrefix)) {
            name = name.substring(0, name.length() - 6);
            String classname = name.replace('/', '.');
            try {
                log.fine("Creating ClassVersionInfo for: " + classname);
                ClassVersionInfo cvi = new ClassVersionInfo(classname, cl);
                log.fine(cvi.toString());
                if (cvi.getSerialVersion() != 0) {
                    ClassVersionInfo prevCVI = (ClassVersionInfo) classVersionMap.put(classname, cvi);
                    if (prevCVI != null) {
                        if (prevCVI.getSerialVersion() != cvi.getSerialVersion()) {
                            log.severe("Found inconsistent classes, " + prevCVI + " != " + cvi + ", jar: "
                                    + jarName);
                        }
                    }
                    if (cvi.getHasExplicitSerialVersionUID() == false) {
                        log.warning("No explicit serialVersionUID: " + cvi);
                    }
                }
            } catch (OutOfMemoryError e) {
                log.log(Level.SEVERE, "Check the MaxPermSize", e);
            } catch (Throwable e) {
                log.log(Level.FINE, "While loading: " + name, e);
            }
        }
    }
    jf.close();
}

From source file:eu.stratosphere.yarn.Utils.java

public static void copyJarContents(String prefix, String pathToJar) throws IOException {
    LOG.info("Copying jar (location: " + pathToJar + ") to prefix " + prefix);

    JarFile jar = null;
    jar = new JarFile(pathToJar);
    Enumeration<JarEntry> enumr = jar.entries();
    byte[] bytes = new byte[1024];
    while (enumr.hasMoreElements()) {
        JarEntry entry = enumr.nextElement();
        if (entry.getName().startsWith(prefix)) {
            if (entry.isDirectory()) {
                File cr = new File(entry.getName());
                cr.mkdirs();/*from   www.j av a2 s .  c  o m*/
                continue;
            }
            InputStream inStream = jar.getInputStream(entry);
            File outFile = new File(entry.getName());
            if (outFile.exists()) {
                throw new RuntimeException("File unexpectedly exists");
            }
            FileOutputStream outputStream = new FileOutputStream(outFile);
            int read = 0;
            while ((read = inStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            inStream.close();
            outputStream.close();
        }
    }
    jar.close();
}

From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java

/**
 * /*from  w  w w.  j  av  a2  s. com*/
 * Extract a directory in a JAR on the classpath to an output folder.
 * 
 * Note: User's responsibility to ensure that the files are actually in a JAR.
 * 
 * @param classInJar A class in the JAR file which is on the classpath
 * @param resourceDirectory Path to resource directory in JAR
 * @param outputDirectory Directory to write to  
 * @return String containing the path to the outputDirectory
 * @throws IOException
 */
private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory,
        String outputDirectory) throws IOException {

    resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator;

    URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation();
    JarFile jarFile = new JarFile(new File(jar.getFile()));

    byte[] buf = new byte[1024];
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) {
            continue;
        }

        String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName());
        //Create directories if they don't exist
        new File(FilenameUtils.getFullPath(outputFileName)).mkdirs();

        //Write file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
        int n;
        InputStream is = jarFile.getInputStream(jarEntry);
        while ((n = is.read(buf, 0, 1024)) > -1) {
            fileOutputStream.write(buf, 0, n);
        }
        is.close();
        fileOutputStream.close();
    }
    jarFile.close();

    String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory);
    return fullPath;
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Get a JCE policy's details.// w  w w  . j  a  v a 2  s  . c  o  m
 *
 * @param jcePolicy
 *            JCE policy
 * @return Policy details
 * @throws CryptoException
 *             If there was a problem getting the policy details
 */
public static String getPolicyDetails(JcePolicy jcePolicy) throws CryptoException {
    try {
        StringWriter sw = new StringWriter();

        File file = getJarFile(jcePolicy);

        // if there is no policy file at all, return empty string
        if (!file.exists()) {
            return "";
        }

        JarFile jar = new JarFile(file);

        Enumeration<JarEntry> jarEntries = jar.entries();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();

            String entryName = jarEntry.getName();

            if (!jarEntry.isDirectory() && entryName.endsWith(".policy")) {
                sw.write(entryName + ":\n\n");

                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(jar.getInputStream(jarEntry));
                    CopyUtil.copy(isr, sw);
                } finally {
                    IOUtils.closeQuietly(isr);
                }

                sw.write('\n');
            }
        }

        return sw.toString();
    } catch (IOException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoGetPolicyDetails.exception.message"), jcePolicy), ex);
    }
}

From source file:org.lightcouch.CouchDbUtil.java

/**
 * List directory contents for a resource folder. Not recursive. This is
 * basically a brute-force implementation. Works for regular files and also
 * JARs.//from   w ww .  j av  a 2s.  c  o  m
 * 
 * @author Greg Briggs
 * @param clazz
 *            Any java class that lives in the same place as the resources
 *            you want.
 * @param path
 *            Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 */
public static List<String> listResources(String path) {
    String fileURL = null;
    try {
        URL entry = Platform.getBundle("org.lightcouch").getEntry(path);
        File file = null;
        if (entry != null) {
            fileURL = FileLocator.toFileURL(entry).getPath();
            // remove leading slash from absolute path when on windows
            if (OSValidator.isWindows())
                fileURL = fileURL.substring(1, fileURL.length());
            file = new File(fileURL);
        }
        URL dirURL = file.toPath().toUri().toURL();

        if (dirURL != null && dirURL.getProtocol().equals("file")) {
            return Arrays.asList(new File(dirURL.toURI()).list());
        }
        if (dirURL != null && dirURL.getProtocol().equals("jar")) {
            String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
            JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
            Enumeration<JarEntry> entries = jar.entries();
            Set<String> result = new HashSet<String>();
            while (entries.hasMoreElements()) {
                String name = entries.nextElement().getName();
                if (name.startsWith(path)) {
                    String entry1 = name.substring(path.length());
                    int checkSubdir = entry1.indexOf("/");
                    if (checkSubdir >= 0) {
                        entry1 = entry1.substring(0, checkSubdir);
                    }
                    if (entry1.length() > 0) {
                        result.add(entry1);
                    }
                }
            }
            return new ArrayList<String>(result);
        }
        return null;
    } catch (Exception e) {
        throw new CouchDbException("fileURL: " + fileURL, e);
    }
}