Example usage for java.util.jar JarOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:org.apache.hadoop.mapreduce.v2.TestMRJobs.java

private Path makeJobJarWithLib(String testDir) throws FileNotFoundException, IOException {
    Path jobJarPath = new Path(testDir, "thejob.jar");
    FileOutputStream fos = new FileOutputStream(new File(jobJarPath.toUri().getPath()));
    JarOutputStream jos = new JarOutputStream(fos);
    // Have to put in real jar files or it will complain
    createAndAddJarToJar(jos, new File(new Path(testDir, "lib1.jar").toUri().getPath()));
    createAndAddJarToJar(jos, new File(new Path(testDir, "lib2.jar").toUri().getPath()));
    jos.close();
    localFs.setPermission(jobJarPath, new FsPermission("700"));
    return jobJarPath;
}

From source file:org.hyperic.hq.plugin.websphere.WebsphereProductPlugin.java

private File runtimeJarHack(File file) throws Exception {
    String tmp = System.getProperty("java.io.tmpdir"); //agent/tmp
    File newJar = new File(tmp, file.getName());
    if (newJar.exists()) {
        return newJar;
    }//from  w w  w . j  a v a  2  s  . c  o m
    log.debug("Creating " + newJar);
    JarFile jar = new JarFile(file);
    JarOutputStream os = new JarOutputStream(new FileOutputStream(newJar));
    byte[] buffer = new byte[1024];
    try {
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            int n;
            JarEntry entry = e.nextElement();

            if (entry.getName().startsWith("org/apache/commons/logging/")) {
                continue;
            }
            InputStream entryStream = jar.getInputStream(entry);

            os.putNextEntry(entry);
            while ((n = entryStream.read(buffer)) != -1) {
                os.write(buffer, 0, n);
            }
            entryStream.close();
        }
    } finally {
        jar.close();
        os.close();
    }
    return newJar;
}

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

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);//  w  w w.  j a va  2  s . c  o  m
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:org.apache.sqoop.integration.connectorloading.ClasspathTest.java

private Map<String, String> buildJar(String outputDir, Map<String, JarContents> sourceFileToJarMap)
        throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    List<File> sourceFiles = new ArrayList<>();
    for (JarContents jarContents : sourceFileToJarMap.values()) {
        sourceFiles.addAll(jarContents.sourceFiles);
    }//  w w  w .  j  av  a2s.c  o m

    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(outputDir.toString())));

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles);

    boolean compiled = compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    if (!compiled) {
        throw new RuntimeException("failed to compile");
    }

    for (Map.Entry<String, JarContents> jarNameAndContents : sourceFileToJarMap.entrySet()) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, ".");

        JarOutputStream target = new JarOutputStream(
                new FileOutputStream(outputDir.toString() + File.separator + jarNameAndContents.getKey()),
                manifest);
        List<String> classesForJar = new ArrayList<>();
        for (File sourceFile : jarNameAndContents.getValue().getSourceFiles()) {
            //split the file on dot to get the filename from FILENAME.java
            String fileName = sourceFile.getName().split("\\.")[0];
            classesForJar.add(fileName);
        }

        File dir = new File(outputDir);
        File[] directoryListing = dir.listFiles();
        for (File compiledClass : directoryListing) {
            String classFileName = compiledClass.getName().split("\\$")[0].split("\\.")[0];
            if (classesForJar.contains(classFileName)) {
                addFileToJar(compiledClass, target);
            }
        }

        for (File propertiesFile : jarNameAndContents.getValue().getProperitesFiles()) {
            addFileToJar(propertiesFile, target);
        }

        target.close();

    }
    //delete non jar files
    File dir = new File(outputDir);
    File[] directoryListing = dir.listFiles();
    for (File file : directoryListing) {
        String extension = file.getName().split("\\.")[1];
        if (!extension.equals("jar")) {
            file.delete();
        }
    }

    Map<String, String> jarMap = new HashMap<>();
    jarMap.put(TEST_CONNECTOR_JAR_NAME, outputDir.toString() + File.separator + TEST_CONNECTOR_JAR_NAME);
    jarMap.put(TEST_DEPENDENCY_JAR_NAME, outputDir.toString() + File.separator + TEST_DEPENDENCY_JAR_NAME);
    return jarMap;
}

From source file:com.buglabs.bug.ws.program.ProgramServlet.java

/**
 * Code from forum board for creating a Jar.
 * //from ww w .  j a v  a 2  s  .c o m
 * @param archiveFile
 * @param tobeJared
 * @param rootDir
 * @throws IOException
 */
protected void createJarArchive(File archiveFile, File[] tobeJared, File rootDir) throws IOException {

    byte buffer[] = new byte[BUFFER_SIZE];
    // Open archive file
    FileOutputStream stream = new FileOutputStream(archiveFile);
    JarOutputStream out = new JarOutputStream(stream, new Manifest(new FileInputStream(
            rootDir.getAbsolutePath() + File.separator + "META-INF" + File.separator + MANIFEST_FILENAME)));

    for (int i = 0; i < tobeJared.length; i++) {
        if (tobeJared[i] == null || !tobeJared[i].exists() || tobeJared[i].isDirectory())
            continue; // Just in case...

        String relPath = getRelPath(rootDir.getAbsolutePath(), tobeJared[i].getAbsolutePath());

        // Add archive entry
        JarEntry jarAdd = new JarEntry(relPath);
        jarAdd.setTime(tobeJared[i].lastModified());
        out.putNextEntry(jarAdd);
        // Write file to archive
        FileInputStream in = new FileInputStream(tobeJared[i]);
        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();

}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/*from   w  w w .j  a  v a  2 s .c o  m*/
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:com.googlecode.mycontainer.maven.plugin.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())
 * /*from  w  w w .  j a v  a 2s  .co  m*/
 * @param classPath
 *            List&lt;String> of all classpath elements.
 * @return
 * @throws IOException
 */
private File createJar(List 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.
    String cp = "";
    for (Iterator it = classPath.iterator(); it.hasNext();) {
        String el = (String) it.next();
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp += UrlUtils.getURL(new File(el)).toExternalForm() + " ";
    }

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

    man.write(jos);
    jos.close();

    return file;
}

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 {//from  www .  ja  v a 2  s  .  c o 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:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java

/**
 * Change the version in jar//from  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.oozie.action.hadoop.TestMapReduceActionExecutor.java

private void createAndAddJarToJar(JarOutputStream jos, File jarFile) throws Exception {
    FileOutputStream fos2 = new FileOutputStream(jarFile);
    JarOutputStream jos2 = new JarOutputStream(fos2);
    // Have to have at least one entry or it will complain
    ZipEntry ze = new ZipEntry(jarFile.getName() + ".inside");
    jos2.putNextEntry(ze);/*from  ww w  .  j av  a 2s .co m*/
    jos2.closeEntry();
    jos2.close();
    ze = new ZipEntry("lib/" + jarFile.getName());
    jos.putNextEntry(ze);
    FileInputStream in = new FileInputStream(jarFile);
    byte buf[] = new byte[1024];
    int numRead;
    do {
        numRead = in.read(buf);
        if (numRead >= 0) {
            jos.write(buf, 0, numRead);
        }
    } while (numRead != -1);
    in.close();
    jos.closeEntry();
    jarFile.delete();
}