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:JarUtils.java

public static void unjar(InputStream in, File dest) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();/*from   w w  w . j ava 2s  . c om*/
    }
    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:com.speed.ob.api.ClassStore.java

public void dump(File in, File out, Config config) throws IOException {
    if (in.isDirectory()) {
        for (ClassNode node : nodes()) {
            String[] parts = node.name.split("\\.");
            String dirName = node.name.substring(0, node.name.lastIndexOf("."));
            dirName = dirName.replace(".", "/");
            File dir = new File(out, dirName);
            if (!dir.exists()) {
                if (!dir.mkdirs())
                    throw new IOException("Could not make output dir: " + dir.getAbsolutePath());
            }//from ww w .j a va2 s  . co m
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            FileOutputStream fOut = new FileOutputStream(
                    new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1)));
            fOut.write(data);
            fOut.flush();
            fOut.close();
        }
    } else if (in.getName().endsWith(".jar")) {
        File output = new File(out, in.getName());
        JarFile jf = new JarFile(in);
        HashMap<JarEntry, Object> existingData = new HashMap<>();
        if (output.exists()) {
            try {
                JarInputStream jarIn = new JarInputStream(new FileInputStream(output));
                JarEntry entry;
                while ((entry = jarIn.getNextJarEntry()) != null) {
                    if (!entry.isDirectory()) {
                        byte[] data = IOUtils.toByteArray(jarIn);
                        existingData.put(entry, data);
                        jarIn.closeEntry();
                    }
                }
                jarIn.close();
            } catch (IOException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Could not read existing output file, overwriting", e);
            }
        }
        FileOutputStream fout = new FileOutputStream(output);
        Manifest manifest = null;
        if (jf.getManifest() != null) {
            manifest = jf.getManifest();
            if (!config.getBoolean("ClassNameTransform.keep_packages")
                    && config.getBoolean("ClassNameTransform.exclude_mains")) {
                manifest = new Manifest(manifest);
                if (manifest.getMainAttributes().getValue("Main-Class") != null) {
                    String manifestName = manifest.getMainAttributes().getValue("Main-Class");
                    if (manifestName.contains(".")) {
                        manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1);
                        manifest.getMainAttributes().putValue("Main-Class", manifestName);
                    }
                }
            }
        }
        jf.close();
        JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout)
                : new JarOutputStream(fout, manifest);
        Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files");
        if (!existingData.isEmpty()) {
            for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) {
                Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName());
                jarOut.putNextEntry(entry.getKey());
                jarOut.write((byte[]) entry.getValue());
                jarOut.closeEntry();
            }
        }
        for (ClassNode node : nodes()) {
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            int index = node.name.lastIndexOf("/");
            String fileName;
            if (index > 0) {
                fileName = node.name.substring(0, index + 1).replace(".", "/");
                fileName += node.name.substring(index + 1).concat(".class");
            } else {
                fileName = node.name.concat(".class");
            }
            JarEntry entry = new JarEntry(fileName);
            jarOut.putNextEntry(entry);
            jarOut.write(data);
            jarOut.closeEntry();
        }
        jarOut.close();
    } else {
        if (nodes().size() == 1) {
            File outputFile = new File(out, in.getName());
            ClassNode node = nodes().iterator().next();
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            byte[] data = writer.toByteArray();
            FileOutputStream stream = new FileOutputStream(outputFile);
            stream.write(data);
            stream.close();
        }
    }
}

From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java

private String getShortDescription(JarInputStream jis) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(jis));
    StringBuffer sb = new StringBuffer();
    boolean first = true;
    while (true) {
        String line = reader.readLine();
        if (line == null || !StringUtils.hasText(line)) {
            break;
        }/*from  w  w w  .  j a  va2  s . com*/
        if (!first) {
            sb.append("\n\r");
        } else {
            first = false;
        }
        sb.append(line);
    }
    jis.closeEntry();
    return sb.toString();
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * @param jarFile not null/*from ww w.j  a v a 2 s .  c o m*/
 * @return all class names from the given jar file.
 * @throws IOException if any or if the jarFile is null or doesn't exist.
 */
