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.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

/**
 * Fetch all the entries in the given (jar) input stream and look for the
 * plugin directory./*from  w w w  .ja  v  a 2 s.c o  m*/
 *
 * @param is the input stream to analyse
 */
private Set<String> discoverJarPlugin(InputStream is) {
    Set<String> plugins = new HashSet<String>();
    if (null == is) {
        return plugins;
    }
    JarEntry je = null;
    try {
        JarInputStream jis = new JarInputStream(is);
        do {
            je = jis.getNextJarEntry();
            if (null != je) {
                String URL = je.toString();
                if (URL.contains(PLUGIN_DIRECTORY) && URL.endsWith(PLUGIN_APSADMIN_PATH)) {
                    plugins.add(URL);
                }
            }
        } while (je != null);
    } catch (Throwable t) {
        _logger.error("error in discoverJarPlugin", t);
        //ApsSystemUtils.logThrowable(t, this, "discoverJarPlugin");
    }
    return plugins;
}

From source file:streamflow.service.TopologyService.java

private void embedFrameworkResources(JarBuilder jarBuilder, byte[] frameworkJar) {
    JarEntry jarEntry;/*from  w  ww  .  ja  v  a 2  s  .c  om*/
    JarInputStream jarInputStream;

    try {
        jarInputStream = new JarInputStream(new ByteArrayInputStream(frameworkJar));

        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            // A resource file is defined as a non *.class file that is a real file
            if (!jarEntry.isDirectory() && !jarEntry.getName().endsWith(".class")) {
                // Ignore the resource files in the META-INF folder
                if (!jarEntry.getName().startsWith("META-INF")
                        && !jarEntry.getName().startsWith("STREAMFLOW-INF")) {
                    // Create the handle to the target resource file in the topology jar
                    if (!jarBuilder.addFile(jarEntry.getName(), IOUtils.toByteArray(jarInputStream))) {
                        LOG.error("Error occurred while writing a framework resource to the topology jar: "
                                + jarEntry.getName());
                    }
                }
            }
        }
    } catch (IOException ex) {
        LOG.error("Exception while embedding framework resource: " + ex.getMessage());
    }
}

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

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {//w  w  w . ja  v a 2  s  .  c o  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.artifactory.repo.db.DbStoringRepoMixin.java

private void validateArtifactIfRequired(MutableVfsFile mutableFile, RepoPath repoPath)
        throws RepoRejectException {
    String pathId = repoPath.getId();
    InputStream jarStream = mutableFile.getStream();
    try {/*from   w  ww  .  j a va  2  s. c om*/
        log.info("Validating the content of '{}'.", pathId);
        JarInputStream jarInputStream = new JarInputStream(jarStream, true);
        JarEntry entry = jarInputStream.getNextJarEntry();

        if (entry == null) {
            if (jarInputStream.getManifest() != null) {
                log.trace("Found manifest validating the content of '{}'.", pathId);
                return;
            }
            throw new IllegalStateException("Could not find entries within the archive.");
        }
        do {
            log.trace("Found the entry '{}' validating the content of '{}'.", entry.getName(), pathId);
        } while ((jarInputStream.available() == 1) && (entry = jarInputStream.getNextJarEntry()) != null);

        log.info("Finished validating the content of '{}'.", pathId);
    } catch (Exception e) {
        String message = String.format("Failed to validate the content of '%s': %s", pathId, e.getMessage());
        if (log.isDebugEnabled()) {
            log.debug(message, e);
        } else {
            log.error(message);
        }
        throw new RepoRejectException(message, HttpStatus.SC_CONFLICT);
    } finally {
        IOUtils.closeQuietly(jarStream);
    }
}

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 {//from   w  w w. j a v a2 s. c  o  m
        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);
    }
}

From source file:org.hecl.jarhack.JarHack.java

/**
 * The <code>substHecl</code> method takes the filenames of two
 * .jar's - one as input, the second as output, in addition to the
 * name of the application.  Where it counts, the old name (Hecl,
 * usually) is overridden with the new name, and the new .jar file
 * is written to the specified outfile.  Via the iconname argument
 * it is also possible to specify a new icon file to use.
 *
 * @param infile a <code>FileInputStream</code> value
 * @param outfile a <code>String</code> value
 * @param newname a <code>String</code> value
 * @param iconname a <code>String</code> value
 * @exception IOException if an error occurs
 *///  w  ww. ja v  a 2 s.c o m
