Example usage for java.util.jar JarFile getInputStream

List of usage examples for java.util.jar JarFile getInputStream

Introduction

In this page you can find the example usage for java.util.jar JarFile getInputStream.

Prototype

public synchronized InputStream getInputStream(ZipEntry ze) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.kantega.revoc.source.MavenSourceArtifactSourceSource.java

private MavenSourceInfo parseInfo(String filePath, URL resource) {

    File file = new File(filePath);

    JarFile jarFile = null;
    boolean isNewFile = false;
    try {//from  w w w  . j  a v a  2  s.co  m
        URLConnection urlConnection = resource.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            jarFile = ((JarURLConnection) urlConnection).getJarFile();
        } else {
            jarFile = new JarFile(file);
            isNewFile = true;
        }
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String prefix = "META-INF/maven/";
            String propSuffix = "/pom.properties";

            if (entry.getName().startsWith(prefix) && entry.getName().endsWith(propSuffix)) {
                Properties props = new Properties();
                InputStream inputStream = jarFile.getInputStream(entry);
                props.load(inputStream);
                inputStream.close();
                String groupId = props.getProperty("groupId");
                String artifactId = props.getProperty("artifactId");
                String version = props.getProperty("version");

                if (file.getName().startsWith(artifactId + "-" + version)) {
                    return new MavenSourceInfo(groupId, artifactId, version);
                }

            }
        }
        return null;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (isNewFile) {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

From source file:com.icesoft.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
 *///from   www  .ja  v  a2 s  .c o  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 (IOException e) {
                        if (log.isDebugEnabled()) {
                            log.debug(e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    }
}

From source file:net.rim.ejde.internal.packaging.PackagingJob.java

/**
 * If the cod file represented by the given <code>codFilePath</code> contains sibling cod file, un-zip it and copy all sibling
 * cod files to the <code>destinationFolderPath</code>. If the cod file is a single cod file, just copy it to the
 * <code>destinationFolderPath</code>.
 *
 * @param codFilePath//from  w  ww  .  ja v a 2 s.c om
 * @param destinationFolderPath
 * @throws CoreException
 */
private void copySiblingCod(IPath codFilePath, IPath destinationFolderPath) throws CoreException {
    boolean hasSiblingCod = false;
    File codFile = codFilePath.toFile();
    try {
        JarFile zipFile = new JarFile(codFile);
        Enumeration<JarEntry> entries = zipFile.entries();
        if (entries.hasMoreElements()) {
            hasSiblingCod = true;
            JarEntry entry;
            for (; entries.hasMoreElements();) {
                entry = entries.nextElement();
                if (entry.isDirectory()) {
                    // this should not happen
                    continue;
                }
                InputStream is = zipFile.getInputStream(entry);
                File outputFile = destinationFolderPath.append(entry.getName()).toFile();
                PackagingManager.copyInputStream(is,
                        new BufferedOutputStream(new FileOutputStream(outputFile)));
            }
        } else {
            hasSiblingCod = false;
        }
    } catch (IOException e) {
        if (codFile.exists()) {
            // if the cod file does not contain any sibling file, we get IOException
            hasSiblingCod = false;
        } else {
            _log.error(e);
        }
    } finally {
        if (!hasSiblingCod) {
            // if the cod file is a single cod file, copy it to the destination
            DeploymentHelper.executeCopy(codFile, destinationFolderPath.append(codFile.getName()).toFile());
        }
    }
}

From source file:org.apache.struts2.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
 *//*  www .j  av  a2 s.c  o 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:org.openeos.tools.maven.plugins.GenerateEntitiesMojo.java

private List<File> findLiquibaseFiles(Artifact artifact) throws IOException {

    if (artifact == null) {
        return Collections.emptyList();
    }/* www. j av  a2s. co m*/
    List<File> result = new ArrayList<File>();

    if (artifact.getType().equals("jar")) {
        File file = artifact.getFile();
        FileSystem fs = FileSystems.newFileSystem(Paths.get(file.getAbsolutePath()),
                this.getClass().getClassLoader());
        PathMatcher matcher = fs.getPathMatcher("glob:" + searchpath);
        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> entries = jarFile.entries();
        TreeSet<JarEntry> setEntries = new TreeSet<JarEntry>(new Comparator<JarEntry>() {

            @Override
            public int compare(JarEntry o1, JarEntry o2) {
                return o1.getName().compareTo(o2.getName());
            }

        });
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (matcher.matches(fs.getPath(entry.getName()))) {
                setEntries.add(entry);
            }
        }
        for (JarEntry entry : setEntries) {
            File resultFile = File.createTempFile("generate-entities-maven", ".xml");
            FileOutputStream out = new FileOutputStream(resultFile);
            InputStream in = jarFile.getInputStream(entry);
            IOUtils.copy(in, out);
            in.close();
            out.close();
            result.add(resultFile);
        }
        jarFile.close();
    }
    return result;
}

