Example usage for java.util.jar JarInputStream getNextJarEntry

List of usage examples for java.util.jar JarInputStream getNextJarEntry

Introduction

In this page you can find the example usage for java.util.jar JarInputStream getNextJarEntry.

Prototype

public JarEntry getNextJarEntry() throws IOException 

Source Link

Document

Reads the next JAR file entry and positions the stream at the beginning of the entry data.

Usage

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

private static void unjar(Resource jar, File baseDir) throws IOException {
    JarInputStream jis = new JarInputStream(jar.getInputStream());
    JarEntry entry = null;// ww w.  j av a2 s  . co m
    try {
        while ((entry = jis.getNextJarEntry()) != null) {
            if (!entry.isDirectory()) {
                File file = new File(baseDir, entry.getName());
                if (!file.getParentFile().mkdirs()) {
                    if (!file.getParentFile().isDirectory()) {
                        throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                    }
                }
                OutputStream out = new FileOutputStream(file);
                try {
                    byte[] buffer = new byte[8192];
                    int i;
                    while ((i = jis.read(buffer)) != -1) {
                        out.write(buffer, 0, i);
                    }
                } finally {
                    IOUtils.closeStream(out);
                }
            }
        }
    } finally {
        IOUtils.closeStream(jis);
    }
}

From source file:org.apache.geode.internal.DeployedJar.java

/**
 * Peek into the JAR data and make sure that it is valid JAR content.
 *
 * @param inputStream InputStream containing data to be validated.
 * @return True if the data has JAR content, false otherwise
 *///from w ww . j a va  2s.co m
private static boolean hasValidJarContent(final InputStream inputStream) {
    JarInputStream jarInputStream = null;
    boolean valid = false;

    try {
        jarInputStream = new JarInputStream(inputStream);
        valid = jarInputStream.getNextJarEntry() != null;
    } catch (IOException ignore) {
        // Ignore this exception and just return false
    } finally {
        try {
            jarInputStream.close();
        } catch (IOException ignored) {
            // Ignore this exception and just return result
        }
    }

    return valid;
}

From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java

/**
 * Loads a plugin descriptor from the given plugin jar and returns it. If the given jar does not
 * have a server plugin descriptor, <code>null</code> will be returned, meaning this is not
 * a server plugin jar.//from  w  w  w.j  a va2 s  .c  o  m
 *  
 * @param pluginJarFileUrl URL to a plugin jar file
 * @return the plugin descriptor found in the given plugin jar file, or <code>null</code> if there
 *         is no plugin descriptor in the jar file
 * @throws Exception if failed to parse the descriptor file found in the plugin jar
 */
public static ServerPluginDescriptorType loadPluginDescriptorFromUrl(URL pluginJarFileUrl) throws Exception {

    final Log logger = LogFactory.getLog(ServerPluginDescriptorUtil.class);

    if (pluginJarFileUrl == null) {
        throw new Exception("A valid plugin JAR URL must be supplied.");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]...");
    }

    testPluginJarIsReadable(pluginJarFileUrl);

    JarInputStream jis = null;
    JarEntry descriptorEntry = null;

    try {
        jis = new JarInputStream(pluginJarFileUrl.openStream());
        JarEntry nextEntry = jis.getNextJarEntry();
        while (nextEntry != null && descriptorEntry == null) {
            if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) {
                descriptorEntry = nextEntry;
            } else {
                jis.closeEntry();
                nextEntry = jis.getNextJarEntry();
            }
        }

        ServerPluginDescriptorType pluginDescriptor = null;

        if (descriptorEntry != null) {
            Unmarshaller unmarshaller = null;
            try {
                unmarshaller = getServerPluginDescriptorUnmarshaller();
                Object jaxbElement = unmarshaller.unmarshal(jis);
                pluginDescriptor = ((JAXBElement<? extends ServerPluginDescriptorType>) jaxbElement).getValue();
            } finally {
                if (unmarshaller != null) {
                    ValidationEventCollector validationEventCollector = (ValidationEventCollector) unmarshaller
                            .getEventHandler();
                    logValidationEvents(pluginJarFileUrl, validationEventCollector);
                }
            }
        }

        return pluginDescriptor;

    } catch (Exception e) {
        throw new Exception("Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH
                + "] found in plugin jar at [" + pluginJarFileUrl + "]", e);
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (Exception e) {
                logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e);
            }
        }
    }
}

From source file:org.artifactory.maven.MavenModelUtils.java

/**
 * Returns a JarEntry object if a valid pom file is found in the given jar input stream
 *
 * @param jis Input stream of given jar//ww  w  .j a  v a  2  s .  com
 * @return JarEntry object if a pom file is found. Null if not
 * @throws IOException Any exceptions that might occur while using the given stream
 */
private static JarEntry getPomFile(JarInputStream jis) throws IOException {
    if (jis != null) {
        JarEntry entry;
        while (((entry = jis.getNextJarEntry()) != null)) {
            String name = entry.getName();
            //Look for pom.xml in META-INF/maven/
            if (name.startsWith("META-INF/maven/") && name.endsWith("pom.xml")) {
                return entry;
            }
        }
    }
    return null;
}

