Example usage for java.util.jar JarOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

From source file:org.wso2.carbon.automation.test.utils.common.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws IOException, URISyntaxException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarFile jarFile = new JarFile(sourceFile);
    String fileName = jarFile.getName();
    String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
    File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
    JarOutputStream jarOutputStream = null;
    try {// w ww .  j  a  v  a  2 s . co  m
        jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
        Enumeration<JarEntry> entries = jarFile.entries();
        InputStream inputStream = null;
        while (entries.hasMoreElements()) {
            try {
                JarEntry jarEntry = entries.nextElement();
                inputStream = jarFile.getInputStream(jarEntry);
                //jarOutputStream.putNextEntry(jarEntry);
                //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
                jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    jarOutputStream.write(buffer, 0, bytesRead);
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                    jarOutputStream.flush();
                    jarOutputStream.closeEntry();
                }
            }
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:net.cliseau.composer.javacor.MissingToolException.java

/**
 * Create a JAR file for startup of the unit.
 *
 * The created JAR file contains all the specified archive files and contains a
 * manifest which in particular determines the class path for the JAR file.
 * All files in startupArchiveFileNames are deleted during the execution of
 * this method./*from  w  w w.  j a  v a2  s  . c o  m*/
 *
 * @param fileName Name of the file to write the result to.
 * @param startupArchiveFileNames Names of files to include in the JAR file.
 * @param startupDependencies Names of classpath entries to include in the JAR file classpath.
 * @exception IOException Thrown if file operations fail, such as creating the JAR file or reading from the input file(s).
 */
private void createJAR(final String fileName, final Collection<String> startupArchiveFileNames,
        final Collection<String> startupDependencies) throws IOException, InvalidConfigurationException {
    // Code inspired by:
    //   http://www.java2s.com/Code/Java/File-Input-Output/CreateJarfile.htm
    //   http://www.massapi.com/class/java/util/jar/Manifest.java.html

    // construct manifest with appropriate "Class-path" property
    Manifest starterManifest = new Manifest();
    Attributes starterAttributes = starterManifest.getMainAttributes();
    // Remark for those who read this code to learn something:
    // If one forgets to set the MANIFEST_VERSION attribute, then
    // silently *nothing* (except for a line break) will be written
    // to the JAR file manifest!
    starterAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    starterAttributes.put(Attributes.Name.MAIN_CLASS, getStartupName());
    starterAttributes.put(Attributes.Name.CLASS_PATH,
            StringUtils.join(startupDependencies, manifestClassPathSeparator));

    // create output JAR file
    FileOutputStream fos = new FileOutputStream(fileName);
    JarOutputStream jos = new JarOutputStream(fos, starterManifest);

    // add the entries for the starter archive's files
    for (String archFileName : startupArchiveFileNames) {
        File startupArchiveFile = new File(archFileName);
        JarEntry startupEntry = new JarEntry(startupArchiveFile.getName());
        startupEntry.setTime(startupArchiveFile.lastModified());
        jos.putNextEntry(startupEntry);

        // copy the content of the starter archive's file
        // TODO: if we used Apache Commons IO 2.1, then the following
        //       code block could be simplified as:
        //       FileUtils.copyFile(startupArchiveFile, jos);
        FileInputStream fis = new FileInputStream(startupArchiveFile);
        byte buffer[] = new byte[1024 /*bytes*/];
        while (true) {
            int nRead = fis.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            jos.write(buffer, 0, nRead);
        }
        fis.close();
        // end of FileUtils.copyFile() substitution code
        jos.closeEntry();

        startupArchiveFile.delete(); // cleanup the disk a bit
    }

    jos.close();
    fos.close();
}

From source file:org.codehaus.mojo.cassandra.AbstractCassandraMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for
 * all classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param jarFile   The jar file to create/update
 * @param mainClass The main class to run.
 * @throws java.io.IOException if something went wrong.
 *///www  . jav a2s. c o  m
protected void createCassandraJar(File jarFile, String mainClass, File cassandraDir) throws IOException {
    File conf = new File(cassandraDir, "conf");
    FileOutputStream fos = null;
    JarOutputStream jos = null;
    try {
        fos = new FileOutputStream(jarFile);
        jos = new JarOutputStream(fos);
        jos.setLevel(JarOutputStream.STORED);
        jos.putNextEntry(new JarEntry("META-INF/MANIFEST.MF"));

        Manifest man = new Manifest();

        // we can't use StringUtils.join here since we need to add a '/' to
        // the end of directory entries - otherwise the jvm will ignore them.
        StringBuilder cp = new StringBuilder();
        cp.append(new URL(conf.toURI().toASCIIString()).toExternalForm());
        cp.append(' ');
        getLog().debug("Adding plugin artifact: " + ArtifactUtils.versionlessKey(pluginArtifact)
                + " to the classpath");
        cp.append(new URL(pluginArtifact.getFile().toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        for (Artifact artifact : this.pluginDependencies) {
            getLog().debug("Adding plugin dependency artifact: " + ArtifactUtils.versionlessKey(artifact)
                    + " to the classpath");
            // NOTE: if File points to a directory, this entry MUST end in '/'.
            cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
            cp.append(' ');
        }

        if (addMainClasspath || addTestClasspath) {
            if (addTestClasspath) {
                getLog().debug("Adding: " + testClassesDirectory + " to the classpath");
                cp.append(new URL(testClassesDirectory.toURI().toASCIIString()).toExternalForm());
                cp.append(' ');
            }
            if (addMainClasspath) {
                getLog().debug("Adding: " + classesDirectory + " to the classpath");
                cp.append(new URL(classesDirectory.toURI().toASCIIString()).toExternalForm());
                cp.append(' ');
            }
            for (Artifact artifact : (Set<Artifact>) this.project.getArtifacts()) {
                if ("jar".equals(artifact.getType()) && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                        && (!Artifact.SCOPE_TEST.equals(artifact.getScope()) || addTestClasspath)) {
                    getLog().debug("Adding dependency: " + ArtifactUtils.versionlessKey(artifact)
                            + " to the classpath");
                    // NOTE: if File points to a directory, this entry MUST end in '/'.
                    cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
                    cp.append(' ');
                }
            }
        }

        man.getMainAttributes().putValue("Manifest-Version", "1.0");
        man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
        man.getMainAttributes().putValue("Main-Class", mainClass);

        man.write(jos);
    } finally {
        IOUtil.close(jos);
        IOUtil.close(fos);
    }
}

From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleJarPath = getModuleJarPath(moduleId);
    Files.deleteIfExists(moduleJarPath);
    JarFile sourceJarFile;/* w  w w.ja  v  a2 s. c  om*/
    try {
        sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile()));
    try {
        String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName();
        Enumeration<JarEntry> sourceEntries = sourceJarFile.entries();
        while (sourceEntries.hasMoreElements()) {
            JarEntry sourceEntry = sourceEntries.nextElement();
            if (sourceEntry.getName().equals(moduleSpecFileName)) {
                // avoid double entry for module spec
                continue;
            }
            destJarFile.putNextEntry(sourceEntry);
            if (!sourceEntry.isDirectory()) {
                InputStream inputStream = sourceJarFile.getInputStream(sourceEntry);
                IOUtils.copy(inputStream, destJarFile);
                IOUtils.closeQuietly(inputStream);
            }
            destJarFile.closeEntry();
        }
        // write the module spec
        String serialized = moduleSpecSerializer.serialize(moduleSpec);
        JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName());
        destJarFile.putNextEntry(moduleSpecEntry);
        IOUtils.write(serialized, destJarFile);
        destJarFile.closeEntry();
    } finally {
        IOUtils.closeQuietly(sourceJarFile);
        IOUtils.closeQuietly(destJarFile);
    }
    // update the timestamp on the jar file to indicate that the module has been updated
    Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:com.speed.ob.api.ClassStore.java

public void init(JarInputStream jarIn, File output, File in) throws IOException {
    ZipEntry entry;/*  w  ww .  jav  a 2s  .co  m*/
    JarOutputStream out = new JarOutputStream(new FileOutputStream(new File(output, in.getName())));
    while ((entry = jarIn.getNextEntry()) != null) {
        byte[] data = IOUtils.toByteArray(jarIn);
        if (entry.getName().endsWith(".class")) {
            ClassReader reader = new ClassReader(data);
            ClassNode cn = new ClassNode();
            reader.accept(cn, ClassReader.EXPAND_FRAMES);
            store.put(cn.name, cn);
        } else if (!entry.isDirectory()) {
            Logger.getLogger(getClass().getName()).finer("Storing " + entry.getName() + " in output file");
            JarEntry je = new JarEntry(entry.getName());
            out.putNextEntry(je);
            out.write(data);
            out.closeEntry();
        }
    }
    out.close();
}

From source file:net.hasor.maven.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for all
 * classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param classPath List&lt;String> of all classpath elements.
 * @return/* w  w  w . j  a va  2s  .c  o m*/
 * @throws IOException
 */
private File createJar(List<String> classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);
    Manifest man = new Manifest();
    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    StringBuilder cp = new StringBuilder();
    for (String el : classPath) {
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
    }
    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);
    man.write(jos);
    jos.close();
    return file;
}

