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) throws IOException 

Source Link

Document

Creates a new JarOutputStream with no manifest.

Usage

From source file:UnpackedJarFile.java

public static void copyToPackedJar(JarFile inputJar, File outputFile) throws IOException {
    if (inputJar.getClass() == JarFile.class) {
        // this is a plain old jar... nothign special
        copyFile(new File(inputJar.getName()), outputFile);
    } else if (inputJar instanceof NestedJarFile && ((NestedJarFile) inputJar).isPacked()) {
        NestedJarFile nestedJarFile = (NestedJarFile) inputJar;
        JarFile baseJar = nestedJarFile.getBaseJar();
        String basePath = nestedJarFile.getBasePath();
        if (baseJar instanceof UnpackedJarFile) {
            // our target jar is just a file in upacked jar (a plain old directory)... now
            // we just need to find where it is and copy it to the outptu
            copyFile(((UnpackedJarFile) baseJar).getFile(basePath), outputFile);
        } else {//from w w  w.j a v a  2s.  co  m
            // out target is just a plain old jar file directly accessabel from the file system
            copyFile(new File(baseJar.getName()), outputFile);
        }
    } else {
        // copy out the module contents to a standalone jar file (entry by entry)
        JarOutputStream out = null;
        try {
            out = new JarOutputStream(new FileOutputStream(outputFile));
            byte[] buffer = new byte[4096];
            Enumeration entries = inputJar.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                InputStream in = inputJar.getInputStream(entry);
                try {
                    out.putNextEntry(new ZipEntry(entry.getName()));
                    try {
                        int count;
                        while ((count = in.read(buffer)) > 0) {
                            out.write(buffer, 0, count);
                        }
                    } finally {
                        out.closeEntry();
                    }
                } finally {
                    close(in);
                }
            }
        } finally {
            close(out);
        }
    }
}

From source file:org.apache.pig.test.TestJobControlCompiler.java

/**
 * creates a jar containing a UDF not in the current classloader
 * @param jarFile the jar to create// www . ja  va  2s. co m
 * @return the name of the class created (in the default package)
 * @throws IOException
 * @throws FileNotFoundException
 */
private String createTestJar(File jarFile) throws IOException, FileNotFoundException {

    // creating the source .java file
    File javaFile = File.createTempFile("TestUDF", ".java");
    javaFile.deleteOnExit();
    String className = javaFile.getName().substring(0, javaFile.getName().lastIndexOf('.'));
    FileWriter fw = new FileWriter(javaFile);
    try {
        fw.write("import org.apache.pig.EvalFunc;\n");
        fw.write("import org.apache.pig.data.Tuple;\n");
        fw.write("import java.io.IOException;\n");
        fw.write("public class " + className + " extends EvalFunc<String> {\n");
        fw.write("  public String exec(Tuple input) throws IOException {\n");
        fw.write("    return \"test\";\n");
        fw.write("  }\n");
        fw.write("}\n");
    } finally {
        fw.close();
    }

    // compiling it
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjects(javaFile);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits1);
    task.call();

    // here is the compiled file
    File classFile = new File(javaFile.getParentFile(), className + ".class");
    Assert.assertTrue(classFile.exists());

    // putting it in the jar
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile));
    try {
        jos.putNextEntry(new ZipEntry(classFile.getName()));
        try {
            InputStream testClassContentIS = new FileInputStream(classFile);
            try {
                byte[] buffer = new byte[64000];
                int n;
                while ((n = testClassContentIS.read(buffer)) != -1) {
                    jos.write(buffer, 0, n);
                }
            } finally {
                testClassContentIS.close();
            }
        } finally {
            jos.closeEntry();
        }
    } finally {
        jos.close();
    }

    return className;
}

From source file:com.taobao.android.builder.tools.multidex.FastMultiDexer.java

@Override
public Collection<File> repackageJarList(Collection<File> files) throws IOException {

    List<String> mainDexList = getMainDexList(files);

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);//from   w  w  w.  j av  a 2s.c  om
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar);
        for (File folder : folderList) {
            jarMerger.addFolder(folder);
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, "fastmaindex.jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));
    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");
        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
            } else {
                copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
            }
        }
        jarFile.close();
        IOUtils.closeQuietly(jos);
    }
    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

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