private static List<String> getClassNamesFromJar(File jarFile) throws IOException {
    if (jarFile == null || !jarFile.exists() || !jarFile.isFile()) {
        throw new IOException("The jar '" + jarFile + "' doesn't exist or is not a file.");
    }

    List<String> classes = new ArrayList<String>();
    JarInputStream jarStream = null;

    try {
        jarStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = jarStream.getNextJarEntry();
        while (jarEntry != null) {
            if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
                String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));

                classes.add(name.replaceAll("/", "\\."));
            }

            jarStream.closeEntry();
            jarEntry = jarStream.getNextJarEntry();
        }
    } finally {
        IOUtil.close(jarStream);
    }

    return classes;
}

From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java

/**
 * Extracts the project files to the project directory.
 *//*from  www  .j a v  a 2s  .c  o m*/
private void extract(URL url) throws Exception {
    packageDirs = packageName.replaceAll("\\.", "/");
    String puTemplate = DIR_TEMPLATES + "/" + template + "/";
    int length = puTemplate.length() - 1;
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    JarInputStream jis = new JarInputStream(bis);
    JarEntry je;
    byte[] buf = new byte[1024];
    int n;
    while ((je = jis.getNextJarEntry()) != null) {
        String jarEntryName = je.getName();
        PluginLog.getLog().debug("JAR entry: " + jarEntryName);
        if (je.isDirectory() || !jarEntryName.startsWith(puTemplate)) {
            continue;
        }
        String targetFileName = projectDir + jarEntryName.substring(length);

        // convert the ${gsGroupPath} to directory
        targetFileName = StringUtils.replace(targetFileName, FILTER_GROUP_PATH, packageDirs);
        PluginLog.getLog().debug("Extracting entry " + jarEntryName + " to " + targetFileName);

        // read the bytes to the buffer
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        while ((n = jis.read(buf, 0, 1024)) > -1) {
            byteStream.write(buf, 0, n);
        }

        // replace property references with the syntax ${property_name}
        // to their respective property values.
        String data = byteStream.toString();
        data = StringUtils.replace(data, FILTER_GROUP_ID, packageName);
        data = StringUtils.replace(data, FILTER_ARTIFACT_ID, projectDir.getName());
        data = StringUtils.replace(data, FILTER_GROUP_PATH, packageDirs);

        // write the entire converted file content to the destination file.
        File f = new File(targetFileName);
        File dir = f.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileWriter writer = new FileWriter(f);
        writer.write(data);
        jis.closeEntry();
        writer.close();
    }
    jis.close();
}

From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

