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.colombbus.tangara.FileUtils.java

private static void addDirectoryToJar(File directory, JarOutputStream output, String prefix,
        PropertyChangeListener listener) throws IOException {
    try {/* w w w .  j  a v  a 2s  .c  om*/
        File files[] = directory.listFiles();
        JarEntry entry = null;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                if (prefix != null) {
                    entry = new JarEntry(prefix + "/" + files[i].getName() + "/");
                    output.putNextEntry(entry);
                    addDirectoryToJar(files[i], output, prefix + "/" + files[i].getName(), listener);
                } else {
                    entry = new JarEntry(files[i].getName() + "/");
                    output.putNextEntry(entry);
                    addDirectoryToJar(files[i], output, files[i].getName(), listener);
                }
            } else {
                addFileToJar(files[i], output, prefix);
                if (listener != null) {
                    listener.propertyChange(new PropertyChangeEvent(directory, "fileAdded", null, null));
                }
            }
        }
    } catch (IOException e) {
        LOG.error("Error while adding directory '" + directory.getAbsolutePath() + "'", e);
        throw e;
    }
}

From source file:org.apache.sysml.utils.lite.BuildLite.java

/**
 * Write the additional resources to the jar.
 * //from www  . j a  v a  2 s  . co  m
 * @param jos
 *            output stream to the jar being written
 * @param numFilesWritten
 *            the number of files written to the jar so far
 * @throws IOException
 *             if an IOException occurs
 */
private static void writeAdditionalResourcesToJar(JarOutputStream jos, int numFilesWritten) throws IOException {
    for (String resource : additionalResources) {
        writeMessage(resource, ++numFilesWritten);
        JarEntry je = new JarEntry(resource);
        jos.putNextEntry(je);
        ClassLoader cl = BuildLite.class.getClassLoader();
        InputStream is = cl.getResourceAsStream(resource);
        byte[] bytes = IOUtils.toByteArray(is);
        jos.write(bytes);
    }
}

From source file:org.infoglue.deliver.portal.deploy.Deploy.java

/**
 * Prepare a portlet according to Pluto (switch web.xml)
 * //  w  ww .j a v a  2 s.com
 * @param file .war to prepare
 * @param tmp the resulting updated .war
 * @param appName name of application (context name)
 * @return the portlet application definition (portlet.xml)
 * @throws IOException
 */
