Example usage for java.util.jar JarInputStream getManifest

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

Introduction

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

Prototype

public Manifest getManifest() 

Source Link

Document

Returns the Manifest for this JAR file, or null if none.

Usage

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

/**
 * @param scanJarsAtDir/* ww w.  j  a  v a 2  s  . c om*/
 * @return A Map(featureId -> featureVersion)
 */
public Map<String, String> scanFeatureVersionsAtDir(final String scanJarsAtDir) {
    final Map<String, String> featureVersions = new LinkedHashMap<String, String>();

    final File file = new File(scanJarsAtDir);
    if (!file.exists() || !file.isDirectory()) {
        log.error("Directory '" + file.getAbsolutePath() + "' does not exists.");
        return featureVersions;
    }

    for (final File jar : file.listFiles()) {
        if (jar.isFile() && jar.getName().toLowerCase().endsWith(".jar")) {
            try {
                final JarInputStream jarStream = new JarInputStream(
                        new BufferedInputStream(new FileInputStream(jar)));
                final Manifest manifest = jarStream.getManifest();
                final String featureId = manifest.getMainAttributes().getValue("FeatureBuilder-FeatureId");
                final String featureVersion = manifest.getMainAttributes()
                        .getValue("FeatureBuilder-FeatureVersion");

                if (featureId != null && featureVersion != null) {
                    featureVersions.put(featureId, featureVersion);
                }

            } catch (final FileNotFoundException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            } catch (final IOException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            }
        }
    }
    return featureVersions;
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

public List<Bundle> scanBundlesAtDir(final String scanJarsAtDir) {
    final File file = new File(scanJarsAtDir);

    final LinkedList<Bundle> bundles = new LinkedList<Bundle>();

    if (!file.exists() || !file.isDirectory()) {
        log.error("Directory '" + file.getAbsolutePath() + "' does not exists.");
        return bundles;
    }/*from  w w  w .java2  s  .c o m*/

    for (final File jar : file.listFiles()) {
        if (jar.isFile() && jar.getName().toLowerCase().endsWith(".jar")) {
            try {
                final JarInputStream jarStream = new JarInputStream(
                        new BufferedInputStream(new FileInputStream(jar)));
                final Manifest manifest = jarStream.getManifest();
                String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                final String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (symbolicName != null && version != null) {
                    symbolicName = symbolicName.split(";")[0].trim();
                    final Bundle bundle = new Bundle(symbolicName, version, jar.length(), jar);
                    bundles.add(bundle);
                } else {
                    log.warn("jar '" + jar.getAbsolutePath() + "' is not an OSGi bundle.");
                }

            } catch (final FileNotFoundException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            } catch (final IOException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            }

        }
    }
    log.info("Found " + bundles.size() + " bundles in scanned directory: " + file.getAbsolutePath());

    Collections.sort(bundles);
    return bundles;
}

From source file:org.jenkins.tools.test.PluginCompatTester.java

/**
 * Scans through a WAR file, accumulating plugin information
 * @param war WAR to scan/*from  ww  w  .  j a v  a 2  s.  c  o  m*/
 * @param pluginGroupIds Map pluginName to groupId if set in the manifest, MUTATED IN THE EXECUTION
 * @return Update center data
 * @throws IOException
 */
private UpdateSite.Data scanWAR(File war, Map<String, String> pluginGroupIds) throws IOException {
    JSONObject top = new JSONObject();
    top.put("id", DEFAULT_SOURCE_ID);
    JSONObject plugins = new JSONObject();
    JarFile jf = new JarFile(war);
    if (pluginGroupIds == null) {
        pluginGroupIds = new HashMap<String, String>();
    }
    try {
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            Matcher m = Pattern.compile("WEB-INF/lib/jenkins-core-([0-9.]+(?:-[0-9.]+)?(?:-SNAPSHOT)?)[.]jar")
                    .matcher(name);
            if (m.matches()) {
                if (top.has("core")) {
                    throw new IOException(">1 jenkins-core.jar in " + war);
                }
                top.put("core", new JSONObject().accumulate("name", "core").accumulate("version", m.group(1))
                        .accumulate("url", ""));
            }
            m = Pattern.compile("WEB-INF/(?:optional-)?plugins/([^/.]+)[.][hj]pi").matcher(name);
            if (m.matches()) {
                JSONObject plugin = new JSONObject().accumulate("url", "");
                InputStream is = jf.getInputStream(entry);
                try {
                    JarInputStream jis = new JarInputStream(is);
                    try {
                        Manifest manifest = jis.getManifest();
                        String shortName = manifest.getMainAttributes().getValue("Short-Name");
                        if (shortName == null) {
                            shortName = manifest.getMainAttributes().getValue("Extension-Name");
                            if (shortName == null) {
                                shortName = m.group(1);
                            }
                        }
                        plugin.put("name", shortName);
                        pluginGroupIds.put(shortName, manifest.getMainAttributes().getValue("Group-Id"));
                        plugin.put("version", manifest.getMainAttributes().getValue("Plugin-Version"));
                        plugin.put("url", "jar:" + war.toURI() + "!/" + name);
                        JSONArray dependenciesA = new JSONArray();
                        String dependencies = manifest.getMainAttributes().getValue("Plugin-Dependencies");
                        if (dependencies != null) {
                            // e.g. matrix-auth:1.0.2;resolution:=optional,credentials:1.8.3;resolution:=optional
                            for (String pair : dependencies.replace(";resolution:=optional", "").split(",")) {
                                String[] nameVer = pair.split(":");
                                assert nameVer.length == 2;
                                dependenciesA.add(new JSONObject().accumulate("name", nameVer[0])
                                        .accumulate("version", nameVer[1])
                                        ./* we do care about even optional deps here */accumulate("optional",
                                                "false"));
                            }
                        }
                        plugin.accumulate("dependencies", dependenciesA);
                        plugins.put(shortName, plugin);
                    } finally {
                        jis.close();
                    }
                } finally {
                    is.close();
                }
            }
        }
    } finally {
        jf.close();
    }
    top.put("plugins", plugins);
    if (!top.has("core")) {
        throw new IOException("no jenkins-core.jar in " + war);
    }
    System.out.println("Scanned contents of " + war + ": " + top);
    return newUpdateSiteData(new UpdateSite(DEFAULT_SOURCE_ID, null), top);
}

