Example usage for java.util.jar JarInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java

private List<PaletteElementInfo> extractElementsFromJarByManifest(JarInputStream jarStream) throws Exception {
    List<PaletteElementInfo> elements = Lists.newArrayList();
    Manifest manifest = jarStream.getManifest();
    // check manifest, if null find it
    if (manifest == null) {
        try {//  www  .java  2s  .com
            while (true) {
                JarEntry entry = jarStream.getNextJarEntry();
                if (entry == null) {
                    break;
                }
                if (JarFile.MANIFEST_NAME.equalsIgnoreCase(entry.getName())) {
                    // read manifest data
                    byte[] buffer = IOUtils.toByteArray(jarStream);
                    jarStream.closeEntry();
                    // create manifest
                    manifest = new Manifest(new ByteArrayInputStream(buffer));
                    break;
                }
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
            manifest = null;
        }
    }
    if (manifest != null) {
        // extract all "Java-Bean: True" classes
        for (Iterator<Map.Entry<String, Attributes>> I = manifest.getEntries().entrySet().iterator(); I
                .hasNext();) {
            Map.Entry<String, Attributes> mapElement = I.next();
            Attributes attributes = mapElement.getValue();
            if (JAVA_BEAN_VALUE.equalsIgnoreCase(attributes.getValue(JAVA_BEAN_KEY))) {
                String beanClass = mapElement.getKey();
                if (beanClass == null || beanClass.length() <= JAVA_BEAN_CLASS_SUFFIX.length()) {
                    continue;
                }
                // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc'
                PaletteElementInfo element = new PaletteElementInfo();
                element.className = StringUtils.substringBeforeLast(beanClass, JAVA_BEAN_CLASS_SUFFIX)
                        .replace('/', '.');
                element.name = CodeUtils.getShortClass(element.className);
                elements.add(element);
            }
        }
    }
    return elements;
}

From source file:org.jahia.admin.components.AssemblerTask.java

private boolean needRewriting(File source) throws FileNotFoundException, IOException {
    final JarInputStream jarIn = new JarInputStream(new FileInputStream(source));
    String webXml = null;// w w  w . j  a  va 2  s  .  c om
    JarEntry jarEntry;
    try {
        // Read the source archive entry by entry
        while ((jarEntry = jarIn.getNextJarEntry()) != null) {
            if (Assembler.SERVLET_XML.equals(jarEntry.getName())) {
                webXml = IOUtils.toString(jarIn);
            }
            jarIn.closeEntry();
        }
    } finally {
        jarIn.close();
    }

    return webXml == null || !webXml.contains(Assembler.DISPATCH_SERVLET_CLASS);
}

From source file:org.ngrinder.common.util.CompressionUtil.java

/**
 * Unpack the given jar file./*w w w . j a  v  a  2s.c  om*/
 * 
 * @param jarFile
 *            file to be uncompressed
 * @param destDir
 *            destination directory
 * @throws IOException
 *             occurs when IO has a problem.
 */
public static void unjar(File jarFile, String destDir) throws IOException {
    File dest = new File(destDir);
    if (!dest.exists()) {
        dest.mkdirs();
    }
    if (!dest.isDirectory()) {
        LOGGER.error("Destination must be a directory.");
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(new FileInputStream(jarFile));
    byte[] buffer = new byte[1024];

    ZipEntry entry = jin.getNextEntry();
    while (entry != null) {
        String fileName = entry.getName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        if (fileName.charAt(0) == '/') {
            fileName = fileName.substring(1);
        }
        if (File.separatorChar != '/') {
            fileName = fileName.replace('/', File.separatorChar);
        }
        File file = new File(dest, fileName);
        if (entry.isDirectory()) {
            // make sure the directory exists
            file.mkdirs();
            jin.closeEntry();
        } else {
            // make sure the directory exists
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            // dump the file
            OutputStream out = new FileOutputStream(file);
            int len = 0;
            while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            IOUtils.closeQuietly(out);
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        IOUtils.closeQuietly(out);
    }
    IOUtils.closeQuietly(jin);
}

From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {//w ww.ja va 2  s.  co m
        final boolean oldExists = moveJarToOld();
        if (javacresult.size() > 0) {
            final Set<String> entries = new HashSet<String>();
            final JarOutputStream jos = new JarOutputStream(
                    new BufferedOutputStream(new FileOutputStream(JARFILE)), getManifest());

            try {
                for (final String key : javacresult.keySet()) {
                    entries.add(key);
                    byte[] bytecode = javacresult.get(key);

                    // create entry for directory (required for classpath scanning)
                    if (key.contains("/")) {
                        String dir = key.substring(0, key.lastIndexOf('/') + 1);
                        if (!entries.contains(dir)) {
                            entries.add(dir);
                            jos.putNextEntry(new JarEntry(dir));
                            jos.closeEntry();
                        }
                    }

                    // call postCompile() (weaving) on compiled sources
                    for (CodeGenerator generator : generators) {
                        if (!oldExists || generator.isRecompileNecessary()) {
                            for (JavaSourceAsString src : generator.getSourceFiles()) {
                                final String name = src.getFQName();
                                if (key.startsWith(name.replaceAll("\\.", "/"))) {
                                    LOG.debug("postCompile (weaving) " + key);
                                    bytecode = generator.postCompile(key, bytecode);
                                    // Can we break here???
                                    // break outer;
                                }
                            }
                        }
                    }
                    jos.putNextEntry(new ZipEntry(key));
                    LOG.debug("writing to " + key + " to jar " + JARFILE);
                    jos.write(bytecode);
                    jos.closeEntry();
                }

                if (oldExists) {
                    final JarInputStream in = new JarInputStream(
                            new BufferedInputStream(new FileInputStream(JARFILE_OLD)));
                    final byte[] buffer = new byte[2048];
                    try {
                        int size;
                        JarEntry entry;
                        while ((entry = in.getNextJarEntry()) != null) {
                            if (!entries.contains(entry.getName())) {
                                jos.putNextEntry(entry);
                                LOG.debug("copying " + entry.getName() + " from old jar " + JARFILE_OLD);
                                while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                                    jos.write(buffer, 0, size);
                                }
                                jos.closeEntry();
                            }
                            in.closeEntry();
                        }
                    } finally {
                        in.close();
                    }
                }
            } finally {
                jos.close();
            }
        }
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
}

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
 */// w w  w.  j  a va  2s .c  o m
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);
    }
}

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./* w  w  w  .ja  va2s .co 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.sourcepit.osgifier.core.packaging.Repackager.java

private void copyJarContents(JarInputStream srcJarIn, final JarOutputStream destJarOut,
        PathMatcher contentMatcher) throws IOException {
    final Set<String> processedEntires = new HashSet<String>();

    JarEntry srcEntry = srcJarIn.getNextJarEntry();
    while (srcEntry != null) {
        final String entryName = srcEntry.getName();
        if (contentMatcher.isMatch(entryName)) {
            if (processedEntires.add(entryName)) {
                destJarOut.putNextEntry(new JarEntry(srcEntry.getName()));
                IOUtils.copy(srcJarIn, destJarOut);
                destJarOut.closeEntry();
            } else {
                logger.warn("Ignored duplicate jar entry: " + entryName);
            }/*from   ww w.  j a  va2s  .  com*/
        }
        srcJarIn.closeEntry();
        srcEntry = srcJarIn.getNextJarEntry();
    }
}

