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:com.xiovr.unibot.plugin.impl.PluginLoaderImpl.java

private Properties getPluginProps(File file) throws IOException {
    Properties result = null;//w w  w  .java  2  s  .com
    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> entries = jar.entries();

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().equals(PROPERTY_FILE_NAME)) {
            // That's it! Load props
            InputStream is = null;
            try {
                is = jar.getInputStream(entry);
                result = new Properties();
                result.load(is);
            } finally {
                if (is != null)
                    is.close();
            }
        }
    }
    jar.close();
    return result;
}

From source file:org.b3log.latke.servlet.RequestProcessors.java

/**
 * Scans classpath (lib directory) to discover request processor classes.
 *///from ww w  .  ja va 2 s.  c o  m
private static void discoverFromLibDir() {
    final String webRoot = AbstractServletListener.getWebRoot();
    final File libDir = new File(
            webRoot + File.separator + "WEB-INF" + File.separator + "lib" + File.separator);
    @SuppressWarnings("unchecked")
    final Collection<File> files = FileUtils.listFiles(libDir, new String[] { "jar" }, true);

    final ClassLoader classLoader = RequestProcessors.class.getClassLoader();

    try {
        for (final File file : files) {
            if (file.getName().contains("appengine-api") || file.getName().startsWith("freemarker")
                    || file.getName().startsWith("javassist") || file.getName().startsWith("commons")
                    || file.getName().startsWith("mail") || file.getName().startsWith("activation")
                    || file.getName().startsWith("slf4j") || file.getName().startsWith("bonecp")
                    || file.getName().startsWith("jsoup") || file.getName().startsWith("guava")
                    || file.getName().startsWith("markdown") || file.getName().startsWith("mysql")
                    || file.getName().startsWith("c3p0")) {
                // Just skips some known dependencies hardly....
                LOGGER.log(Level.INFO, "Skipped request processing discovery[jarName={0}]", file.getName());

                continue;
            }

            final JarFile jarFile = new JarFile(file.getPath());
            final Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                final JarEntry jarEntry = entries.nextElement();
                final String classFileName = jarEntry.getName();

                if (classFileName.contains("$") // Skips inner class
                        || !classFileName.endsWith(".class")) {
                    continue;
                }

                final DataInputStream classInputStream = new DataInputStream(jarFile.getInputStream(jarEntry));

                final ClassFile classFile = new ClassFile(classInputStream);
                final AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) classFile
                        .getAttribute(AnnotationsAttribute.visibleTag);

                if (null == annotationsAttribute) {
                    continue;
                }

                for (Annotation annotation : annotationsAttribute.getAnnotations()) {
                    if ((annotation.getTypeName()).equals(RequestProcessor.class.getName())) {
                        // Found a request processor class, loads it
                        final String className = classFile.getName();
                        final Class<?> clz = classLoader.loadClass(className);

                        LOGGER.log(Level.FINER, "Found a request processor[className={0}]", className);
                        final Method[] declaredMethods = clz.getDeclaredMethods();

                        for (int i = 0; i < declaredMethods.length; i++) {
                            final Method mthd = declaredMethods[i];
                            final RequestProcessing requestProcessingMethodAnn = mthd
                                    .getAnnotation(RequestProcessing.class);

                            if (null == requestProcessingMethodAnn) {
                                continue;
                            }

                            addProcessorMethod(requestProcessingMethodAnn, clz, mthd);
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Scans classpath (lib directory) failed", e);
    }
}

From source file:org.massyframework.modules.utils.SunJdkModuleExporter.java

/**
 * ?SunJdk??/*from   w  w  w.  j a  v  a  2 s .c  o  m*/
 * 
 * @param fileName
 * @return
 * @throws IOException
 */
protected List<String> getSunJdkPackageNames(String rtJar) throws IOException {
    Set<String> packageNames = new HashSet<String>();
    JarFile file = null;
    try {
        file = new JarFile(rtJar);
        Enumeration<JarEntry> em = file.entries();
        while (em.hasMoreElements()) {
            JarEntry entry = em.nextElement();
            if (!entry.isDirectory()) {
                String name = entry.getName();
                if (name.endsWith(".class")) {
                    int index = StringUtils.lastIndexOf(name, "/");
                    packageNames.add(StringUtils.substring(name, 0, index));
                }
            }
        }
    } finally {
        IOUtils.closeStream(file);
    }
    List<String> result = new ArrayList<String>(packageNames);
    Collections.sort(result);
    return result;
}

From source file:org.sonar.server.plugins.ClassLoaderUtils.java

/**
 * Finds directories and files within a given directory and its subdirectories.
 *
 * @param classLoader//from  www  .  ja  v  a 2 s .  c o m
 * @param rootPath    the root directory, for example org/sonar/sqale, or a file in this root directory, for example org/sonar/sqale/index.txt
 * @param
 * @return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo", "org/sonar/sqale/foo/bar.txt}. Never null.
 */
public static Collection<String> listResources(ClassLoader classLoader, String rootPath,
        Predicate<String> predicate) {
    String jarPath = null;
    JarFile jar = null;
    try {
        Collection<String> paths = Lists.newArrayList();
        rootPath = StringUtils.removeStart(rootPath, "/");

        URL root = classLoader.getResource(rootPath);
        if (root != null) {
            checkJarFile(root);

            // Path of the root directory
            // Examples :
            // org/sonar/sqale/index.txt  -> rootDirectory is org/sonar/sqale
            // org/sonar/sqale/  -> rootDirectory is org/sonar/sqale
            // org/sonar/sqale  -> rootDirectory is org/sonar/sqale
            String rootDirectory = rootPath;
            if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) {
                rootDirectory = StringUtils.substringBeforeLast(rootPath, "/");
            }
            jarPath = root.getPath().substring(5, root.getPath().indexOf("!")); //strip out only the JAR file
            jar = new JarFile(URLDecoder.decode(jarPath, CharEncoding.UTF_8));
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String name = entries.nextElement().getName();
                if (name.startsWith(rootDirectory) && predicate.apply(name)) {
                    paths.add(name);
                }
            }
        }
        return paths;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    } finally {
        closeJar(jar, jarPath);
    }
}

From source file:org.apache.hadoop.hive.ql.exec.tez.HivePreWarmProcessor.java

@Override
public void run(Map<String, LogicalInput> inputs, Map<String, LogicalOutput> outputs) throws Exception {
    if (prewarmed) {
        /* container reuse */
        return;// w w  w .  j  a  va2 s. c o m
    }
    for (LogicalInput input : inputs.values()) {
        input.start();
    }
    for (LogicalOutput output : outputs.values()) {
        output.start();
    }
    /* these are things that goes through singleton initialization on most queries */
    FileSystem fs = FileSystem.get(conf);
    Mac mac = Mac.getInstance("HmacSHA1");
    ReadaheadPool rpool = ReadaheadPool.getInstance();
    ShimLoader.getHadoopShims();

    URL hiveurl = new URL("jar:" + DagUtils.getInstance().getExecJarPathLocal() + "!/");
    JarURLConnection hiveconn = (JarURLConnection) hiveurl.openConnection();
    JarFile hivejar = hiveconn.getJarFile();
    try {
        Enumeration<JarEntry> classes = hivejar.entries();
        while (classes.hasMoreElements()) {
            JarEntry je = classes.nextElement();
            if (je.getName().endsWith(".class")) {
                String klass = je.getName().replace(".class", "").replaceAll("/", "\\.");
                if (klass.indexOf("ql.exec") != -1 || klass.indexOf("ql.io") != -1) {
                    /* several hive classes depend on the metastore APIs, which is not included
                     * in hive-exec.jar. These are the relatively safe ones - operators & io classes.
                     */
                    if (klass.indexOf("vector") != -1 || klass.indexOf("Operator") != -1) {
                        JavaUtils.loadClass(klass);
                    }
                }
            }
        }
    } finally {
        hivejar.close();
    }
    prewarmed = true;
}

From source file:org.xwiki.webjars.internal.WebJarsExportURLFactoryActionHandler.java

private void copyResourceFromJAR(String resourcePath, String prefix, ExportURLFactoryContext factoryContext)
        throws IOException {
    // Note that we cannot use ClassLoader.getResource() to access the resource since the resourcePath may point
    // to a directory inside the JAR, and in this case we need to copy all resources inside that directory in the
    // JAR!/* w ww.j a  va  2  s . c  o m*/

    JarFile jar = new JarFile(getJARFile(resourcePath));
    for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (entry.getName().startsWith(resourcePath) && !entry.isDirectory()) {
            // Copy the resource!
            String targetPath = prefix + entry.getName();
            File targetLocation = new File(factoryContext.getExportDir(), targetPath);
            if (!targetLocation.exists()) {
                targetLocation.getParentFile().mkdirs();
                FileOutputStream fos = new FileOutputStream(targetLocation);
                InputStream is = jar.getInputStream(entry);
                IOUtils.copy(is, fos);
                fos.close();
                is.close();
            }
        }
    }
    jar.close();
}