From source file:org.eclipse.gemini.blueprint.util.DebugUtils.java

private static URL checkBundleJarsForClass(Bundle bundle, String name) {
    String cname = name.replace('.', '/') + ".class";
    for (Enumeration e = bundle.findEntries("/", "*.jar", true); e != null && e.hasMoreElements();) {
        URL url = (URL) e.nextElement();
        JarInputStream jin = null;
        try {/*w w  w.  java2s .c o m*/
            jin = new JarInputStream(url.openStream());
            // Copy entries from the real jar to our virtual jar
            for (JarEntry ze = jin.getNextJarEntry(); ze != null; ze = jin.getNextJarEntry()) {
                if (ze.getName().equals(cname)) {
                    jin.close();
                    return url;
                }
            }
        } catch (IOException e1) {
            log.trace("Skipped " + url.toString() + ": " + e1.getMessage());
        }

        finally {
            if (jin != null) {
                try {
                    jin.close();
                } catch (Exception ex) {
                    // ignore it
                }
            }
        }

    }
    return null;
}

From source file:petascope.util.IOUtil.java

public static List<String> filesInJarDir(String jarDir) {
    List<String> ret = new ArrayList<String>();
    JarInputStream jfile = null;
    try {/*from   ww w. j  a v a2 s.  co m*/
        // path to the jar
        String jarPath = IOUtil.class.getResource("").getPath();
        jarPath = jarPath.substring(0, jarPath.indexOf("!"));

        File file = new File(new URI(jarPath));
        jfile = new JarInputStream(new FileInputStream(file));
        JarEntry entry = null;
        do {
            try {
                entry = jfile.getNextJarEntry();
                if (entry == null) {
                    continue;
                }
                String sentry = entry.toString();
                if (("/" + sentry).contains(jarDir) && !sentry.endsWith("/")) {
                    ret.add(sentry);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } while (entry != null);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            jfile.close();
        } catch (Exception ex) {
        }
        return ret;
    }
}

From source file:org.jahia.utils.maven.plugin.support.MavenAetherHelperUtils.java

public static boolean doesJarHavePackageName(File jarFile, String packageName, Log log) {
    JarInputStream jarInputStream = null;
    if (jarFile == null) {
        log.warn("File is null !");
        return false;
    }/*w  w w  .ja va2  s .  c o  m*/
    if (!jarFile.exists()) {
        log.warn("File " + jarFile + " does not exist !");
        return false;
    }
    log.debug("Scanning JAR " + jarFile + "...");
    try {
        jarInputStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = null;
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            String jarPackageName = jarEntry.getName().replaceAll("/", ".");
            if (jarPackageName.endsWith(".")) {
                jarPackageName = jarPackageName.substring(0, jarPackageName.length() - 1);
            }
            if (jarPackageName.equals(packageName)) {
                return true;
            }
        }
    } catch (IOException e) {
        log.error(e);
        ;
    } finally {
        IOUtils.closeQuietly(jarInputStream);
    }
    return false;
}

From source file:org.diffkit.common.DKUnjar.java

/**
 * N.B. this method is much less efficient than the similar signature without
 * substitutions, so use that if you don't really need substitutions <br>
 * /*from   w  w  w .  ja va2 s  .  c  o  m*/
 * closes inputStream_ at the end
 */
public static void unjar(JarInputStream inputStream_, File outputDir_, Map<String, String> substitutions_)
        throws IOException {
    boolean isDebugEnabled = LOG.isDebugEnabled();
    if (isDebugEnabled)
        LOG.debug("substitutions_->{}", substitutions_);

    if (MapUtils.isEmpty(substitutions_))
        unjar(inputStream_, outputDir_);

    DKValidate.notNull(inputStream_, outputDir_);
    if (!outputDir_.isDirectory())
        throw new RuntimeException(String.format("directory does not exist->%s", outputDir_));

    JarEntry entry = null;
    while ((entry = inputStream_.getNextJarEntry()) != null) {
        String contents = IOUtils.toString(inputStream_);
        if (isDebugEnabled)
            LOG.debug("contents->{}", contents);
        contents = DKStringUtil.replaceEach(contents, substitutions_);
        if (isDebugEnabled)
            LOG.debug("substituted contents->{}", contents);
        File outFile = new File(outputDir_, entry.getName());
        FileUtils.writeStringToFile(outFile, contents);
    }
    inputStream_.close();
}

From source file:org.apache.pluto.util.assemble.io.JarStreamingAssembly.java

/**
 * Reads the source JarInputStream, copying entries to the destination JarOutputStream. 
 * The web.xml and portlet.xml are cached, and after the entire archive is copied 
 * (minus the web.xml) a re-written web.xml is generated and written to the 
 * destination JAR./*from ww  w.  ja  v  a 2  s.co m*/
 * 
 * @param source the WAR source input stream
 * @param dest the WAR destination output stream
 * @param dispatchServletClass the name of the dispatch class
 * @throws IOException
 */