/**
 * Prepare a portlet according to Pluto (switch web.xml)
 * /* w w w  .  j a v  a  2  s  . co  m*/
 * @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:com.izforge.izpack.installer.multiunpacker.MultiVolumeUnpackerTest.java

/**
 * Creates a {@link MultiVolumePackager}.
 *
 * @param baseDir      the base directory
 * @param installerJar the jar to create
 * @return a new packager//from  ww  w .  j  a  v a2  s.  com
 * @throws IOException for any I/O error
 */
private MultiVolumePackager createPackager(File baseDir, File installerJar) throws IOException {
    Properties properties = new Properties();
    PackagerListener packagerListener = Mockito.mock(PackagerListener.class);
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(installerJar));
    MergeManager mergeManager = Mockito.mock(MergeManager.class);
    CompilerPathResolver resolver = Mockito.mock(CompilerPathResolver.class);
    MergeableResolver mergeableResolver = Mockito.mock(MergeableResolver.class);
    CompilerData data = new CompilerData(null, baseDir.getPath(), installerJar.getPath(), true);
    RulesEngine rulesEngine = Mockito.mock(RulesEngine.class);
    MultiVolumePackager packager = new MultiVolumePackager(properties, packagerListener, jar, mergeManager,
            resolver, mergeableResolver, data, rulesEngine);
    packager.setInfo(new Info());
    return packager;
}

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Abre el jar para escribir el nuevo archivo class compilado, elresto de archivos los copia tal cual
 *
 * @throws IOException//from   w w w. ja va 2  s  .co  m
 */