From source file:com.datatorrent.stram.webapp.TypeGraph.java

public TypeGraphVertex addNode(JarEntry jarEntry, JarFile jar) throws IOException {
    return addNode(jar.getInputStream(jarEntry), jar.getName());
}

From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleJarPath = getModuleJarPath(moduleId);
    Files.deleteIfExists(moduleJarPath);
    JarFile sourceJarFile;
    try {//from ww w .j a  va  2  s .c o m
        sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile()));
    try {
        String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName();
        Enumeration<JarEntry> sourceEntries = sourceJarFile.entries();
        while (sourceEntries.hasMoreElements()) {
            JarEntry sourceEntry = sourceEntries.nextElement();
            if (sourceEntry.getName().equals(moduleSpecFileName)) {
                // avoid double entry for module spec
                continue;
            }
            destJarFile.putNextEntry(sourceEntry);
            if (!sourceEntry.isDirectory()) {
                InputStream inputStream = sourceJarFile.getInputStream(sourceEntry);
                IOUtils.copy(inputStream, destJarFile);
                IOUtils.closeQuietly(inputStream);
            }
            destJarFile.closeEntry();
        }
        // write the module spec
        String serialized = moduleSpecSerializer.serialize(moduleSpec);
        JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName());
        destJarFile.putNextEntry(moduleSpecEntry);
        IOUtils.write(serialized, destJarFile);
        destJarFile.closeEntry();
    } finally {
        IOUtils.closeQuietly(sourceJarFile);
        IOUtils.closeQuietly(destJarFile);
    }
    // update the timestamp on the jar file to indicate that the module has been updated
    Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:org.jahia.configuration.configurators.JahiaGlobalConfiguratorTest.java