public static PortletApplicationDefinition prepareArchive(File file, File tmp, String appName)
        throws IOException {
    PortletApplicationDefinitionImpl portletApp = null;
    try {
        Mapping pdmXml = new Mapping();
        try {
            URL url = Deploy.class.getResource("/" + PORTLET_MAPPING);
            pdmXml.loadMapping(url);
        } catch (Exception e) {
            throw new IOException("Failed to load mapping file " + PORTLET_MAPPING);
        }

        // Open the jar file.
        JarFile jar = new JarFile(file);

        // Extract and parse portlet.xml
        ZipEntry portletEntry = jar.getEntry(PORTLET_XML);
        if (portletEntry == null) {
            throw new IOException("Unable to find portlet.xml");
        }

        InputStream pisDebug = jar.getInputStream(portletEntry);
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = pisDebug.read()) > -1) {
            sb.append((char) i);
        }
        pisDebug.close();

        InputSource xmlSource = new InputSource(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
        DOMParser parser = new DOMParser();
        parser.parse(xmlSource);
        Document portletDocument = parser.getDocument();

        //InputStream pis = jar.getInputStream(portletEntry);
        //Document portletDocument = XmlParser.parsePortletXml(pis);
        //pis.close();
        InputStream pis = jar.getInputStream(portletEntry);

        ZipEntry webEntry = jar.getEntry(WEB_XML);
        InputStream wis = null;
        if (webEntry != null) {
            wis = jar.getInputStream(webEntry);
            /*  webDocument = XmlParser.parseWebXml(wis);
            wis.close();
            */
        }

        Unmarshaller unmarshaller = new Unmarshaller(pdmXml);
        unmarshaller.setWhitespacePreserve(true);
        unmarshaller.setIgnoreExtraElements(true);
        unmarshaller.setIgnoreExtraAttributes(true);

        portletApp = (PortletApplicationDefinitionImpl) unmarshaller.unmarshal(portletDocument);

        // refill structure with necessary information
        Vector structure = new Vector();
        structure.add(appName);
        structure.add(null);
        structure.add(null);
        portletApp.preBuild(structure);

        /*
        // now generate web part
        WebApplicationDefinitionImpl webApp = null;
        if (webDocument != null) {
        Unmarshaller unmarshallerWeb = new Unmarshaller(sdmXml);
                
        // modified by YCLI: START :: to ignore extra elements and
        // attributes
        unmarshallerWeb.setWhitespacePreserve(true);
        unmarshallerWeb.setIgnoreExtraElements(true);
        unmarshallerWeb.setIgnoreExtraAttributes(true);
        // modified by YCLI: END
                
        webApp = (WebApplicationDefinitionImpl) unmarshallerWeb.unmarshal(webDocument);
        } else {
        webApp = new WebApplicationDefinitionImpl();
        DisplayNameImpl dispName = new DisplayNameImpl();
        dispName.setDisplayName(appName);
        dispName.setLocale(Locale.ENGLISH);
        DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
        dispSet.add(dispName);
        webApp.setDisplayNames(dispSet);
        DescriptionImpl desc = new DescriptionImpl();
        desc.setDescription("Automated generated Application Wrapper");
        desc.setLocale(Locale.ENGLISH);
        DescriptionSetImpl descSet = new DescriptionSetImpl();
        descSet.add(desc);
        webApp.setDescriptions(descSet);
        }
                
        org.apache.pluto.om.ControllerFactory controllerFactory = new org.apache.pluto.portalImpl.om.ControllerFactoryImpl();
                
        ServletDefinitionListCtrl servletDefinitionSetCtrl = (ServletDefinitionListCtrl) controllerFactory
            .get(webApp.getServletDefinitionList());
        Collection servletMappings = webApp.getServletMappings();
                
        Iterator portlets = portletApp.getPortletDefinitionList().iterator();
        while (portlets.hasNext()) {
                
        PortletDefinition portlet = (PortletDefinition) portlets.next();
                
        // check if already exists
        ServletDefinition servlet = webApp.getServletDefinitionList()
                .get(portlet.getName());
        if (servlet != null) {
            ServletDefinitionCtrl _servletCtrl = (ServletDefinitionCtrl) controllerFactory
                    .get(servlet);
            _servletCtrl.setServletClass("org.apache.pluto.core.PortletServlet");
        } else {
            servlet = servletDefinitionSetCtrl.add(portlet.getName(),
                    "org.apache.pluto.core.PortletServlet");
        }
                
        ServletDefinitionCtrl servletCtrl = (ServletDefinitionCtrl) controllerFactory
                .get(servlet);
                
        DisplayNameImpl dispName = new DisplayNameImpl();
        dispName.setDisplayName(portlet.getName() + " Wrapper");
        dispName.setLocale(Locale.ENGLISH);
        DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
        dispSet.add(dispName);
        servletCtrl.setDisplayNames(dispSet);
        DescriptionImpl desc = new DescriptionImpl();
        desc.setDescription("Automated generated Portlet Wrapper");
        desc.setLocale(Locale.ENGLISH);
        DescriptionSetImpl descSet = new DescriptionSetImpl();
        descSet.add(desc);
        servletCtrl.setDescriptions(descSet);
        ParameterSet parameters = servlet.getInitParameterSet();
                
        ParameterSetCtrl parameterSetCtrl = (ParameterSetCtrl) controllerFactory
                .get(parameters);
                
        Parameter parameter1 = parameters.get("portlet-class");
        if (parameter1 == null) {
            parameterSetCtrl.add("portlet-class", portlet.getClassName());
        } else {
            ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter1);
            parameterCtrl.setValue(portlet.getClassName());
                
        }
        Parameter parameter2 = parameters.get("portlet-guid");
        if (parameter2 == null) {
            parameterSetCtrl.add("portlet-guid", portlet.getId().toString());
        } else {
            ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter2);
            parameterCtrl.setValue(portlet.getId().toString());
                
        }
                
        boolean found = false;
        Iterator mappings = servletMappings.iterator();
        while (mappings.hasNext()) {
            ServletMappingImpl servletMapping = (ServletMappingImpl) mappings.next();
            if (servletMapping.getServletName().equals(portlet.getName())) {
                found = true;
                servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_')
                        + "/*");
            }
        }
        if (!found) {
            ServletMappingImpl servletMapping = new ServletMappingImpl();
            servletMapping.setServletName(portlet.getName());
            servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_') + "/*");
            servletMappings.add(servletMapping);
        }
                
        SecurityRoleRefSet servletSecurityRoleRefs = ((ServletDefinitionImpl) servlet)
                .getInitSecurityRoleRefSet();
                
        SecurityRoleRefSetCtrl servletSecurityRoleRefSetCtrl = (SecurityRoleRefSetCtrl) controllerFactory
                .get(servletSecurityRoleRefs);
                
        SecurityRoleSet webAppSecurityRoles = webApp.getSecurityRoles();
                
        SecurityRoleRefSet portletSecurityRoleRefs = portlet.getInitSecurityRoleRefSet();
                
        Iterator p = portletSecurityRoleRefs.iterator();
        while (p.hasNext()) {
            SecurityRoleRef portletSecurityRoleRef = (SecurityRoleRef) p.next();
                
            if (portletSecurityRoleRef.getRoleLink() == null
                    && webAppSecurityRoles.get(portletSecurityRoleRef.getRoleName()) == null) {
                logger.info("Note: The web application has no security role defined which matches the role name \""
                                + portletSecurityRoleRef.getRoleName()
                                + "\" of the security-role-ref element defined for the wrapper-servlet with the name '"
                                + portlet.getName() + "'.");
                break;
            }
            SecurityRoleRef servletSecurityRoleRef = servletSecurityRoleRefs
                    .get(portletSecurityRoleRef.getRoleName());
            if (null != servletSecurityRoleRef) {
                logger.info("Note: Replaced already existing element of type <security-role-ref> with value \""
                                + portletSecurityRoleRef.getRoleName()
                                + "\" for subelement of type <role-name> for the wrapper-servlet with the name '"
                                + portlet.getName() + "'.");
                servletSecurityRoleRefSetCtrl.remove(servletSecurityRoleRef);
            }
            servletSecurityRoleRefSetCtrl.add(portletSecurityRoleRef);
        }
                
        }
        */

        /*
         * TODO is this necessary? TagDefinitionImpl portletTagLib = new
         * TagDefinitionImpl(); Collection taglibs =
         * webApp.getCastorTagDefinitions(); taglibs.add(portletTagLib);
         */

        // Duplicate jar-file with replaced web.xml
        FileOutputStream fos = new FileOutputStream(tmp);
        JarOutputStream tempJar = new JarOutputStream(fos);
        byte[] buffer = new byte[1024];
        int bytesRead;
        for (Enumeration entries = jar.entries(); entries.hasMoreElements();) {
            JarEntry entry = (JarEntry) entries.nextElement();
            JarEntry newEntry = new JarEntry(entry.getName());
            tempJar.putNextEntry(newEntry);

            if (entry.getName().equals(WEB_XML)) {
                // Swap web.xml
                /*
                log.debug("Swapping web.xml");
                OutputFormat of = new OutputFormat();
                of.setIndenting(true);
                of.setIndent(4); // 2-space indention
                of.setLineWidth(16384);
                of.setDoctype(Constants.WEB_PORTLET_PUBLIC_ID, Constants.WEB_PORTLET_DTD);
                        
                XMLSerializer serializer = new XMLSerializer(tempJar, of);
                Marshaller marshaller = new Marshaller(serializer.asDocumentHandler());
                marshaller.setMapping(sdmXml);
                marshaller.marshal(webApp);
                */

                PortletAppDescriptorService portletAppDescriptorService = new StreamPortletAppDescriptorServiceImpl(
                        appName, pis, null);
                File tmpf = File.createTempFile("infoglue-web-xml", null);
                WebAppDescriptorService webAppDescriptorService = new StreamWebAppDescriptorServiceImpl(appName,
                        wis, new FileOutputStream(tmpf));

                org.apache.pluto.driver.deploy.Deploy d = new org.apache.pluto.driver.deploy.Deploy(
                        webAppDescriptorService, portletAppDescriptorService);
                d.updateDescriptors();
                FileInputStream fis = new FileInputStream(tmpf);
                while ((bytesRead = fis.read(buffer)) != -1) {
                    tempJar.write(buffer, 0, bytesRead);
                }
                tmpf.delete();
            } else {
                InputStream entryStream = jar.getInputStream(entry);
                if (entryStream != null) {
                    while ((bytesRead = entryStream.read(buffer)) != -1) {
                        tempJar.write(buffer, 0, bytesRead);
                    }
                }
            }
        }
        tempJar.flush();
        tempJar.close();
        fos.flush();
        fos.close();
        /*
         * String strTo = dirDelim + "WEB-INF" + dirDelim + "tld" + dirDelim +
         * "portlet.tld"; String strFrom = "webapps" + dirDelim + strTo;
         * 
         * copy(strFrom, webAppsDir + webModule + strTo);
         */
    } catch (Exception e) {
        log.error("Failed to prepare archive", e);
        throw new IOException(e.getMessage());
    }

    return portletApp;
}