From source file:org.webical.plugin.classloading.PluginClassLoader.java

/**
 * Reads in all classes in a jar file for later reference
 * @param name the full name and path of the jar file
 * @throws PluginException // ww w.j  a  v a 2  s  . co m
 */
public void readJarFile(File jarFile) throws PluginException {
    //Firstly check input
    if (jarFile == null) {
        log.error("Cannot load jar without a reference...");
        throw new PluginException("Cannot load jar without a reference...");
    }

    JarInputStream jis;
    JarEntry je;

    if (!jarFile.exists()) {
        log.error("Jar does not exist: " + jarFile.getAbsolutePath());
        throw new PluginException("Jar does not exist: " + jarFile.getAbsolutePath());
    }
    if (!jarFile.canRead()) {
        log.error("Jar is not readable: " + jarFile.getAbsolutePath());
        throw new PluginException("Jar is not readable: " + jarFile.getAbsolutePath());
    }
    if (log.isDebugEnabled())
        log.debug("Loading jar file " + jarFile);

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(jarFile);
        jis = new JarInputStream(fis);
    } catch (IOException ioe) {
        log.error("Can't open jar file " + jarFile, ioe);
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("Could not close filehandle to: " + jarFile.getAbsolutePath(), e);
                throw new PluginException("Could not close filehandle to: " + jarFile.getAbsolutePath(), e);
            }
        }
        throw new PluginException("Can't open jar file " + jarFile, ioe);
    }

    //Loop over the jarfile entries
    try {
        while ((je = jis.getNextJarEntry()) != null) {
            String jarEntryName = je.getName();
            //Skip the META-INF dir
            if (jarEntryName.startsWith(META_INF)) {
                continue;
            }

            if (jarEntryName.endsWith(FileUtils.CLASS_FILE_EXTENSION)) {
                //Extract java class
                loadClassBytes(jis, ClassUtils.fileToFullClassName(jarEntryName));
            } else if (je.isDirectory()) {
                //Extract directory
                unpackDirectory(jarEntryName, jarFile);
            } else {
                //it could be an image or audio file so let's extract it and store it somewhere for later reference
                try {
                    extractJarResource(jis, jarEntryName, jarFile);
                } catch (Exception e) {
                    log.error("Cannot cache jar resource: " + jarEntryName + " from jar file: "
                            + jarFile.getAbsolutePath(), e);
                    throw new PluginException("Cannot cache jar resource: " + jarEntryName + " from jar file: "
                            + jarFile.getAbsolutePath(), e);
                }
            }
            jis.closeEntry();
        }
    } catch (IOException ioe) {
        log.error("Badly formatted jar file: " + jarFile.getAbsolutePath(), ioe);
        throw new PluginException("Badly formatted jar file: " + jarFile.getAbsolutePath(), ioe);
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (IOException e) {
                log.error("Could not close connection to jar: " + jarFile.getAbsolutePath(), e);
                throw new PluginException("Could not close connection to jar: " + jarFile.getAbsolutePath(), e);
            }
        }
    }
}