From source file:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java

/**
 * //ww w.j a  va 2s  .co m
 * create one default index bean which based one the component zip file directly.
 * 
 * bundleId, version, mvn_uri are required
 */
public ComponentIndexBean create(File componentZipFile) {
    if (componentZipFile == null || !componentZipFile.exists() || componentZipFile.isDirectory()
            || !componentZipFile.getName().endsWith(FileExtensions.ZIP_FILE_SUFFIX)) {
        return null;
    }

    String name = null;
    String bundleId = null;
    String bundleVersion = null;
    String mvnUri = null;

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(componentZipFile);

        Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries();
        while (enumeration.hasMoreElements()) {
            final ZipEntry zipEntry = enumeration.nextElement();
            String path = zipEntry.getName();
            if (path.endsWith(FileExtensions.JAR_FILE_SUFFIX)) { // is jar
                // if it's bundle, not from other folder, like lib, m2 repository.
                IPath p = new Path(path);
                // must be in plugins
                if (p.segmentCount() > 1
                        && p.removeLastSegments(1).lastSegment().equals(UpdatesHelper.FOLDER_PLUGINS)) {
                    if (UpdatesHelper.isComponentJar(zipFile.getInputStream(zipEntry))) {
                        JarInputStream jarEntryStream = null;
                        try {
                            // must use another stream
                            jarEntryStream = new JarInputStream(zipFile.getInputStream(zipEntry));
                            // find the bundleId and version
                            Manifest manifest = jarEntryStream.getManifest();
                            if (manifest != null) {
                                bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                            }
                            boolean checkManifest = StringUtils.isBlank(bundleId)
                                    || StringUtils.isBlank(bundleVersion);

                            // find the pom.properties
                            JarEntry jarEntry = null;
                            while ((jarEntry = jarEntryStream.getNextJarEntry()) != null) {
                                final String entryPath = jarEntry.getName();
                                if (checkManifest && JarFile.MANIFEST_NAME.equalsIgnoreCase(entryPath)) {
                                    manifest = new Manifest();
                                    manifest.read(jarEntryStream);
                                    bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                    bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                                    checkManifest = false;
                                }
                                final Path fullPath = new Path(entryPath);
                                final String fileName = fullPath.lastSegment();

                                /*
                                 * for example,
                                 * META-INF/maven/org.talend.components/components-splunk/pom.properties
                                 */
                                if (fileName.equals("pom.properties") //$NON-NLS-1$
                                        && entryPath.contains("META-INF/maven/")) { //$NON-NLS-1$

                                    // FIXME, didn't find one way to read the inner jar
                                    // final InputStream propStream = jarFile.getInputStream(jarEntry);
                                    // if (propStream != null) {
                                    // Properties pomProp = new Properties();
                                    // pomProp.load(propStream);
                                    //
                                    // String version = pomProp.getProperty("version"); //$NON-NLS-1$
                                    // String groupId = pomProp.getProperty("groupId"); //$NON-NLS-1$
                                    // String artifactId = pomProp.getProperty("artifactId"); //$NON-NLS-1$
                                    // mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, version,
                                    // FileExtensions.ZIP_FILE_SUFFIX, null);
                                    //
                                    // propStream.close();
                                    // }

                                    // FIXME, try the path way
                                    // META-INF/maven/org.talend.components/components-splunk
                                    IPath tmpMavenPath = fullPath.removeLastSegments(1);
                                    String artifactId = tmpMavenPath.lastSegment(); // components-splunk
                                    // META-INF/maven/org.talend.components
                                    tmpMavenPath = tmpMavenPath.removeLastSegments(1);
                                    String groupId = tmpMavenPath.lastSegment(); // org.talend.components

                                    mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, bundleVersion,
                                            FileExtensions.ZIP_EXTENSION, null);

                                } else
                                /*
                                 * /OSGI-INF/installer$$splunk.xml
                                 */
                                if (fileName.endsWith(FileExtensions.XML_FILE_SUFFIX)
                                        && fileName.startsWith(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                        && entryPath.contains(UpdatesHelper.FOLDER_OSGI_INF + '/')) {
                                    name = fullPath.removeFileExtension().lastSegment();
                                    name = name.substring(name.indexOf(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                            + UpdatesHelper.NEW_COMPONENT_PREFIX.length());
                                }
                            }
                        } catch (IOException e) {
                            //
                        } finally {
                            try {
                                if (jarEntryStream != null) {
                                    jarEntryStream.close();
                                }
                            } catch (IOException e) {
                                //
                            }
                        }

                    }
                }
            }
        }

    } catch (ZipException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } catch (IOException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                //
            }
        }
    }
    // set the required
    if (name != null && bundleId != null && bundleVersion != null && mvnUri != null) {
        final ComponentIndexBean indexBean = new ComponentIndexBean();
        final boolean set = indexBean.setRequiredFieldsValue(name, bundleId, bundleVersion, mvnUri);
        indexBean.setValue(ComponentIndexNames.types,
                PathUtils.convert2StringTypes(Arrays.asList(Type.TCOMP_V0)));
        if (set) {
            return indexBean;
        }
    }
    return null;
}

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 {// ww  w . ja  v  a2  s .c o  m
            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.artifactory.repo.db.DbStoringRepoMixin.java

private void validateArtifactIfRequired(MutableVfsFile mutableFile, RepoPath repoPath)
        throws RepoRejectException {
    String pathId = repoPath.getId();
    InputStream jarStream = mutableFile.getStream();
    try {/* ww  w. j  a v  a 2 s .co  m*/
        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:JarUtils.java

public static void unjar(InputStream in, File dest) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();//w w  w  . j a v a  2s .c o  m
    }
    if (!dest.isDirectory()) {
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(in);
    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();
            out.close();
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    /* Explicity write out the META-INF/MANIFEST.MF so that any headers such
    as the Class-Path are see for the unpackaged jar
    */
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (parent.exists() == false) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        out.close();
    }
    jin.close();
}

From source file:org.jahia.utils.maven.plugin.osgi.BuildFrameworkPackageListMojo.java

private void scanJar(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts, File jarFile,
        String defaultVersion) throws IOException {
    JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
    Manifest jarManifest = jarInputStream.getManifest();
    // Map<String, String> manifestVersions = new HashMap<String,String>();
    String specificationVersion = null;
    if (jarManifest == null) {
        getLog().warn("No MANIFEST.MF file found for dependency " + jarFile);
    } else {//from ww  w  . j av  a2s.  c om
        if (jarManifest.getMainAttributes() == null) {
            getLog().warn("No main attributes found in MANIFEST.MF file found for dependency " + jarFile);
        } else {
            specificationVersion = jarManifest.getMainAttributes().getValue("Specification-Version");
            if (defaultVersion == null) {
                if (jarManifest.getMainAttributes().getValue("Bundle-Version") != null) {
                } else if (specificationVersion != null) {
                    defaultVersion = specificationVersion;
                } else {
                    defaultVersion = jarManifest.getMainAttributes().getValue("Implementation-Version");
                }
            }
            String exportPackageHeaderValue = jarManifest.getMainAttributes().getValue("Export-Package");
            if (exportPackageHeaderValue != null) {
                ManifestElement[] manifestElements = new ManifestElement[0];
                try {
                    manifestElements = ManifestElement.parseHeader("Export-Package", exportPackageHeaderValue);
                } catch (BundleException e) {
                    getLog().warn("Error while parsing Export-Package header value for jar " + jarFile, e);
                }
                for (ManifestElement manifestElement : manifestElements) {
                    String[] packageNames = manifestElement.getValueComponents();
                    String version = manifestElement.getAttribute("version");
                    for (String packageName : packageNames) {
                        updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), version,
                                version, packageName);
                    }
                }
            }
            for (Map.Entry<String, Attributes> manifestEntries : jarManifest.getEntries().entrySet()) {
                String packageName = manifestEntries.getKey().replaceAll("/", ".");
                if (packageName.endsWith(".class")) {
                    continue;
                }
                if (packageName.endsWith(".")) {
                    packageName = packageName.substring(0, packageName.length() - 1);
                }
                if (packageName.endsWith(".*")) {
                    packageName = packageName.substring(0, packageName.length() - 1);
                }
                int lastDotPos = packageName.lastIndexOf(".");
                String lastPackage = packageName;
                if (lastDotPos > -1) {
                    lastPackage = packageName.substring(lastDotPos + 1);
                }
                if (lastPackage.length() > 0 && Character.isUpperCase(lastPackage.charAt(0))) {
                    // ignore non package version
                    continue;
                }
                if (StringUtils.isEmpty(packageName) || packageName.startsWith("META-INF")
                        || packageName.startsWith("OSGI-INF") || packageName.startsWith("OSGI-OPT")
                        || packageName.startsWith("WEB-INF") || packageName.startsWith("org.osgi")) {
                    // ignore private package names
                    continue;
                }
                String packageVersion = null;
                if (manifestEntries.getValue().getValue("Specification-Version") != null) {
                    packageVersion = manifestEntries.getValue().getValue("Specification-Version");
                } else {
                    packageVersion = manifestEntries.getValue().getValue("Implementation-Version");
                }
                if (packageVersion != null) {
                    getLog().info("Found package version in " + jarFile.getName() + " MANIFEST : " + packageName
                            + " v" + packageVersion);
                    updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(),
                            packageVersion, specificationVersion, packageName);
                    // manifestVersions.put(packageName, packageVersion);
                }
            }
        }
    }
    JarEntry jarEntry = null;
    // getLog().debug("Processing file " + artifact.getFile() + "...");
    while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
        if (!jarEntry.isDirectory()) {
            String entryName = jarEntry.getName();
            String entryPackage = "";
            int lastSlash = entryName.lastIndexOf("/");
            if (lastSlash > -1) {
                entryPackage = entryName.substring(0, lastSlash);
                entryPackage = entryPackage.replaceAll("/", ".");
                if (StringUtils.isNotEmpty(entryPackage) && !entryPackage.startsWith("META-INF")
                        && !entryPackage.startsWith("OSGI-INF") && !entryPackage.startsWith("OSGI-OPT")
                        && !entryPackage.startsWith("WEB-INF") && !entryPackage.startsWith("org.osgi")) {
                    updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(),
                            defaultVersion, specificationVersion, entryPackage);
                }
            }
        }
    }
    jarInputStream.close();
}

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