public void testGlobalConfiguration() throws Exception {

    JahiaConfigBean websphereDerbyConfigBean;

    Logger logger = LoggerFactory.getLogger(JahiaGlobalConfiguratorTest.class);

    URL configuratorsResourceURL = this.getClass().getClassLoader().getResource("configurators");
    File configuratorsFile = new File(configuratorsResourceURL.toURI());

    websphereDerbyConfigBean = new JahiaConfigBean();
    websphereDerbyConfigBean.setDatabaseType("derby_embedded");
    websphereDerbyConfigBean.setTargetServerType("was");
    websphereDerbyConfigBean.setTargetServerVersion("6.1.0.25");
    websphereDerbyConfigBean.setTargetConfigurationDirectory(configuratorsFile.toString());
    websphereDerbyConfigBean.setCluster_activated("true");
    websphereDerbyConfigBean.setCluster_node_serverId("jahiaServer1");
    websphereDerbyConfigBean.setProcessingServer("true");
    websphereDerbyConfigBean.setLdapActivated("true");
    websphereDerbyConfigBean.setExternalizedConfigActivated(true);
    websphereDerbyConfigBean.setExternalizedConfigExploded(false);
    websphereDerbyConfigBean.setExternalizedConfigTargetPath(configuratorsFile.getPath());
    websphereDerbyConfigBean.setExternalizedConfigClassifier("jahiaServer1");
    websphereDerbyConfigBean.setExternalizedConfigFinalName("jahia-externalized-config");
    websphereDerbyConfigBean.setJeeApplicationLocation(configuratorsFile.toString());
    websphereDerbyConfigBean.setJeeApplicationModuleList(
            "jahia-war:web:jahia.war:jahia,portlet-testsuite:web:websphere-testsuite.war:testsuite,java-example:java:somecode.jar");
    websphereDerbyConfigBean.setJahiaToolManagerUsername("toolmgr");

    JahiaGlobalConfigurator jahiaGlobalConfigurator = new JahiaGlobalConfigurator(new SLF4JLogger(logger),
            websphereDerbyConfigBean);// w w w.  ja v  a  2 s. c om
    jahiaGlobalConfigurator.execute();

    File configFile = new File(configuratorsFile, "jahia-externalized-config-jahiaServer1.jar");
    JarFile configJarFile = new JarFile(configFile);
    try {
        JarEntry licenseJarEntry = configJarFile.getJarEntry("jahia/license.xml");
        assertNotNull("Missing license file in jahia-externalized-config-jahiaServer1.jar file!",
                licenseJarEntry);
        JarEntry jahiaPropertiesJarEntry = configJarFile.getJarEntry("jahia/jahia.jahiaServer1.properties");
        assertNotNull(
                "Missing jahia.jahiaServer1.properties file in jahia-externalized-config-jahiaServer1.jar file!",
                jahiaPropertiesJarEntry);
        JarEntry jahiaAdvancedPropertiesJarEntry = configJarFile
                .getJarEntry("jahia/jahia.node.jahiaServer1.properties");
        assertNotNull(
                "Missing jahia.node.jahiaServer1.properties file in jahia-externalized-config-jahiaServer1.jar file!",
                jahiaAdvancedPropertiesJarEntry);

        InputStream jahiaPropsInputStream = configJarFile.getInputStream(jahiaPropertiesJarEntry);
        Properties jahiaProperties = new Properties();
        jahiaProperties.load(jahiaPropsInputStream);
        assertEquals("Tool manager is not set", "toolmgr", jahiaProperties.get("jahiaToolManagerUsername"));
    } finally {
        configJarFile.close();
    }
    // The following tests are NOT exhaustive
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document jdomDocument = saxBuilder.build(configuratorsFile.toString() + "/META-INF/application.xml");
    String prefix = "";

    assertAllTextEquals(jdomDocument, "//application/module[@id=\"jahia-war\"]/web/web-uri/text()", prefix,
            "jahia.war");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"jahia-war\"]/web/context-root/text()", prefix,
            "jahia");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"portlet-testsuite\"]/web/web-uri/text()",
            prefix, "websphere-testsuite.war");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"portlet-testsuite\"]/web/context-root/text()",
            prefix, "testsuite");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"java-example\"]/java/text()", prefix,
            "somecode.jar");

}

From source file:com.smartitengineering.cms.maven.tools.plugin.StartMojo.java

protected void extract(File jarFile, File outDir) {
    try {//from  w  w w.j a v a  2 s  .  c o  m
        getLog().info(new StringBuilder("Extracting ").append(jarFile.getAbsolutePath()).append(" to ")
                .append(outDir.getAbsolutePath()).toString());
        java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
        java.util.Enumeration enumeration = jar.entries();
        while (enumeration.hasMoreElements()) {
            java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumeration.nextElement();
            final String str = new StringBuilder(outDir.getAbsolutePath()).append(File.separator)
                    .append(file.getName()).toString();
            File f = new File(str);
            if (file.isDirectory()) {
                f.mkdir();
                continue;
            }
            getLog().debug(new StringBuilder("Extracting ").append(file.getName()).append(" to ").append(str)
                    .toString());
            java.io.InputStream is = jar.getInputStream(file); // get the input stream
            java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
            IOUtils.copy(is, fos);
            fos.close();
            is.close();
        }
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:org.apache.nifi.web.server.JettyServer.java

private void readUiExtensions(final Map<UiExtensionType, List<String>> uiExtensions,
        final UiExtensionType uiExtensionType, final JarFile jarFile, final JarEntry jarEntry)
        throws IOException {
    if (jarEntry == null) {
        return;/*from  w  ww  .jav a  2s . c  o m*/
    }

    // get an input stream for the nifi-processor configuration file
    try (BufferedReader in = new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry)))) {

        // read in each configured type
        String rawComponentType;
        while ((rawComponentType = in.readLine()) != null) {
            // extract the component type
            final String componentType = extractComponentType(rawComponentType);
            if (componentType != null) {
                List<String> extensions = uiExtensions.get(uiExtensionType);

                // if there are currently no extensions for this type create it
                if (extensions == null) {
                    extensions = new ArrayList<>();
                    uiExtensions.put(uiExtensionType, extensions);
                }

                // add the specified type
                extensions.add(componentType);
            }
        }
    }
}