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:org.kitesdk.data.hbase.tool.SchemaTool.java

/**
 * Gets the list of HBase Common Avro schema strings from a directory in the
 * Jar. It recursively searches the directory in the jar to find files that
 * end in .avsc to locate thos strings./* w ww .ja  v  a 2 s .co m*/
 * 
 * @param jarPath
 *          The path to the jar to search
 * @param directoryPath
 *          The directory in the jar to find avro schema strings
 * @return The list of schema strings.
 */
private List<String> getSchemaStringsFromJar(String jarPath, String directoryPath) {
    LOG.info("Getting schema strings in: " + directoryPath + ", from jar: " + jarPath);
    JarFile jar;
    try {
        jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new DatasetException(e);
    } catch (IOException e) {
        throw new DatasetException(e);
    }
    Enumeration<JarEntry> entries = jar.entries();
    List<String> schemaStrings = new ArrayList<String>();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.getName().startsWith(directoryPath) && jarEntry.getName().endsWith(".avsc")) {
            LOG.info("Found schema: " + jarEntry.getName());
            InputStream inputStream;
            try {
                inputStream = jar.getInputStream(jarEntry);
            } catch (IOException e) {
                throw new DatasetException(e);
            }
            String schemaString = AvroUtils.inputStreamToString(inputStream);
            schemaStrings.add(schemaString);
        }
    }
    return schemaStrings;
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {//from w  ww .ja  va 2 s. co  m
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir(expectedHomeDir);
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:org.primeframework.mvc.util.ClassClasspathResolver.java

private Collection<Class<U>> loadFromJar(File f, Test<Class<U>> test, boolean recursive,
        Iterable<String> locators, boolean embeddable) throws IOException {
    Set<Class<U>> matches = new HashSet<Class<U>>();

    JarFile jarFile;
    try {//  w  w w. ja v a2s. com
        jarFile = new JarFile(f);
    } catch (IOException e) {
        throw new IOException("Error opening JAR file [" + f.getAbsolutePath() + "]", e);
    }

    Enumeration<JarEntry> en = jarFile.entries();
    while (en.hasMoreElements()) {
        JarEntry entry = en.nextElement();
        String name = entry.getName();

        // Verify against the locators
        for (String locator : locators) {
            int index = name.indexOf(locator + "/");
            boolean match = (!embeddable && index == 0) || (embeddable && index >= 0);
            if (!match) {
                continue;
            }

            match = recursive || name.indexOf('/', index + locator.length() + 1) == -1;
            if (!match) {
                continue;
            }

            Testable<Class<U>> testable = test.prepare(f, jarFile, entry);
            if (testable != null && testable.passes()) {
                matches.add(testable.result());
                break;
            }
        }
    }

    jarFile.close();

    return matches;
}

From source file:org.interreg.docexplore.GeneralConfigPanel.java

String browseClasses(File file) {
    try {//from  ww w  . j  av  a  2s  .c  o m
        List<Class<?>> metaDataPlugins = new LinkedList<Class<?>>();
        List<Class<?>> analysisPlugins = new LinkedList<Class<?>>();
        List<Class<?>> clientPlugins = new LinkedList<Class<?>>();
        List<Class<?>> serverPlugins = new LinkedList<Class<?>>();
        List<Class<?>> inputPlugins = new LinkedList<Class<?>>();

        List<URL> urls = Startup.extractDependencies(file.getName().substring(0, file.getName().length() - 4),
                file.getName());
        urls.add(file.toURI().toURL());
        URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[] {}),
                this.getClass().getClassLoader());

        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (!entry.getName().endsWith(".class") || entry.getName().indexOf('$') > 0)
                continue;
            String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
            Class<?> clazz = null;
            try {
                clazz = loader.loadClass(className);
                System.out.println("Reading " + className);
            } catch (NoClassDefFoundError e) {
                System.out.println("Couldn't read " + className);
            }
            if (clazz == null)
                continue;

            if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))
                continue;
            if (MetaDataPlugin.class.isAssignableFrom(clazz))
                metaDataPlugins.add(clazz);
            if (AnalysisPlugin.class.isAssignableFrom(clazz))
                analysisPlugins.add(clazz);
            if (ClientPlugin.class.isAssignableFrom(clazz))
                clientPlugins.add(clazz);
            if (ServerPlugin.class.isAssignableFrom(clazz))
                serverPlugins.add(clazz);
            if (InputPlugin.class.isAssignableFrom(clazz))
                inputPlugins.add(clazz);
        }
        jarFile.close();

        @SuppressWarnings("unchecked")
        Pair<String, String>[] classes = new Pair[metaDataPlugins.size() + analysisPlugins.size()
                + clientPlugins.size() + serverPlugins.size() + inputPlugins.size()];
        if (classes.length == 0)
            throw new Exception("Invalid plugin (no entry points were found).");

        int cnt = 0;
        for (Class<?> clazz : metaDataPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "MetaData plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : analysisPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Analysis plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : clientPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader client plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : serverPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader server plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : inputPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader input plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        @SuppressWarnings("unchecked")
        Pair<String, String> res = (Pair<String, String>) JOptionPane.showInputDialog(this,
                "Please select an entry point for the plugin:", "Plugin entry point",
                JOptionPane.QUESTION_MESSAGE, null, classes, classes[0]);
        if (res != null)
            return res.first;
    } catch (Throwable e) {
        ErrorHandler.defaultHandler.submit(e);
    }
    return null;
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java