From source file:net.adamcin.oakpal.testing.TestPackageUtil.java

private static void add(final File root, final File source, final JarOutputStream target) throws IOException {
    if (root == null || source == null) {
        throw new IllegalArgumentException("Cannot add from a null file");
    }/* w w  w.j av a 2s .  c o  m*/
    if (!(source.getPath() + "/").startsWith(root.getPath() + "/")) {
        throw new IllegalArgumentException("source must be the same file or a child of root");
    }
    final String relPath;
    if (!root.getPath().equals(source.getPath())) {
        relPath = source.getPath().substring(root.getPath().length() + 1).replace(File.separator, "/");
    } else {
        relPath = "";
    }
    if (source.isDirectory()) {
        if (!relPath.isEmpty()) {
            String name = relPath;
            if (!name.endsWith("/")) {
                name += "/";
            }
            JarEntry entry = new JarEntry(name);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            target.closeEntry();
        }
        File[] children = source.listFiles();
        if (children != null) {
            for (File nestedFile : children) {
                add(root, nestedFile, target);
            }
        }
    } else {
        JarEntry entry = new JarEntry(relPath);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        try (InputStream in = new BufferedInputStream(new FileInputStream(source))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static void writeSignatureFile(byte[] sf, String signatureName, JarOutputStream jos)
        throws IOException {

    // Signature file entry
    JarEntry sfJarEntry = new JarEntry(
            MessageFormat.format(METAINF_FILE_LOCATION, signatureName, SIGNATURE_EXT).toUpperCase());
    jos.putNextEntry(sfJarEntry);

    // Write content
    ByteArrayInputStream bais = null;

    try {/*from ww w .j  a  v a  2 s .  com*/
        bais = new ByteArrayInputStream(sf);

        byte[] buffer = new byte[2048];
        int read = -1;

        while ((read = bais.read(buffer)) != -1) {
            jos.write(buffer, 0, read);
        }

        jos.closeEntry();
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

From source file:org.commonjava.indy.ftest.core.content.StoreAndVerifyJarViaDirectDownloadTest.java

@Test
public void storeFileThenDownloadAndVerifyContentViaDirectDownload() throws Exception {
    final String content = "This is a test: " + System.nanoTime();
    String entryName = "org/something/foo.class";

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JarOutputStream jarOut = new JarOutputStream(out);
    jarOut.putNextEntry(new JarEntry(entryName));
    jarOut.write(content.getBytes());//from ww  w .  ja  v  a2  s.  c o m
    jarOut.close();

    // Used to visually inspect the jars moving up...
    //        String userDir = System.getProperty( "user.home" );
    //        File dir = new File( userDir, "temp" );
    //        dir.mkdirs();
    //
    //        FileUtils.writeByteArrayToFile( new File( dir, name.getMethodName() + "-in.jar" ), out.toByteArray() );

    final InputStream stream = new ByteArrayInputStream(out.toByteArray());

    final String path = "/path/to/" + getClass().getSimpleName() + "-" + name.getMethodName() + ".jar";

    assertThat(client.content().exists(hosted, STORE, path), equalTo(false));

    client.content().store(hosted, STORE, path, stream);

    assertThat(client.content().exists(hosted, STORE, path), equalTo(true));

    final URL url = new URL(client.content().contentUrl(hosted, STORE, path));

    final InputStream is = url.openStream();

    byte[] result = IOUtils.toByteArray(is);
    is.close();

    assertThat(result, equalTo(out.toByteArray()));

    // ...and down
    //        FileUtils.writeByteArrayToFile( new File( dir, name.getMethodName() + "-out.jar" ), result );

    JarInputStream jarIn = new JarInputStream(new ByteArrayInputStream(result));
    JarEntry jarEntry = jarIn.getNextJarEntry();

    assertThat(jarEntry.getName(), equalTo(entryName));
    String contentResult = IOUtils.toString(jarIn);

    assertThat(contentResult, equalTo(content));
}

From source file:org.apache.hadoop.hbase.TestClassFinder.java

/**
 * Makes a jar out of some class files. Unfortunately it's very tedious.
 * @param filesInJar Files created via compileTestClass.
 * @return path to the resulting jar file.
 *//*from  w  ww .  ja v a 2 s .com*/
private static String packageAndLoadJar(FileAndPath... filesInJar) throws Exception {
    // First, write the bogus jar file.
    String path = basePath + "jar" + jarCounter.incrementAndGet() + ".jar";
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    FileOutputStream fos = new FileOutputStream(path);
    JarOutputStream jarOutputStream = new JarOutputStream(fos, manifest);
    // Directory entries for all packages have to be added explicitly for
    // resources to be findable via ClassLoader. Directory entries must end
    // with "/"; the initial one is expected to, also.
    Set<String> pathsInJar = new HashSet<String>();
    for (FileAndPath fileAndPath : filesInJar) {
        String pathToAdd = fileAndPath.path;
        while (pathsInJar.add(pathToAdd)) {
            int ix = pathToAdd.lastIndexOf('/', pathToAdd.length() - 2);
            if (ix < 0) {
                break;
            }
            pathToAdd = pathToAdd.substring(0, ix);
        }
    }
    for (String pathInJar : pathsInJar) {
        jarOutputStream.putNextEntry(new JarEntry(pathInJar));
        jarOutputStream.closeEntry();
    }
    for (FileAndPath fileAndPath : filesInJar) {
        File file = fileAndPath.file;
        jarOutputStream.putNextEntry(new JarEntry(fileAndPath.path + file.getName()));
        byte[] allBytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(allBytes);
        fis.close();
        jarOutputStream.write(allBytes);
        jarOutputStream.closeEntry();
    }
    jarOutputStream.close();
    fos.close();

    // Add the file to classpath.
    File jarFile = new File(path);
    assertTrue(jarFile.exists());
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
    method.setAccessible(true);
    method.invoke(urlClassLoader, new Object[] { jarFile.toURI().toURL() });
    return jarFile.getAbsolutePath();
}

From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java

/**
 * Convert a ScriptModule to its compiled equivalent ScriptArchive.
 * <p>//from www.  ja v a  2s  .  c  o  m
 * A jar script archive is created containing compiled bytecode
 * from a script module, as well as resources and other metadata from
 * the source script archive.
 * <p>
 * This involves serializing the class bytes of all the loaded classes in
 * the script module, as well as copying over all entries in the original
 * script archive, minus any that have excluded extensions. The module spec
 * of the source script archive is transferred as is to the target bytecode
 * archive.
 *
 * @param module the input script module containing loaded classes
 * @param jarPath the path to a destination JarScriptArchive.
 * @param excludeExtensions a set of extensions with which
 *        source script archive entries can be excluded.
 *
 * @throws Exception
 */
public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions)
        throws Exception {
    ScriptArchive sourceArchive = module.getSourceArchive();
    JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile()));
    try {
        // First copy all resources (excluding those with excluded extensions)
        // from the source script archive, into the target script archive
        for (String archiveEntry : sourceArchive.getArchiveEntryNames()) {
            URL entryUrl = sourceArchive.getEntry(archiveEntry);
            boolean skip = false;
            for (String extension : excludeExtensions) {
                if (entryUrl.toString().endsWith(extension)) {
                    skip = true;
                    break;
                }
            }

            if (skip)
                continue;

            InputStream entryStream = entryUrl.openStream();
            byte[] entryBytes = IOUtils.toByteArray(entryStream);
            entryStream.close();

            jarStream.putNextEntry(new ZipEntry(archiveEntry));
            jarStream.write(entryBytes);
            jarStream.closeEntry();
        }

        // Now copy all compiled / loaded classes from the script module.
        Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses();
        Iterator<Class<?>> iterator = loadedClasses.iterator();
        while (iterator.hasNext()) {
            Class<?> clazz = iterator.next();
            String classPath = clazz.getName().replace(".", "/") + ".class";
            URL resourceURL = module.getModuleClassLoader().getResource(classPath);
            if (resourceURL == null) {
                throw new Exception("Unable to find class resource for: " + clazz.getName());
            }

            InputStream resourceStream = resourceURL.openStream();
            jarStream.putNextEntry(new ZipEntry(classPath));
            byte[] classBytes = IOUtils.toByteArray(resourceStream);
            resourceStream.close();
            jarStream.write(classBytes);
            jarStream.closeEntry();
        }

        // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the
        // compiler plugin IDs list.
        ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec();
        ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId());
        newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds());
        newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID);
        newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata());
        newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies());

        // Serialize the modulespec with GSON and its default spec file name
        ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer();
        String json = specSerializer.serialize(newModuleSpecBuilder.build());
        jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName()));
        jarStream.write(json.getBytes(Charsets.UTF_8));
        jarStream.closeEntry();
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
}