From source file:org.xwiki.tool.packager.PackageMojo.java

private void generateConfigurationFiles(File configurationFileTargetDirectory) throws MojoExecutionException {
    VelocityContext context = createVelocityContext();
    Artifact configurationResourcesArtifact = this.factory.createArtifact("org.xwiki.platform",
            "xwiki-platform-tool-configuration-resources", this.project.getVersion(), "", "jar");
    resolveArtifact(configurationResourcesArtifact);

    configurationFileTargetDirectory.mkdirs();

    try {/* www . ja  v a 2  s .c om*/
        JarInputStream jarInputStream = new JarInputStream(
                new FileInputStream(configurationResourcesArtifact.getFile()));
        JarEntry entry;
        while ((entry = jarInputStream.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".vm")) {

                String fileName = entry.getName().replace(".vm", "");
                File outputFile = new File(configurationFileTargetDirectory, fileName);
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile));
                getLog().info("Writing config file: " + outputFile);
                // Note: Init is done once even if this method is called several times...
                Velocity.init();
                Velocity.evaluate(context, writer, "", IOUtils.toString(jarInputStream));
                writer.close();
                jarInputStream.closeEntry();
            }
        }
        // Flush and close all the streams
        jarInputStream.close();
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to extract configuration files", e);
    }
}