/**
 * Unpack the given jar file.//from w  w w .  j  av  a  2 s  .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.hyperic.hq.product.server.session.PluginManagerImpl.java

private File getFileAndValidateJar(String filename, byte[] bytes) throws PluginDeployException {
    ByteArrayInputStream bais = null;
    JarInputStream jis = null;
    FileOutputStream fos = null;//w ww  .j a  va 2s .c  o m
    String file = null;
    try {
        bais = new ByteArrayInputStream(bytes);
        jis = new JarInputStream(bais);
        final Manifest manifest = jis.getManifest();
        if (manifest == null) {
            throw new PluginDeployException("plugin.manager.jar.manifest.does.not.exist", filename);
        }
        file = TMP_DIR + File.separator + filename;
        fos = new FileOutputStream(file);
        fos.write(bytes);
        fos.flush();
        final File rtn = new File(file);
        final URL url = new URL("jar", "", "file:" + file + "!/");
        final JarURLConnection jarConn = (JarURLConnection) url.openConnection();
        final JarFile jarFile = jarConn.getJarFile();
        processJarEntries(jarFile, file, filename);
        return rtn;
    } catch (IOException e) {
        final File toRemove = new File(file);
        if (toRemove != null && toRemove.exists()) {
            toRemove.delete();
        }
        throw new PluginDeployException("plugin.manager.file.ioexception", e, filename);
    } finally {
        close(jis);
        close(fos);
    }
}