Example usage for java.util.jar JarOutputStream JarOutputStream

List of usage examples for java.util.jar JarOutputStream JarOutputStream

Introduction

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

Prototype

public JarOutputStream(OutputStream out, Manifest man) throws IOException 

Source Link

Document

Creates a new JarOutputStream with the specified Manifest.

Usage

From source file:org.jahia.modules.serversettings.portlets.BasePortletHelper.java

/**
 * Returns a file descriptor for the modified (prepared) portlet WAR file.
 * /*  w  ww  . j av a  2  s.co m*/
 * @param sourcePortletWar
 *            the source portlet WAR file
 * @return a file descriptor for the modified (prepared) portlet WAR file
 * @throws IOException
 *             in case of processing error
 */
public File process(File sourcePortletWar) throws IOException {
    JarFile jar = new JarFile(sourcePortletWar);
    File dest = new File(FilenameUtils.getFullPathNoEndSeparator(sourcePortletWar.getPath()),
            FilenameUtils.getBaseName(sourcePortletWar.getName()) + ".war");
    try {
        boolean needsServerSpecificProcessing = needsProcessing(jar);
        if (portletTldsPresent(jar) && !needsServerSpecificProcessing) {
            return sourcePortletWar;
        }
        jar.close();
        final JarInputStream jarIn = new JarInputStream(new FileInputStream(sourcePortletWar));
        final Manifest manifest = jarIn.getManifest();
        final JarOutputStream jarOut;
        if (manifest != null) {
            jarOut = new JarOutputStream(new FileOutputStream(dest), manifest);
        } else {
            jarOut = new JarOutputStream(new FileOutputStream(dest));
        }

        try {
            copyEntries(jarIn, jarOut);

            process(jarIn, jarOut);

            if (!hasPortletTld) {
                addToJar("META-INF/portlet-resources/portlet.tld", "WEB-INF/portlet.tld", jarOut);
            }
            if (!hasPortlet2Tld) {
                addToJar("META-INF/portlet-resources/portlet_2_0.tld", "WEB-INF/portlet_2_0.tld", jarOut);
            }
        } finally {
            jarIn.close();
            jarOut.close();
            FileUtils.deleteQuietly(sourcePortletWar);
        }
        return dest;
    } finally {
        jar.close();
    }
}

From source file:rapture.kernel.JarApiImplTest.java

private byte[] createTestJar() {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (JarOutputStream target = new JarOutputStream(baos, manifest)) {
        File testJar = new File(TEST_JAR_PATH);
        if (!testJar.exists() || !testJar.canRead()) {
            return null;
        }// w  w w  . j  av  a2 s .  c  o m
        add(testJar, target);
    } catch (IOException e) {
        log.error(e);
    }
    return baos.toByteArray();
}

From source file:org.xwiki.extension.test.ExtensionPackager.java

public void generateExtension(String classPackageFolder, URL descriptorUrl) throws IOException {
    String descriptorUrlStr = descriptorUrl.toString();
    String descriptorFolderURL = descriptorUrlStr.substring(0,
            descriptorUrlStr.length() - PACKAGEFILE_DESCRIPTOR.length());

    Properties descriptorProperties = new Properties();

    InputStream descriptorStream = descriptorUrl.openStream();
    try {//  w  w  w . ja  v a 2  s .  com
        descriptorProperties.load(descriptorStream);
    } finally {
        descriptorStream.close();
    }
    String type = descriptorProperties.getProperty("type");
    if (type == null) {
        type = "zip";
    }
    String id = descriptorProperties.getProperty("id");
    if (id == null) {
        id = descriptorFolderURL.substring(0, descriptorFolderURL.length() - 1);
        id = id.substring(id.lastIndexOf('/') + 1);
    }
    String version = descriptorProperties.getProperty("version");
    if (version == null) {
        version = "1.0";
    }
    File packageFile;
    String directory = descriptorProperties.getProperty("directory");
    String fileName = descriptorProperties.getProperty("fileName");
    String repositoryName = descriptorProperties.getProperty("repository");
    if (directory == null) {
        if (fileName == null) {
            packageFile = new File(this.repositories.get(repositoryName),
                    URLEncoder.encode(id + '-' + version + '.' + type, "UTF-8"));
        } else {
            packageFile = new File(this.repositories.get(repositoryName), fileName);
        }
    } else {
        if (fileName == null) {
            fileName = URLEncoder.encode(id + '-' + version + '.' + type, "UTF-8");
        }

        packageFile = new File(this.workingDirectory, directory);
        packageFile = new File(packageFile, fileName);
    }

    // generate

    // Make sure the folder exists
    packageFile.getParentFile().mkdirs();

    FileOutputStream fos = new FileOutputStream(packageFile);
    try {
        ZipOutputStream zos;
        if (type.equals("jar")) {
            Manifest manifest = new Manifest();
            manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
            zos = new JarOutputStream(fos, manifest);
        } else {
            zos = new ZipOutputStream(fos);
        }

        try {
            // Order files
            TreeMap<String, Vfs.File> files = new TreeMap<>();
            for (Vfs.File resourceFile : Vfs.fromURL(new URL(descriptorFolderURL)).getFiles()) {
                files.put(resourceFile.getRelativePath(), resourceFile);
            }

            // Add files to zip
            for (Vfs.File resourceFile : files.values()) {
                if (!resourceFile.getRelativePath().equals(PACKAGEFILE_DESCRIPTOR)) {
                    addZipEntry(classPackageFolder, resourceFile, zos, type);
                }
            }
        } finally {
            zos.close();
        }

        // Register the extension
        this.extensionsFiles.put(new ExtensionId(id, version), packageFile);
    } finally {
        fos.close();
    }
}