/**
 * Copy the contents of a jar file to another archive
 *
 * @param file The input jar file//from   w ww  . jav a 2  s .c  om
 * @param os   The output archive
 * @throws IOException
 */
protected void extractJarToArchive(JarFile file, ArchiveOutputStream os, String[] excludes) throws IOException {
    Enumeration<? extends JarEntry> entries = file.entries();
    while (entries.hasMoreElements()) {
        JarEntry j = entries.nextElement();

        if (excludes != null && excludes.length > 0) {
            for (String exclude : excludes) {
                if (SelectorUtils.match(exclude, j.getName())) {
                    continue;
                }
            }
        }

        if (StringUtils.equalsIgnoreCase(j.getName(), "META-INF/MANIFEST.MF")) {
            continue;
        }
        os.putArchiveEntry(new JarArchiveEntry(j.getName()));
        IOUtils.copy(file.getInputStream(j), os);
        os.closeArchiveEntry();
    }
    if (file != null) {
        file.close();
    }
}

From source file:edu.stanford.muse.email.JarDocCache.java

public void exportAsMbox(String outFilename, String prefix, Collection<EmailDocument> selectedDocs,
        boolean append) throws IOException, GeneralSecurityException, ClassNotFoundException {
    PrintWriter mbox = new PrintWriter(new FileOutputStream("filename", append));
    Map<Integer, Document> allHeadersMap = getAllHeaders(prefix);
    Map<Integer, Document> selectedHeadersMap = new LinkedHashMap<Integer, Document>();
    Set<EmailDocument> selectedDocsSet = new LinkedHashSet<EmailDocument>(selectedDocs);

    for (Integer I : allHeadersMap.keySet()) {
        EmailDocument ed = (EmailDocument) allHeadersMap.get(I);
        if (selectedDocsSet.contains(ed))
            selectedHeadersMap.put(I, ed);
    }//from w  w  w.ja  v  a 2  s .co  m

    JarFile contentJar = null;
    try {
        contentJar = new JarFile(baseDir + File.separator + prefix + ".contents");
    } catch (Exception e) {
        Util.print_exception(e, log);
        return;
    }

    Enumeration<JarEntry> contentEntries = contentJar.entries();
    String suffix = ".content";
    while (contentEntries.hasMoreElements()) {
        JarEntry c_je = contentEntries.nextElement();
        String s = c_je.getName();
        if (!s.endsWith(suffix))
            continue;
        int index = -1;
        String idx_str = s.substring(0, s.length() - suffix.length());
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        EmailDocument ed = (EmailDocument) selectedHeadersMap.get(index);
        if (ed == null)
            continue; // not selected

        byte[] b = Util.getBytesFromStream(contentJar.getInputStream(c_je));
        String contents = new String(b, "UTF-8");
        EmailUtils.printHeaderToMbox(ed, mbox);
        EmailUtils.printBodyAndAttachmentsToMbox(contents, ed, mbox, null);
        mbox.println(contents);
    }
}