private void processJarFile(InputStream inputStream, String jarFilePath, JarMetadata contextJarMetadata,
        boolean processMavenPom, int level, boolean lookForNotice, boolean lookForLicense,
        boolean processingSources) throws IOException {
    // if we don't need to find either a license or notice, don't process the jar at all
    if (!lookForLicense && !lookForNotice) {
        return;//from  w ww  .  j  a  v a2  s  .  com
    }

    final String indent = getIndent(level);
    output(indent, "Processing JAR " + jarFilePath + "...", false, true);

    // JarFile realJarFile = new JarFile(jarFile);
    JarInputStream jarInputStream = new JarInputStream(inputStream);
    String bundleLicense = null;
    Manifest manifest = jarInputStream.getManifest();
    if (manifest != null && manifest.getMainAttributes() != null) {
        bundleLicense = manifest.getMainAttributes().getValue("Bundle-License");
        if (bundleLicense != null) {
            output(indent, "Found Bundle-License attribute with value:" + bundleLicense);
            KnownLicense knownLicense = getKnowLicenseByName(bundleLicense);
            // this data is not reliable, especially on the ServiceMix repackaged bundles
        }
    }
    String pomFilePath = null;
    byte[] pomByteArray = null;

    final String jarFileName = getJarFileName(jarFilePath);
    if (contextJarMetadata == null) {
        contextJarMetadata = jarDatabase.get(jarFileName);
        if (contextJarMetadata == null) {
            // compute project name
            contextJarMetadata = new JarMetadata(jarFilePath, jarFileName);
        }
        jarDatabase.put(jarFileName, contextJarMetadata);
    }

    Notice notice;
    JarEntry curJarEntry = null;
    while ((curJarEntry = jarInputStream.getNextJarEntry()) != null) {

        if (!curJarEntry.isDirectory()) {
            final String fileName = curJarEntry.getName();
            if (lookForNotice && isNotice(fileName, jarFilePath)) {

                output(indent, "Processing notice found in " + curJarEntry + "...");

                InputStream noticeInputStream = jarInputStream;
                List<String> noticeLines = IOUtils.readLines(noticeInputStream);
                notice = new Notice(noticeLines);

                Map<String, Notice> notices = contextJarMetadata.getNoticeFiles();
                if (notices == null) {
                    notices = new TreeMap<>();
                    notices.put(fileName, notice);
                    output(indent, "Found first notice " + curJarEntry);
                } else if (!notices.containsValue(notice)) {
                    output(indent, "Found additional notice " + curJarEntry);
                    notices.put(fileName, notice);
                } else {
                    output(indent, "Duplicated notice in " + curJarEntry);
                    notices.put(fileName, notice);
                    duplicatedNotices.add(jarFilePath);
                }

                // IOUtils.closeQuietly(noticeInputStream);
            } else if (processMavenPom && fileName.endsWith("pom.xml")) {
                // remember pom file path in case we need it
                pomFilePath = curJarEntry.getName();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(jarInputStream, byteArrayOutputStream);
                pomByteArray = byteArrayOutputStream.toByteArray();

            } else if (lookForLicense && isLicense(fileName, jarFilePath)) {

                output(indent, "Processing license found in " + curJarEntry + "...");
                InputStream licenseInputStream = jarInputStream;
                List<String> licenseLines = IOUtils.readLines(licenseInputStream);

                LicenseFile licenseFile = new LicenseFile(jarFilePath, fileName, jarFilePath, licenseLines);

                resolveKnownLicensesByText(licenseFile);

                if (StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText())
                        && StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText().trim())) {
                    KnownLicense knownLicense = new KnownLicense();
                    knownLicense.setId(FilenameUtils.getBaseName(jarFilePath) + "-additional-terms");
                    knownLicense
                            .setName("Additional license terms from " + FilenameUtils.getBaseName(jarFilePath));
                    List<TextVariant> textVariants = new ArrayList<>();
                    TextVariant textVariant = new TextVariant();
                    textVariant.setId("default");
                    textVariant.setDefaultVariant(true);
                    textVariant.setText(Pattern.quote(licenseFile.getAdditionalLicenseText()));
                    textVariants.add(textVariant);
                    knownLicense.setTextVariants(textVariants);
                    knownLicense.setTextToUse(licenseFile.getAdditionalLicenseText());
                    knownLicense.setViral(licenseFile.getText().toLowerCase().contains("gpl"));
                    knownLicenses.getLicenses().put(knownLicense.getId(), knownLicense);
                    licenseFile.getKnownLicenses().add(knownLicense);
                    licenseFile.getKnownLicenseKeys().add(knownLicense.getId());
                }

                for (KnownLicense knownLicense : licenseFile.getKnownLicenses()) {
                    SortedSet<LicenseFile> licenseFiles = knownLicensesFound.get(knownLicense);
                    if (licenseFiles != null) {
                        if (!licenseFiles.contains(licenseFile)) {
                            licenseFiles.add(licenseFile);
                        }
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    } else {
                        licenseFiles = new TreeSet<>();
                        licenseFiles.add(licenseFile);
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    }
                }

                Map<String, LicenseFile> licenseFiles = contextJarMetadata.getLicenseFiles();
                if (licenseFiles == null) {
                    licenseFiles = new TreeMap<>();
                }
                if (licenseFiles.containsKey(fileName)) {
                    // warning we already have a license file here, what should we do ?
                    output(indent, "License file already exists for " + jarFilePath + " will override it !",
                            true, false);
                    licenseFiles.remove(fileName);
                }
                licenseFiles.put(fileName, licenseFile);

                // IOUtils.closeQuietly(licenseInputStream);

            } else if (fileName.endsWith(".jar")) {
                InputStream embeddedJarInputStream = jarInputStream;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(embeddedJarInputStream, byteArrayOutputStream);
                final JarMetadata embeddedJarMetadata = new JarMetadata(jarFilePath, getJarFileName(fileName));

                if (embeddedJarMetadata != null) {
                    embeddedJarMetadata.setJarContents(byteArrayOutputStream.toByteArray());
                    contextJarMetadata.getEmbeddedJars().add(embeddedJarMetadata);
                }
            } else if (fileName.endsWith(".class")) {
                String className = fileName.substring(0, fileName.length() - ".class".length()).replaceAll("/",
                        ".");
                int lastPoint = className.lastIndexOf(".");
                String packageName = null;
                if (lastPoint > 0) {
                    packageName = className.substring(0, lastPoint);
                    SortedSet<String> currentJarPackages = jarDatabase
                            .get(FilenameUtils.getBaseName(jarFilePath)).getPackages();
                    if (currentJarPackages == null) {
                        currentJarPackages = new TreeSet<>();
                    }
                    currentJarPackages.add(packageName);
                }
            }

        }
        jarInputStream.closeEntry();
    }

    jarInputStream.close();
    jarInputStream = null;

    if (!contextJarMetadata.getEmbeddedJars().isEmpty()) {
        for (JarMetadata embeddedJarMetadata : contextJarMetadata.getEmbeddedJars()) {
            if (embeddedJarMetadata.getJarContents() != null) {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                        embeddedJarMetadata.getJarContents());
                processJarFile(byteArrayInputStream, contextJarMetadata.toString(), null, true, level, true,
                        true, processingSources);
            } else {
                output(indent, "Couldn't find dependency for embedded JAR " + contextJarMetadata, true, false);
            }
        }
    }

    if (processMavenPom) {
        if (pomFilePath == null) {
            output(indent, "No POM found in " + jarFilePath);
        } else {
            output(indent, "Processing POM found at " + pomFilePath + " in " + jarFilePath + "...");
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pomByteArray);
            processJarPOM(byteArrayInputStream, pomFilePath, jarFilePath, contextJarMetadata, lookForNotice,
                    lookForLicense, contextJarMetadata.getEmbeddedJars(), level + 1, processingSources);
        }
    }

    if (lookForLicense || lookForNotice) {
        if (lookForLicense) {
            output(indent, "No license found in " + jarFilePath);
        }
        if (lookForNotice) {
            output(indent, "No notice found in " + jarFilePath);
        }

        if (pomFilePath == null && lookForLicense && lookForNotice) {
            if (StringUtils.isBlank(contextJarMetadata.getVersion())) {
                output(indent, "Couldn't resolve version for JAR " + contextJarMetadata
                        + ", can't query Maven Central repository without version !");
            } else {
                List<Artifact> mavenCentralArtifacts = findArtifactInMavenCentral(contextJarMetadata.getName(),
                        contextJarMetadata.getVersion(), contextJarMetadata.getClassifier());
                if (mavenCentralArtifacts != null && mavenCentralArtifacts.size() == 1) {
                    Artifact mavenCentralArtifact = mavenCentralArtifacts.get(0);
                    Artifact resolvedArtifact = resolveArtifact(mavenCentralArtifact, level);
                    if (resolvedArtifact != null) {
                        // we have a copy of the local artifact, let's request the sources for it.
                        if (!processingSources && !"sources".equals(contextJarMetadata.getClassifier())) {
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), "sources", "jar",
                                    resolvedArtifact.getVersion());
                            File sourceJar = getArtifactFile(artifact, level);
                            if (sourceJar != null && sourceJar.exists()) {
                                FileInputStream sourceJarInputStream = new FileInputStream(sourceJar);
                                processJarFile(sourceJarInputStream, sourceJar.getPath(), contextJarMetadata,
                                        false, level + 1, lookForNotice, lookForLicense, true);
                                IOUtils.closeQuietly(sourceJarInputStream);
                            }
                        } else {
                            // we are already processing a sources artifact, we need to load the pom artifact to extract information from there
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), null, "pom",
                                    resolvedArtifact.getVersion());
                            File artifactPom = getArtifactFile(artifact, level);
                            if (artifactPom != null && artifactPom.exists()) {
                                output(indent, "Processing POM for " + artifact + "...");
                                processPOM(lookForNotice, lookForLicense, jarFilePath, contextJarMetadata,
                                        contextJarMetadata.getEmbeddedJars(), level + 1,
                                        new FileInputStream(artifactPom), processingSources);
                            }
                        }
                    } else {
                        output(indent, "===>  Couldn't resolve artifact " + mavenCentralArtifact
                                + " in Maven Central. Please resolve license and notice files manually!", false,
                                true);
                    }
                } else {
                    output(indent, "===>  Couldn't find nor POM, license or notice. Please check manually!",
                            false, true);
                }
            }
        }
    }

    output(indent, "Done processing JAR " + jarFilePath + ".", false, true);

}