protected void writeNewJar() throws IOException {
    // buffer para leer datos de los archivos
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.oaiApiJarJarFile.getName()).getParentFile();
    // nombre del jar
    String name = oaiApiJarWorkFile.getName();
    String extension = name.substring(name.lastIndexOf('.'));
    name = name.substring(0, name.lastIndexOf('.'));
    // archivo temporal del nuevo jar
    File newJarFile = File.createTempFile(name, extension, jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura del nuevo jar
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    // recorrer todos los archivos del jar menos el crosswalk para replicarlos
    try {
        Enumeration<JarEntry> entries = oaiApiJarJarFile.entries();
        while (entries.hasMoreElements()) {
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            if (!entry.getName().equals(edmCrossWalkClass)) {
                JarEntry entryOld = new JarEntry(entry);
                entryOld.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryOld);
                InputStream intputStream = oaiApiJarJarFile.getInputStream(entry);
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // aadir class compilado
        addClass2Jar(jarOutputStream);
        // cerrar jar original
        oaiApiJarJarFile.close();
        // borrar jar original
        oaiApiJarWorkFile.delete();
        // cambiar jar original por nuevo
        try {
            /*if (newJarFile.renameTo(oaiApiJarWorkFile) && oaiApiJarWorkFile.setExecutable(true, true)) {
            oaiApiJarWorkFile = new File(oaiApiJarName);
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, oaiApiJarWorkFile);
            oaiApiJarWorkFile.setExecutable(true, true);
            oaiApiJarWorkFile = new File(oaiApiJarName);
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
 * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
 * the archive will not be signed.//from  w ww. jav  a  2s. co  m
 *
 * @param out         the {@link OutputStream} where to write the Jar archive.
 * @param key         the {@link PrivateKey} used to sign the archive, or <code>null</code>.
 * @param certificate the {@link X509Certificate} used to sign the archive, or
 *                    <code>null</code>.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public LocalSignedJarBuilder(@NonNull OutputStream out, @Nullable PrivateKey key,
        @Nullable X509Certificate certificate, @Nullable String builtBy, @Nullable String createdBy,
        @Nullable String signFile) throws IOException, NoSuchAlgorithmException {
    mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
    mOutputJar.setLevel(9);
    mKey = key;
    mCertificate = certificate;
    mSignFile = signFile;

    if (mKey != null && mCertificate != null) {
        mManifest = new Manifest();
        Attributes main = mManifest.getMainAttributes();
        main.putValue("Manifest-Version", "1.0");
        if (builtBy != null) {
            main.putValue("Built-By", builtBy);
        }
        if (createdBy != null) {
            main.putValue("Created-By", createdBy);
        }

        mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    }
}

From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java

private void addMetaInf(File outputFile, ArrayList<File> jarFiles) throws IOException {
    File tmp = File.createTempFile(outputFile.getName(), ".add", outputFile.getParentFile());

    FileOutputStream fos = new FileOutputStream(tmp);
    JarOutputStream zos = new JarOutputStream(fos);
    Set<String> entries = new HashSet<String>();

    updateWithMetaInf(zos, outputFile, entries, false);

    for (File f : jarFiles) {
        updateWithMetaInf(zos, f, entries, true);
    }//from w w w .  j a va 2 s . c om

    if (transformers != null) {
        for (ResourceTransformer transformer : transformers) {
            if (transformer.hasTransformedResource()) {
                transformer.modifyOutputStream(zos);
            }
        }
    }

    zos.close();

    outputFile.delete();

    if (!tmp.renameTo(outputFile)) {
        throw new IOException(String.format("Cannot rename %s to %s", tmp, outputFile.getName()));
    }
}

From source file:org.atricore.josso.tooling.wrapper.InstallCommand.java

private void createJar(File outFile, String resource) throws Exception {
    if (!outFile.exists()) {
        System.out.println(Ansi.ansi().a("Creating file: ").a(Ansi.Attribute.INTENSITY_BOLD)
                .a(outFile.getPath()).a(Ansi.Attribute.RESET).toString());
        InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
        if (is == null) {
            throw new IllegalStateException("Resource " + resource + " not found!");
        }/*from   w w w.java 2  s  .co  m*/
        try {
            JarOutputStream jar = new JarOutputStream(new FileOutputStream(outFile));
            int idx = resource.indexOf('/');
            while (idx > 0) {
                jar.putNextEntry(new ZipEntry(resource.substring(0, idx)));
                jar.closeEntry();
                idx = resource.indexOf('/', idx + 1);
            }
            jar.putNextEntry(new ZipEntry(resource));
            int c;
            while ((c = is.read()) >= 0) {
                jar.write(c);
            }
            jar.closeEntry();
            jar.close();
        } finally {
            safeClose(is);
        }
    }
}

From source file:com.taobao.android.builder.tools.classinject.CodeInjectByJavassist.java

/**
 * jar?/*from  w  w w .ja v  a2  s . c o  m*/
 *
 * @param inJar
 * @param outJar
 * @throws IOException
 * @throws NotFoundException
 * @throws CannotCompileException
 */
public static List<String> inject(ClassPool pool, File inJar, File outJar, InjectParam injectParam)
        throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    JarFile jarFile = newJarFile(inJar);

    outJar.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(fileOutputStream));
    Enumeration<JarEntry> jarFileEntries = jarFile.entries();
    JarEntry jarEntry = null;
    while (jarFileEntries.hasMoreElements()) {
        jarEntry = jarFileEntries.nextElement();
        String name = jarEntry.getName();
        String className = StringUtils.replace(name, File.separator, "/");
        className = StringUtils.replace(className, "/", ".");
        className = StringUtils.substring(className, 0, className.length() - 6);
        if (!StringUtils.endsWithIgnoreCase(name, ".class")) {
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            copyStreamToJar(inputStream, jos, name, jarEntry.getTime(), jarEntry);
            IOUtils.closeQuietly(inputStream);
        } else {
            byte[] codes;

            codes = inject(pool, className, injectParam);
            InputStream classInstream = new ByteArrayInputStream(codes);
            copyStreamToJar(classInstream, jos, name, jarEntry.getTime(), jarEntry);

        }
    }
    jarFile.close();
    IOUtils.closeQuietly(jos);
    return errorFiles;
}