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:io.smartspaces.workbench.project.java.BndOsgiContainerBundleCreator.java

/**
 * Create a Jar file from a source folder.
 *
 * @param jarDestinationFile//from w  w  w .  ja v  a2 s . co  m
 *          the jar file being created
 * @param sourceFolder
 *          the source folder containing the classes
 */
private void createJarFile(File jarDestinationFile, File sourceFolder) {
    // Create a buffer for reading the files
    byte[] buf = new byte[IO_BUFFER_SIZE];

    JarOutputStream out = null;
    try {
        // Create the jar file
        out = new JarOutputStream(new FileOutputStream(jarDestinationFile));

        writeJarFile(sourceFolder, buf, out, "");

        // Complete the jar file
        out.close();
    } catch (Exception e) {
        throw new SmartSpacesException(
                String.format("Failed creating jar file %s", jarDestinationFile.getAbsolutePath()), e);
    } finally {
        fileSupport.close(out, true);
    }
}

From source file:com.francetelecom.clara.cloud.mvn.consumer.maven.MavenDeployer.java

private File populateJarArchive(File archive, List<FileRef> fileset) throws IOException {
    archive.getParentFile().mkdirs();/*w  ww  . j ava2 s .  co  m*/
    JarOutputStream target = new JarOutputStream(new FileOutputStream(archive));
    for (FileRef fileRef : fileset) {
        JarEntry jarAdd = new JarEntry(fileRef.getRelativeLocation());
        target.putNextEntry(jarAdd);
        target.write(fileRef.getContent().getBytes());
    }
    target.close();
    return archive;
}

From source file:org.apache.crunch.WordCountHBaseTest.java