From source file:com.headwire.aem.tooling.intellij.eclipse.stub.JarBuilder.java

public InputStream buildJar(final IFolder sourceDir) throws CoreException {

    ByteArrayOutputStream store = new ByteArrayOutputStream();

    JarOutputStream zos = null;
    InputStream manifestInput = null;
    try {//from   w  w  w. j a va 2 s .co m
        IResource manifestResource = sourceDir.findMember(JarFile.MANIFEST_NAME);
        if (manifestResource == null || manifestResource.getType() != IResource.FILE) {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "No file named " + JarFile.MANIFEST_NAME + " found under " + sourceDir));
        }

        manifestInput = ((IFile) manifestResource).getContents();

        Manifest manifest = new Manifest(manifestInput);

        zos = new JarOutputStream(store);
        zos.setLevel(Deflater.NO_COMPRESSION);
        // manifest first
        final ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(anEntry);
        manifest.write(zos);
        zos.closeEntry();
        zipDir(sourceDir, zos, "");
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(manifestInput);
    }

    return new ByteArrayInputStream(store.toByteArray());
}

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   www .j av  a 2s .c  o m*/
        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 {//  w w  w . j  ava  2 s .  c o m
        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();
    }
}

From source file:org.apache.maven.plugins.shade.resource.ServicesResourceTransformer.java