From source file:com.glaf.core.util.ZipUtils.java

public static byte[] getZipBytes(Map<String, InputStream> dataMap) {
    byte[] bytes = null;
    try {//w w w .  j a  v  a  2 s. c  om
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        JarOutputStream jos = new JarOutputStream(bos);
        if (dataMap != null) {
            Set<Entry<String, InputStream>> entrySet = dataMap.entrySet();
            for (Entry<String, InputStream> entry : entrySet) {
                String name = entry.getKey();
                InputStream inputStream = entry.getValue();
                if (name != null && inputStream != null) {
                    BufferedInputStream bis = new BufferedInputStream(inputStream);
                    JarEntry jarEntry = new JarEntry(name);
                    jos.putNextEntry(jarEntry);

                    while ((len = bis.read(buf)) >= 0) {
                        jos.write(buf, 0, len);
                    }

                    bis.close();
                    jos.closeEntry();
                }
            }
        }
        jos.flush();
        jos.close();
        bos.flush();
        bos.close();
        bytes = baos.toByteArray();
        baos.close();
        return bytes;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.apache.brooklyn.rest.resources.BundleAndTypeResourcesTest.java

private static File createJar(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "jar");

    JarOutputStream zip = new JarOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        JarEntry ze = new JarEntry(entry.getKey());
        zip.putNextEntry(ze);
        zip.write(entry.getValue().getBytes());
    }/*  w ww.  j  av a  2 s .  c o m*/

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}