From source file:de.micromata.tpsb.doc.sources.JarSourceFileRepository.java

@Override
public Collection<JavaSourceFileHolder> getSources() {
    List<JavaSourceFileHolder> fileContentList = new ArrayList<JavaSourceFileHolder>();

    for (String jarFileName : getLocations()) {
        try {/*  w w w  .  j a va2s  .  c o  m*/
            JarFile jarFile;
            jarFile = new JarFile(jarFileName);
            Enumeration<? extends ZipEntry> jarEntryEnum = jarFile.entries();

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

                // nur Java-Dateien beachten
                if (jarEntry.isDirectory() || StringUtils.endsWith(jarEntry.getName(), ".java") == false) {
                    continue;
                }

                String javaFilename = jarEntry.getName();
                String javaFileContent = getContents(jarFile, jarEntry);

                if (StringUtils.isBlank(javaFileContent) == true) {
                    continue;
                }
                JavaSourceFileHolder fileHolder = new JavaSourceFileHolder(javaFilename, javaFileContent);
                fileHolder.setSource(Source.Jar);
                fileHolder.setOrigin(jarFileName);
                fileContentList.add(fileHolder);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return fileContentList;
}

From source file:javadepchecker.Main.java

public void processJar(JarFile jar) throws IOException {
    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        String name = entry.getName();
        if (!entry.isDirectory() && name.endsWith(".class")) {
            this.current.add(name);
            InputStream stream = jar.getInputStream(entry);
            ClassParser parser = new ClassParser(stream, name);
            JavaClass jclass = parser.parse();
            this.pool = jclass.getConstantPool();
            new DescendingVisitor(jclass, this).visitConstantPool(this.pool);
        }/*from  w w w.  j a va  2 s .  co  m*/
    }
}

From source file:hudson.remoting.RegExpBenchmark.java

private List<String> getAllRTClasses() throws Exception {
    List<String> classes = new ArrayList<String>();
    // Object.class.getProtectionDomain().getCodeSource() returns null :(
    String javaHome = System.getProperty("java.home");
    JarFile jf = new JarFile(javaHome + "/lib/rt.jar");
    for (JarEntry je : Collections.list(jf.entries())) {
        if (!je.isDirectory() && je.getName().endsWith(".class")) {
            String name = je.getName().replace('/', '.');
            // remove the .class
            name = name.substring(0, name.length() - 6);
            classes.add(name);//from w w w.java2s .  co m
        }
    }
    jf.close();
    // add in a couple from xalan and commons just for testing...
    classes.add(new String("org.apache.commons.collections.functors.EvilClass"));
    classes.add(new String("org.codehaus.groovy.runtime.IWIllHackYou"));
    classes.add(new String("org.apache.xalan.YouAreOwned"));
    return classes;
}

From source file:i18nplugin.TranslationNode.java

/**
 * Create Tree//ww  w  . ja v a 2s. co  m
 * @param string Name of Tree-Node
 * @param file Jar-File with Properties
 */
public TranslationNode(String string, File file) {
    super(string);

    try {
        JarFile jarfile = new JarFile(file);

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

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();

            if (entry.getName().endsWith(".properties")) {
                String name = entry.getName();

                name = name.substring(0, name.length() - 11);

                if (name.indexOf('/') >= 0) {
                    String dir = StringUtils.substringBeforeLast(name, "/");

                    if (dir.contains("/")) {
                        dir = StringUtils.substringAfterLast(dir, "/");
                    }

                    name = StringUtils.substringAfterLast(name, "/");

                    if (name.equals(dir)) {
                        addEntry(jarfile, entry);
                    }
                }
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}