@SuppressWarnings("deprecation")
@Before/*from   w  ww . ja  v  a2  s . co  m*/
public void setUp() throws Exception {
    Configuration conf = hbaseTestUtil.getConfiguration();
    File tmpDir = File.createTempFile("logdir", "");
    tmpDir.delete();
    tmpDir.mkdir();
    tmpDir.deleteOnExit();
    conf.set("hadoop.log.dir", tmpDir.getAbsolutePath());
    conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
    conf.setInt("hbase.master.info.port", -1);
    conf.setInt("hbase.regionserver.info.port", -1);

    hbaseTestUtil.startMiniZKCluster();
    hbaseTestUtil.startMiniCluster();
    hbaseTestUtil.startMiniMapReduceCluster(1);

    // For Hadoop-2.0.0, we have to do a bit more work.
    if (TaskAttemptContext.class.isInterface()) {
        conf = hbaseTestUtil.getConfiguration();
        FileSystem fs = FileSystem.get(conf);
        Path tmpPath = new Path("target", "WordCountHBaseTest-tmpDir");
        FileSystem localFS = FileSystem.getLocal(conf);
        for (FileStatus jarFile : localFS.listStatus(new Path("target/lib/"))) {
            Path target = new Path(tmpPath, jarFile.getPath().getName());
            fs.copyFromLocalFile(jarFile.getPath(), target);
            DistributedCache.addFileToClassPath(target, conf, fs);
        }

        // Create a programmatic container for this jar.
        JarOutputStream jos = new JarOutputStream(new FileOutputStream("WordCountHBaseTest.jar"));
        File baseDir = new File("target/test-classes");
        String prefix = "org/apache/crunch/";
        jarUp(jos, baseDir, prefix + "WordCountHBaseTest.class");
        jarUp(jos, baseDir, prefix + "WordCountHBaseTest$1.class");
        jarUp(jos, baseDir, prefix + "WordCountHBaseTest$2.class");
        jos.close();

        Path target = new Path(tmpPath, "WordCountHBaseTest.jar");
        fs.copyFromLocalFile(true, new Path("WordCountHBaseTest.jar"), target);
        DistributedCache.addFileToClassPath(target, conf, fs);
    }
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Creates a Jar archive that includes the given list of files
 * //w  w  w  .  jav a 2s  .  c om
 * @param archiveFile the name of the jar archive file
 * @param tobeJared the files to be included in the jar file
 * 
 * @return if the operation was successful
 */
public static boolean createJarArchive(File archiveFile, List<File> tobeJared) {
    try {
        byte buffer[] = new byte[BUFFER_SIZE];
        // Open archive file
        FileOutputStream stream = new FileOutputStream(archiveFile);
        JarOutputStream out = new JarOutputStream(stream, new Manifest());

        for (int i = 0; i < tobeJared.size(); i++) {
            if (tobeJared.get(i) == null || !tobeJared.get(i).exists() || tobeJared.get(i).isDirectory())
                continue; // Just in case...
            log.debug("Adding " + tobeJared.get(i).getName());

            // Add archive entry
            JarEntry jarAdd = new JarEntry(tobeJared.get(i).getName());
            jarAdd.setTime(tobeJared.get(i).lastModified());
            out.putNextEntry(jarAdd);

            // Write file to archive
            FileInputStream in = new FileInputStream(tobeJared.get(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();
        log.info("Adding completed OK");
        return true;
    } catch (Exception e) {
        log.error("Creating jar file failed", e);
        return false;
    }
}

From source file:com.dragome.callbackevictor.serverside.utils.RewritingUtils.java

public static boolean rewriteJar(final JarInputStream pInput, final ResourceTransformer transformer,
        final JarOutputStream pOutput, final Matcher pMatcher) throws IOException {

    boolean changed = false;

    while (true) {
        final JarEntry entry = pInput.getNextJarEntry();

        if (entry == null) {
            break;
        }/* w  w  w .j av  a2s.  com*/

        if (entry.isDirectory()) {
            pOutput.putNextEntry(new JarEntry(entry));
            continue;
        }

        final String name = entry.getName();

        pOutput.putNextEntry(new JarEntry(name));

        if (name.endsWith(".class")) {
            if (pMatcher.isMatching(name)) {

                if (log.isDebugEnabled()) {
                    log.debug("transforming " + name);
                }

                final byte[] original = toByteArray(pInput);

                byte[] transformed = transformer.transform(original);

                pOutput.write(transformed);

                changed |= transformed.length != original.length;

                continue;
            }
        } else if (name.endsWith(".jar") || name.endsWith(".ear") || name.endsWith(".zip")
                || name.endsWith(".war")) {

            changed |= rewriteJar(new JarInputStream(pInput), transformer, new JarOutputStream(pOutput),
                    pMatcher);

            continue;
        }

        int length = copy(pInput, pOutput);

        log.debug("copied " + name + "(" + length + ")");
    }

    pInput.close();
    pOutput.close();

    return changed;
}

From source file:com.opensymphony.xwork2.util.fs.JarEntryRevisionTest.java

private String createJarFile(long time) throws Exception {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    Path jarPath = Paths/*  ww w  .j a  va2 s  .com*/
            .get(Thread.currentThread().getContextClassLoader().getResource("xwork-jar.jar").toURI())
            .getParent();
    File jarFile = jarPath.resolve("JarEntryRevisionTest_testNeedsReloading.jar").toFile();
    FileOutputStream fos = new FileOutputStream(jarFile, false);
    JarOutputStream target = new JarOutputStream(fos, manifest);
    target.putNextEntry(new ZipEntry("com/opensymphony/xwork2/util/fs/"));
    ZipEntry entry = new ZipEntry("com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class");
    entry.setTime(time);
    target.putNextEntry(entry);
    InputStream source = getClass()
            .getResourceAsStream("/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class");
    IOUtils.copy(source, target);
    source.close();
    target.closeEntry();
    target.close();
    fos.close();

    return jarFile.toURI().toURL().toExternalForm();
}

From source file:gov.redhawk.rap.internal.PluginProviderServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Path path = new Path(req.getRequestURI());
    String pluginId = path.lastSegment();
    if (pluginId.endsWith(".jar")) {
        pluginId = pluginId.substring(0, pluginId.length() - 4);
    }//from   w  w w  . j  av a  2s  .c o m
    final Bundle b = Platform.getBundle(pluginId);
    if (b == null) {
        final String protocol = req.getProtocol();
        final String msg = "Plugin does not exist: " + pluginId;
        if (protocol.endsWith("1.1")) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
        return;
    }
    final File file = FileLocator.getBundleFile(b);
    resp.setContentType("application/octet-stream");

    if (file.isFile()) {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + "\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        resp.setContentLength((int) file.length());
        final FileInputStream istream = new FileInputStream(file);
        try {
            IOUtils.copy(istream, resp.getOutputStream());
        } finally {
            istream.close();
        }
        resp.flushBuffer();
    } else {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + ".jar\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        final Manifest man = new Manifest(new FileInputStream(new File(file, "META-INF/MANIFEST.MF")));
        final JarOutputStream out = new JarOutputStream(outputStream, man);
        final File binDir = new File(file, "bin");

        if (binDir.exists()) {
            addFiles(out, Path.ROOT, binDir.listFiles());
            for (final File f : file.listFiles()) {
                if (!f.getName().equals("bin")) {
                    addFiles(out, Path.ROOT, f);
                }
            }
        } else {
            addFiles(out, Path.ROOT, file.listFiles());
        }
        out.close();
        outputStream.close();
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        resp.setContentLength(outputStream.size());
        try {
            IOUtils.copy(inputStream, resp.getOutputStream());
        } finally {
            inputStream.close();
        }
        resp.flushBuffer();
    }

}

From source file:com.cloudera.sqoop.orm.CompilationManager.java

/**
 * Create an output jar file to use when executing MapReduce jobs.
 *//*ww  w  .  java 2s .co  m*/
public void jar() throws IOException {
    String jarOutDir = options.getJarOutputDir();

    String jarFilename = getJarFilename();

    LOG.info("Writing jar file: " + jarFilename);

    File jarFileObj = new File(jarFilename);
    if (jarFileObj.exists()) {
        LOG.debug("Found existing jar (" + jarFilename + "); removing.");
        if (!jarFileObj.delete()) {
            LOG.warn("Could not remove existing jar file: " + jarFilename);
        }
    }

    FileOutputStream fstream = null;
    JarOutputStream jstream = null;
    try {
        fstream = new FileOutputStream(jarFilename);
        jstream = new JarOutputStream(fstream);

        addClassFilesFromDir(new File(jarOutDir), jstream);
        jstream.finish();
    } finally {
        if (null != jstream) {
            try {
                jstream.close();
            } catch (IOException ioe) {
                LOG.warn("IOException closing jar stream: " + ioe.toString());
            }
        }

        if (null != fstream) {
            try {
                fstream.close();
            } catch (IOException ioe) {
                LOG.warn("IOException closing file stream: " + ioe.toString());
            }
        }
    }

    LOG.debug("Finished writing jar file " + jarFilename);
}

From source file:org.mule.util.JarUtils.java

public static void createJarFileEntries(File jarFile, LinkedHashMap entries) throws Exception {
    JarOutputStream jarStream = null;
    FileOutputStream fileStream = null;

    if (jarFile != null) {
        logger.debug("Creating jar file " + jarFile.getAbsolutePath());

        try {/*from   w ww  . j  a  v a2s  .  c o m*/
            fileStream = new FileOutputStream(jarFile);
            jarStream = new JarOutputStream(fileStream);

            if (entries != null && !entries.isEmpty()) {
                Iterator iter = entries.keySet().iterator();
                while (iter.hasNext()) {
                    String jarFilePath = (String) iter.next();
                    Object content = entries.get(jarFilePath);

                    JarEntry entry = new JarEntry(jarFilePath);
                    jarStream.putNextEntry(entry);

                    logger.debug("Adding jar entry " + jarFilePath + " to " + jarFile.getAbsolutePath());

                    if (content instanceof String) {
                        writeJarEntry(jarStream, ((String) content).getBytes());
                    } else if (content instanceof byte[]) {
                        writeJarEntry(jarStream, (byte[]) content);
                    } else if (content instanceof File) {
                        writeJarEntry(jarStream, (File) content);
                    }
                }
            }

            jarStream.flush();
            fileStream.getFD().sync();
        } finally {
            if (jarStream != null) {
                try {
                    jarStream.close();
                } catch (Exception jarNotClosed) {
                    logger.debug(jarNotClosed);
                }
            }
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (Exception fileNotClosed) {
                    logger.debug(fileNotClosed);
                }
            }
        }
    }
}

From source file:com.hellblazer.process.JavaProcessTest.java

protected void copyTestJarFile() throws Exception {
    String classFileName = HelloWorld.class.getCanonicalName().replace('.', '/') + ".class";
    URL classFile = getClass().getResource("/" + classFileName);
    assertNotNull(classFile);/*from   ww  w  . ja  v  a2  s .com*/

    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0");
    attributes.putValue("Main-Class", HelloWorld.class.getCanonicalName());

    FileOutputStream fos = new FileOutputStream(new File(testDir, TEST_JAR));
    JarOutputStream jar = new JarOutputStream(fos, manifest);
    JarEntry entry = new JarEntry(classFileName);
    jar.putNextEntry(entry);
    InputStream in = classFile.openStream();
    byte[] buffer = new byte[1024];
    for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
        jar.write(buffer, 0, read);
    }
    in.close();
    jar.closeEntry();
    jar.close();
}