From source file:org.apache.maven.plugins.help.EvaluateMojo.java

/**
 * @param xstreamObject not null/*from  w w w  .j  a  v  a2s . com*/
 * @param jarFile not null
 * @param packageFilter a package name to filter.
 */
private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) {
    JarInputStream jarStream = null;
    try {
        jarStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = jarStream.getNextJarEntry();
        while (jarEntry != null) {
            if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
                String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));
                name = name.replaceAll("/", "\\.");

                if (name.contains(packageFilter)) {
                    try {
                        Class<?> clazz = ClassUtils.getClass(name);
                        String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz));
                        xstreamObject.alias(alias, clazz);
                        if (!clazz.equals(Model.class)) {
                            xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field
                        }
                    } catch (ClassNotFoundException e) {
                        getLog().error(e);
                    }
                }
            }

            jarStream.closeEntry();
            jarEntry = jarStream.getNextJarEntry();
        }
    } catch (IOException e) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("IOException: " + e.getMessage(), e);
        }
    } finally {
        IOUtil.close(jarStream);
    }
}

From source file:org.apache.pluto.util.assemble.ear.EarAssembler.java

public void assembleInternal(AssemblerConfig config) throws UtilityException, IOException {

    File source = config.getSource();
    File dest = config.getDestination();

    JarInputStream earIn = new JarInputStream(new FileInputStream(source));
    JarOutputStream earOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest), BUFLEN));

    try {//from  w w  w .ja v  a2 s.c  o m

        JarEntry entry;

        // Iterate over entries in the EAR archive
        while ((entry = earIn.getNextJarEntry()) != null) {

            // If a war file is encountered, assemble it into a
            // ByteArrayOutputStream and write the assembled bytes
            // back to the EAR archive.
            if (entry.getName().toLowerCase().endsWith(".war")) {

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Assembling war file " + entry.getName());
                }

                // keep a handle to the AssemblySink so we can write out
                // JarEntry metadata and the bytes later.
                AssemblySink warBytesOut = getAssemblySink(config, entry);
                JarOutputStream warOut = new JarOutputStream(warBytesOut);

                JarStreamingAssembly.assembleStream(new JarInputStream(earIn), warOut,
                        config.getDispatchServletClass());

                JarEntry warEntry = new JarEntry(entry);

                // Write out the assembled JarEntry metadata
                warEntry.setSize(warBytesOut.getByteCount());
                warEntry.setCrc(warBytesOut.getCrc());
                warEntry.setCompressedSize(-1);
                earOut.putNextEntry(warEntry);

                // Write out the assembled WAR file to the EAR
                warBytesOut.writeTo(earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            } else {

                earOut.putNextEntry(entry);
                IOUtils.copy(earIn, earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            }
        }

    } finally {

        earOut.close();
        earIn.close();

    }
}

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

/**
 * Change the version in jar//  ww w .  j  a v  a2 s  .c  o  m
 * 
 * @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.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;//from ww w.j a  v  a  2 s.c o  m
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        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()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}