public static void assembleStream(JarInputStream source, JarOutputStream dest, String dispatchServletClass)
        throws IOException {

    try {
        //Need to buffer the web.xml and portlet.xml files for the rewritting
        JarEntry servletXmlEntry = null;
        byte[] servletXmlBuffer = null;
        byte[] portletXmlBuffer = null;

        JarEntry originalJarEntry;

        //Read the source archive entry by entry
        while ((originalJarEntry = source.getNextJarEntry()) != null) {

            final JarEntry newJarEntry = smartClone(originalJarEntry);
            originalJarEntry = null;

            //Capture the web.xml JarEntry and contents as a byte[], don't write it out now or
            //update the CRC or length of the destEntry.
            if (Assembler.SERVLET_XML.equals(newJarEntry.getName())) {
                servletXmlEntry = newJarEntry;
                servletXmlBuffer = IOUtils.toByteArray(source);
            }

            //Capture the portlet.xml contents as a byte[]
            else if (Assembler.PORTLET_XML.equals(newJarEntry.getName())) {
                portletXmlBuffer = IOUtils.toByteArray(source);
                dest.putNextEntry(newJarEntry);
                IOUtils.write(portletXmlBuffer, dest);
            }

            //Copy all other entries directly to the output archive
            else {
                dest.putNextEntry(newJarEntry);
                IOUtils.copy(source, dest);
            }

            dest.closeEntry();
            dest.flush();

        }

        // If no portlet.xml was found in the archive, skip the assembly step.
        if (portletXmlBuffer != null) {
            // container for assembled web.xml bytes
            final byte[] webXmlBytes;

            // Checks to make sure the web.xml was found in the archive
            if (servletXmlBuffer == null) {
                throw new FileNotFoundException(
                        "File '" + Assembler.SERVLET_XML + "' could not be found in the source input stream.");
            }

            //Create streams of the byte[] data for the updater method
            final InputStream webXmlIn = new ByteArrayInputStream(servletXmlBuffer);
            final InputStream portletXmlIn = new ByteArrayInputStream(portletXmlBuffer);
            final ByteArrayOutputStream webXmlOut = new ByteArrayOutputStream(servletXmlBuffer.length);

            //Update the web.xml
            WebXmlStreamingAssembly.assembleStream(webXmlIn, portletXmlIn, webXmlOut, dispatchServletClass);
            IOUtils.copy(webXmlIn, webXmlOut);
            webXmlBytes = webXmlOut.toByteArray();

            //If no compression is being used (STORED) we have to manually update the size and crc
            if (servletXmlEntry.getMethod() == ZipEntry.STORED) {
                servletXmlEntry.setSize(webXmlBytes.length);
                final CRC32 webXmlCrc = new CRC32();
                webXmlCrc.update(webXmlBytes);
                servletXmlEntry.setCrc(webXmlCrc.getValue());
            }

            //write out the assembled web.xml entry and contents
            dest.putNextEntry(servletXmlEntry);
            IOUtils.write(webXmlBytes, dest);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Jar stream " + source + " successfully assembled.");
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No portlet XML file was found, assembly was not required.");
            }

            //copy the original, unmodified web.xml entry to the destination
            dest.putNextEntry(servletXmlEntry);
            IOUtils.write(servletXmlBuffer, dest);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Jar stream " + source + " successfully assembled.");
            }
        }

    } finally {

        dest.flush();
        dest.close();

    }
}

From source file:org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.java

/**
 * Loads a plugin descriptor from the given plugin jar and returns it.
 *
 * This is a static method to provide a convenience method for others to be able to use.
 *
 * @param pluginJarFileUrl URL to a plugin jar file
 * @return the plugin descriptor found in the given plugin jar file
 * @throws PluginContainerException if failed to find or parse a descriptor file in the plugin jar
 *//*from   w ww  . j  a  v  a2 s .c om*/
public static PluginDescriptor loadPluginDescriptorFromUrl(URL pluginJarFileUrl)
        throws PluginContainerException {

    final Log logger = LogFactory.getLog(AgentPluginDescriptorUtil.class);

    if (pluginJarFileUrl == null) {
        throw new PluginContainerException("A valid plugin JAR URL must be supplied.");
    }
    logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]...");

    testPluginJarIsReadable(pluginJarFileUrl);

    JarInputStream jis = null;
    JarEntry descriptorEntry = null;
    ValidationEventCollector validationEventCollector = new ValidationEventCollector();
    try {
        jis = new JarInputStream(pluginJarFileUrl.openStream());
        JarEntry nextEntry = jis.getNextJarEntry();
        while (nextEntry != null && descriptorEntry == null) {
            if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) {
                descriptorEntry = nextEntry;
            } else {
                jis.closeEntry();
                nextEntry = jis.getNextJarEntry();
            }
        }

        if (descriptorEntry == null) {
            throw new Exception("The plugin descriptor does not exist");
        }

        return parsePluginDescriptor(jis, validationEventCollector);
    } catch (Exception e) {
        throw new PluginContainerException(
                "Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH
                        + "] found in plugin jar at [" + pluginJarFileUrl + "].",
                new WrappedRemotingException(e));
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (Exception e) {
                logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e);
            }
        }

        logValidationEvents(pluginJarFileUrl, validationEventCollector, logger);
    }
}