public void modifyOutputStream(JarOutputStream jos, boolean consistentDates) throws IOException {
    for (Map.Entry<String, ServiceStream> entry : serviceEntries.entrySet()) {
        String key = entry.getKey();
        ServiceStream data = entry.getValue();

        if (relocators != null) {
            key = key.substring(SERVICES_PATH.length() + 1);
            for (Relocator relocator : relocators) {
                if (relocator.canRelocateClass(key)) {
                    key = relocator.relocateClass(key);
                    break;
                }/*from   w w  w .  jav a2  s.  c  o m*/
            }

            key = SERVICES_PATH + '/' + key;
        }

        JarEntry jarEntry = new ConsistentJarEntry(key, consistentDates);
        jos.putNextEntry(jarEntry);

        //read the content of service file for candidate classes for relocation
        PrintWriter writer = new PrintWriter(jos);
        InputStreamReader streamReader = new InputStreamReader(data.toInputStream());
        BufferedReader reader = new BufferedReader(streamReader);
        String className;

        while ((className = reader.readLine()) != null) {

            if (relocators != null) {
                for (Relocator relocator : relocators) {
                    //if the class can be relocated then relocate it
                    if (relocator.canRelocateClass(className)) {
                        className = relocator.applyToSourceContent(className);
                        break;
                    }
                }
            }

            writer.println(className);
            writer.flush();
        }

        reader.close();
        data.reset();
    }
}