From source file:org.wso2.carbon.integration.common.utils.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws URISyntaxException, IOException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarOutputStream jarOutputStream = null;
    InputStream inputStream = null;

    try {//from  w ww.  j a v  a2 s  .c om
        JarFile jarFile = new JarFile(sourceFile);
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
        File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
        jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            try {
                JarEntry jarEntry = entries.nextElement();
                inputStream = jarFile.getInputStream(jarEntry);
                //jarOutputStream.putNextEntry(jarEntry);
                //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
                jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    jarOutputStream.write(buffer, 0, bytesRead);
                }
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.warn("Fail to close jarOutStream");
                    }
                }
                if (jarOutputStream != null) {
                    try {
                        jarOutputStream.flush();
                        jarOutputStream.closeEntry();
                    } catch (IOException e) {
                        log.warn("Error while closing jar out stream");
                    }
                }
                if (jarFile != null) {
                    try {
                        jarFile.close();
                    } catch (IOException e) {
                        log.warn("Error while closing jar file");
                    }
                }
            }
        }
    } finally {
        if (jarOutputStream != null) {
            try {
                jarOutputStream.close();
            } catch (IOException e) {
                log.warn("Fail to close jarOutStream");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.warn("Error while closing input stream");
            }
        }
    }
}

From source file:org.apache.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF
 * (or a subdirectory of it), adding an implicit map entry to the taglib
 * map for any TLD that has a <uri> element.
 *
 * @param conn The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given
 * JAR should be ignored, false otherwise
 *///  w  ww.ja v  a 2  s .  co m
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();

    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable t) {
                        // do nothing
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
    }
}

From source file:com.cloudera.cdk.data.hbase.tool.SchemaTool.java

/**
 * Gets the list of HBase Common Avro schema strings from a directory in the
 * Jar. It recursively searches the directory in the jar to find files that
 * end in .avsc to locate thos strings.//from w w w  .ja va  2 s.  c  om
 * 
 * @param jarPath
 *          The path to the jar to search
 * @param directoryPath
 *          The directory in the jar to find avro schema strings
 * @return The list of schema strings.
 */
private List<String> getSchemaStringsFromJar(String jarPath, String directoryPath) {
    LOG.info("Getting schema strings in: " + directoryPath + ", from jar: " + jarPath);
    JarFile jar;
    try {
        jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new HBaseCommonException(e);
    } catch (IOException e) {
        throw new HBaseCommonException(e);
    }
    Enumeration<JarEntry> entries = jar.entries();
    List<String> schemaStrings = new ArrayList<String>();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.getName().startsWith(directoryPath) && jarEntry.getName().endsWith(".avsc")) {
            LOG.info("Found schema: " + jarEntry.getName());
            InputStream inputStream;
            try {
                inputStream = jar.getInputStream(jarEntry);
            } catch (IOException e) {
                throw new HBaseCommonException(e);
            }
            String schemaString = AvroUtils.inputStreamToString(inputStream);
            schemaStrings.add(schemaString);
        }
    }
    return schemaStrings;
}

From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

/**
 * Gets the classes from jar./*from  w  ww .  ja  v a 2  s  .c om*/
 * 
 * @param jar
 *            the jar
 * 
 * @return the classes from jar
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static LinkedList<String> getClassesFromJar(File jar) throws IOException {
    JarFile j = new JarFile(jar);

    LinkedList<String> list = new LinkedList<String>();

    // System.err.println("Jar entries: " + j.size());

    Enumeration<JarEntry> entries = j.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();

        if (entry.getName().endsWith(".class")) {
            String className = entry.getName().substring(0, entry.getName().lastIndexOf('.'));
            list.add(className.replace('/', '.'));
        }
        // System.err.println(entry);
    }
    return list;
}