public static void substHecl(InputStream infile, String outfile, String newname, String iconname,
        String scriptfile) throws IOException {

    JarInputStream jif = new JarInputStream(infile);
    Manifest mf = jif.getManifest();
    Attributes attrs = mf.getMainAttributes();

    Set keys = attrs.keySet();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
        Object key = it.next();
        Object value = attrs.get(key);
        String keyname = key.toString();

        /* These are the three cases that interest us in
         * particular, where we need to make changes. */
        if (keyname.equals("MIDlet-Name")) {
            attrs.putValue(keyname, newname);
        } else if (keyname.equals("MIDlet-1")) {
            String valuestr = value.toString();
            /* FIXME - the stringsplit method is used for older
             * versions of GCJ.  Once newer versions are common,
             * it can go away.  Or not - it works just fine. */
            String properties[] = stringsplit(valuestr, ", ");
            attrs.putValue(keyname, newname + ", " + properties[1] + ", " + properties[2]);
        } else if (keyname.equals("MicroEdition-Configuration")) {
            cldcversion = value.toString();
        } else if (keyname.equals("MicroEdition-Profile")) {
            midpversion = value.toString();
        } else if (keyname.equals("MIDlet-Jar-URL")) {
            attrs.put(key, newname + ".jar");
        }
    }

    JarOutputStream jof = new JarOutputStream(new FileOutputStream(outfile), mf);

    byte[] buf = new byte[4096];

    /* Go through the various entries. */
    JarEntry entry;
    int read;
    while ((entry = jif.getNextJarEntry()) != null) {

        /* Don't copy the manifest file. */
        if ("META-INF/MANIFEST.MF".equals(entry.getName()))
            continue;

        /* Insert our own icon */
        if (iconname != null && "Hecl.png".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("Hecl.png"));
            FileInputStream inf = new FileInputStream(iconname);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        }
        /* Insert our own copy of the script file. */
        else if ("script.hcl".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("script.hcl"));
            FileInputStream inf = new FileInputStream(scriptfile);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        } else {
            /* Otherwise, just copy the entry. */
            jof.putNextEntry(entry);
            while ((read = jif.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
        }

        jof.closeEntry();
    }

    jof.flush();
    jof.close();
    jif.close();
}

From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java

private List<String> jar(JarInputStream jarStream) throws IOException {
    List<String> classNames = new ArrayList<String>();

    JarEntry entry;//from   w  w w  .j av a2 s.c  o  m
    while ((entry = jarStream.getNextJarEntry()) != null) {
        if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
            continue;
        }
        String className = entry.getName();
        className = className.replaceFirst(".class$", "");

        //war files are treated as .jar files, so takeout WEB-INF/classes
        className = StringUtils.removeStart(className, "WEB-INF/classes/");

        className = className.replace('/', '.');
        classNames.add(className);
    }

    return classNames;
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java

/**
 * Change the version in jar/* www . j  a v a2 s . c  om*/
 * 
 * @param newVersion
 * @param file
 * @return
 * @throws MojoExecutionException
 */
protected File changeVersion(File file, String oldVersion, String newVersion) throws MojoExecutionException {
    String fileName = file.getName();
    int pos = fileName.indexOf(oldVersion);
    fileName = fileName.substring(0, pos) + newVersion + fileName.substring(pos + oldVersion.length());

    JarInputStream jis = null;
    JarOutputStream jos;
    OutputStream out = null;
    JarFile sourceJar = null;
    try {
        // now create a temporary file and update the version
        sourceJar = new JarFile(file);
        final Manifest manifest = sourceJar.getManifest();
        manifest.getMainAttributes().putValue("Bundle-Version", newVersion);

        jis = new JarInputStream(new FileInputStream(file));
        final File destJar = new File(file.getParentFile(), fileName);
        out = new FileOutputStream(destJar);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                IOUtils.copy(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();
        return destJar;
    } catch (IOException ioe) {
        throw new MojoExecutionException("Unable to update version in jar file.", ioe);
    } finally {
        if (sourceJar != null) {
            try {
                sourceJar.close();
            } catch (IOException ex) {
                // close
            }
        }
        IOUtils.closeQuietly(jis);
        IOUtils.closeQuietly(out);
    }

}

From source file:org.exist.repo.Deployment.java

public DocumentImpl getDescriptor(File jar) throws IOException, PackageException {
    final InputStream istream = new BufferedInputStream(new FileInputStream(jar));
    final JarInputStream jis = new JarInputStream(istream);
    JarEntry entry;//  ww  w.  ja v  a 2s  .  co  m
    DocumentImpl doc = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory() && "expath-pkg.xml".equals(entry.getName())) {
            final ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int c;
            final byte[] b = new byte[4096];
            while ((c = jis.read(b)) > 0) {
                bos.write(b, 0, c);
            }

            bos.close();

            final byte[] data = bos.toByteArray();

            final ByteArrayInputStream bis = new ByteArrayInputStream(data);
            try {
                doc = DocUtils.parse(broker.getBrokerPool(), null, bis);
            } catch (final XPathException e) {
                throw new PackageException("Error while parsing expath-pkg.xml: " + e.getMessage(), e);
            }
            break;
        }
    }
    jis.close();
    return doc;
}

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

private List<PaletteElementInfo> extractElementsFromJarAllClasses(JarInputStream jarStream) throws Exception {
    // load all classes
    List<PaletteElementInfo> elements = Lists.newArrayList();
    try {//w w w.j av  a  2 s .co  m
        while (true) {
            JarEntry jarEntry = jarStream.getNextJarEntry();
            if (jarEntry == null) {
                break;
            }
            String jarEntryName = jarEntry.getName();
            if (jarEntryName.endsWith(JAVA_BEAN_CLASS_SUFFIX)) {
                // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc'
                PaletteElementInfo element = new PaletteElementInfo();
                element.className = StringUtils.substringBeforeLast(jarEntryName, JAVA_BEAN_CLASS_SUFFIX)
                        .replace('/', '.');
                element.name = CodeUtils.getShortClass(element.className);
                elements.add(element);
            }
        }
    } catch (Throwable e) {
        DesignerPlugin.log(e);
    }
    // sort element over class name
    Collections.sort(elements, new Comparator<PaletteElementInfo>() {
        public int compare(PaletteElementInfo element0, PaletteElementInfo element1) {
            return element0.className.compareToIgnoreCase(element1.className);
        }
    });
    return elements;
}