From source file:com.github.sampov2.OneJarMojo.java

public void execute() throws MojoExecutionException {

    // Show some info about the plugin.
    displayPluginInfo();//from ww w. j av a2  s  . c om

    JarOutputStream out = null;
    JarInputStream template = null;
    File onejarFile = null;
    try {
        // Create the target file
        onejarFile = new File(outputDirectory, filename);

        // Prepare the onejar manifest file content
        Manifest manifest = prepareManifest();

        // Open a stream to write to the target file
        out = new JarOutputStream(new FileOutputStream(onejarFile, false), manifest);

        // Add files (based on options)
        addFilesToArchive(out);

        // Finalize the onejar archive
        template = openOnejarTemplateArchive();
        copyTemplateFilesToArchive(template, out);

    } catch (IOException e) {
        error(e);
        throw new MojoExecutionException("One-jar Mojo failed.", e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(template);
    }

    // Attach the created one-jar to the build.
    if (attachToBuild) {
        projectHelper.attachArtifact(project, "jar", classifier, onejarFile);
    }
}

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

/**
 * Change the version in jar/*  w  ww  .j  a v  a 2s .  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:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;/*  www.ja  v  a  2s  . co m*/
    int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$
    int separateMark = jobFile.lastIndexOf(File.separatorChar);
    if (dotMark != -1) {
        sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$
                + jobFile.substring(separateMark, dotMark);
    }
    try {
        JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$
    } catch (Exception e1) {
        LOGGER.error("Extraction exception occurred.", e1);
        return;
    }
    List<File> resultList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$
    if (!resultList.isEmpty()) {
        JarInputStream jarIn = null;
        JarOutputStream jarOut = null;
        try {
            JarFile jarFile = new JarFile(resultList.get(0));
            Manifest mf = jarFile.getManifest();
            jarIn = new JarInputStream(new FileInputStream(resultList.get(0)));
            Manifest newManifest = jarIn.getManifest();
            if (newManifest == null) {
                newManifest = new Manifest();
            }
            newManifest.getMainAttributes().putAll(mf.getMainAttributes());
            newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$
            jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest);
            byte[] buf = new byte[4096];
            JarEntry entry;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$
                    continue;
                }
                jarOut.putNextEntry(entry);
                int read;
                while ((read = jarIn.read(buf)) != -1) {
                    jarOut.write(buf, 0, read);
                }
                jarOut.closeEntry();
            }
        } catch (Exception e) {
            LOGGER.error("Extraction exception occurred.", e);
        } finally {
            IOUtils.closeQuietly(jarIn);
            IOUtils.closeQuietly(jarOut);
        }
        // re-zip file
        if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$
            File sourceFile = new File(sourcePath);
            try {
                JoboxUtil.zip(sourceFile, jobFile);
            } catch (Exception e) {
                LOGGER.error("Zip exception occurred.", e);
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.util.ClassLoaderTestHelper.java

/**
 * Add a list of jar files to another jar file under a specific folder.
 * It is used to generated coprocessor jar files which can be loaded by
 * the coprocessor class loader.  It is for testing usage only so we
 * don't be so careful about stream closing in case any exception.
 *
 * @param targetJar the target jar file// ww w.ja v a  2s . co  m
 * @param libPrefix the folder where to put inner jar files
 * @param srcJars the source inner jar files to be added
 * @throws Exception if anything doesn't work as expected
 */
public static void addJarFilesToJar(File targetJar, String libPrefix, File... srcJars) throws Exception {
    FileOutputStream stream = new FileOutputStream(targetJar);
    JarOutputStream out = new JarOutputStream(stream, new Manifest());
    byte buffer[] = new byte[BUFFER_SIZE];

    for (File jarFile : srcJars) {
        // Add archive entry
        JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName());
        jarAdd.setTime(jarFile.lastModified());
        out.putNextEntry(jarAdd);

        // Write file to archive
        FileInputStream in = new FileInputStream(jarFile);
        while (true) {
            int nRead = in.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            out.write(buffer, 0, nRead);
        }
        in.close();
    }
    out.close();
    stream.close();
    LOG.info("Adding jar file to outer jar file completed");
}

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

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {/*from  ww  w  .  j av a2 s . c om*/
        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:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java

@Test
public void testUpdateZipfile_warAlreadyExists() throws Exception {

    // First, set up our zipfile test.
    File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {//from   ww w.ja v  a2  s  .com
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest());

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        String expectedDestFile = webappsTarget + "s#test123#jenkins.war";
        configurator.setTargetWebappsDir(webappsTarget);
        configurator.setJenkinsPath("/s/");
        configurator.setTargetJenkinsHomeBaseDir("/some/silly/random/homeDir");

        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");
        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test123");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            // Now, try and create it a second time - this should work, even though the war exists.
            configurator.configure(config);
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile_warAlreadyExists() throws Exception {

    // First, set up our zipfile test.
    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/* ww  w  .j a va  2s  .c  om*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest());

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        String expectedDestFile = webappsTarget + "s#test123#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir("/some/silly/random/homeDir");

        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");
        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test123");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            // Now, try and create it a second time - this should work, even though the war exists.
            configurator.configure(config);
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}