Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream.

Prototype

public ZipArchiveOutputStream(File file) throws IOException 

Source Link

Document

Creates a new ZIP OutputStream writing to a File.

Usage

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractWeirdIndex() throws InterruptedException, IOException {

    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/baz"));
        zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length);
        zip.closeArchiveEntry();//from   w w w.  j a  v  a2s. c  o m
        zip.putArchiveEntry(new ZipArchiveEntry("foo/"));
        zip.closeArchiveEntry();
        zip.putArchiveEntry(new ZipArchiveEntry("qux/"));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo")));
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar/baz")));

    assertEquals(ImmutableList.of(extractFolder.resolve("foo/bar/baz")), result);
}

From source file:cz.cuni.mff.ufal.AllBitstreamZipArchiveReader.java

@Override
public void generate() throws IOException, SAXException, ProcessingException {

    if (redirect != NO_REDIRECTION) {
        return;//  ww w  . j a  va  2s . c o m
    }

    String name = item.getName() + ".zip";

    try {

        // first write everything to a temp file
        String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
        String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString()
                + ".zip";
        OutputStream outStream = new FileOutputStream(new File(fn));
        ZipArchiveOutputStream zip = new ZipArchiveOutputStream(outStream);
        zip.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zip.setLevel(Deflater.NO_COMPRESSION);
        ConcurrentMap<String, AtomicInteger> usedFilenames = new ConcurrentHashMap<String, AtomicInteger>();

        Bundle[] originals = item.getBundles("ORIGINAL");
        if (needsZip64) {
            zip.setUseZip64(Zip64Mode.Always);
        }
        for (Bundle original : originals) {
            Bitstream[] bss = original.getBitstreams();
            for (Bitstream bitstream : bss) {
                String filename = bitstream.getName();
                String uniqueName = createUniqueFilename(filename, usedFilenames);
                ZipArchiveEntry ze = new ZipArchiveEntry(uniqueName);
                zip.putArchiveEntry(ze);
                InputStream is = bitstream.retrieve();
                Utils.copy(is, zip);
                zip.closeArchiveEntry();
                is.close();
            }
        }
        zip.close();

        File file = new File(fn);
        zipFileSize = file.length();

        zipInputStream = new TempFileInputStream(file);
    } catch (AuthorizeException e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("You do not have permissions to access one or more files.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("Could not create ZIP, please download the files one by one. "
                + "The error has been stored and will be solved by our technical team.");
    }

    // Log download statistics
    for (int bitstreamID : bitstreamIDs) {
        DSpaceApi.updateFileDownloadStatistics(userID, bitstreamID);
    }

    response.setDateHeader("Last-Modified", item.getLastModified().getTime());

    // Try and make the download file name formated for each browser.
    try {
        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.contains("MSIE")) {
            name = URLEncoder.encode(name, "UTF8");
        } else if (agent != null && agent.contains("Mozilla")) {
            name = MimeUtility.encodeText(name, "UTF8", "B");
        }
    } catch (UnsupportedEncodingException see) {
        name = "item_" + item.getID() + ".zip";
    }
    response.setHeader("Content-Disposition", "attachment;filename=" + name);

    byte[] buffer = new byte[BUFFER_SIZE];
    int length = -1;

    try {
        response.setHeader("Content-Length", String.valueOf(this.zipFileSize));

        while ((length = this.zipInputStream.read(buffer)) > -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
    } finally {
        try {
            if (this.zipInputStream != null) {
                this.zipInputStream.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Closing the stream threw an IOException but do we want this to propagate up to Cocoon?
            // No point since the user has already got the file contents.
            log.warn("Caught IO exception when closing a stream: " + ioe.getMessage());
        }
    }

}

From source file:com.haulmont.cuba.core.app.FoldersServiceBean.java

@Override
public byte[] exportFolder(Folder folder) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    String xml = createXStream().toXML(folder);
    byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
    ArchiveEntry zipEntryDesign = newStoredEntry("folder.xml", xmlBytes);
    zipOutputStream.putArchiveEntry(zipEntryDesign);
    zipOutputStream.write(xmlBytes);/*ww w  . ja  v  a 2 s  . c  om*/
    try {
        zipOutputStream.closeArchiveEntry();
    } catch (Exception ex) {
        throw new RuntimeException(
                String.format("Exception occurred while exporting folder %s.", folder.getName()));
    }

    zipOutputStream.close();
    return byteArrayOutputStream.toByteArray();
}

From source file:io.selendroid.builder.SelendroidServerBuilder.java

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();
    File tempdir = new File(FileUtils.getTempDirectoryPath() + File.separatorChar + targetPackageName
            + System.currentTimeMillis());

    if (!tempdir.exists()) {
        tempdir.mkdirs();/*from   w  w w .  j a  v  a2 s .  com*/
    }

    File customizedManifest = new File(tempdir, "AndroidManifest.xml");
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk", false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(
            new File(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk"));
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = new File(tempdir.getAbsolutePath() + "selendroid-server.apk");
    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

From source file:com.eucalyptus.www.X509Download.java

private static byte[] getX509Zip(User u) throws Exception {
    X509Certificate cloudCert = null;
    final X509Certificate x509;
    String userAccessKey = null;/*from  ww  w  . ja  v  a2s.  com*/
    String userSecretKey = null;
    KeyPair keyPair = null;
    try {
        for (AccessKey k : u.getKeys()) {
            if (k.isActive()) {
                userAccessKey = k.getAccessKey();
                userSecretKey = k.getSecretKey();
            }
        }
        if (userAccessKey == null) {
            AccessKey k = u.createKey();
            userAccessKey = k.getAccessKey();
            userSecretKey = k.getSecretKey();
        }
        keyPair = Certs.generateKeyPair();
        x509 = Certs.generateCertificate(keyPair, u.getName());
        x509.checkValidity();
        u.addCertificate(x509);
        cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate();
    } catch (Exception e) {
        LOG.fatal(e, e);
        throw e;
    }
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut);
    ZipArchiveEntry entry = null;
    String fingerPrint = Certs.getFingerPrint(keyPair.getPublic());
    if (fingerPrint != null) {
        String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-"
                + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8);

        zipOut.setComment("To setup the environment run: source /path/to/eucarc");
        StringBuilder sb = new StringBuilder();
        //TODO:GRZE:FIXME velocity
        String userNumber = u.getAccount().getAccountNumber();
        sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)");
        final Optional<String> computeUrl = remotePublicify(Compute.class);
        if (computeUrl.isPresent()) {
            sb.append(entryFor("EC2_URL", null, computeUrl));
        } else {
            sb.append("\necho WARN:  Eucalyptus URL is not configured. >&2");
            ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class);
            ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(),
                    Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort());
            sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig));
        }

        sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. "
                + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. "
                + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage",
                remotePublicify(ObjectStorage.class)));
        sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class)));
        sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class)));
        sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.",
                remotePublicify(AutoScaling.class)));
        sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class)));
        sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.",
                remotePublicify(CloudWatch.class)));
        sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.",
                remotePublicify(LoadBalancing.class)));
        sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL);
        sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem");
        sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem");
        sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts");
        sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem");
        sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'");
        sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'");
        sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'");
        sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'");
        sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'");
        sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc");
        sb.append("\nexport EC2_USER_ID='" + userNumber + "'");
        sb.append(
                "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\"");
        sb.append(
                "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\"");
        sb.append("\n");
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc"));
        entry.setUnixMode(0600);
        zipOut.write(sb.toString().getBytes("UTF-8"));
        zipOut.closeArchiveEntry();

        sb = new StringBuilder();
        sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n');
        sb.append("AWSSecretKey=").append(userSecretKey);
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc"));
        entry.setUnixMode(0600);
        zipOut.write(sb.toString().getBytes("UTF-8"));
        zipOut.closeArchiveEntry();

        /** write the private key to the zip stream **/
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem"));
        entry.setUnixMode(0600);
        zipOut.write(PEMFiles.getBytes(cloudCert));
        zipOut.closeArchiveEntry();

        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts"));
        entry.setUnixMode(0600);
        KeyStore tempKs = KeyStore.getInstance("jks");
        tempKs.load(null);
        tempKs.setCertificateEntry("eucalyptus", cloudCert);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        tempKs.store(bos, "changeit".toCharArray());
        zipOut.write(bos.toByteArray());
        zipOut.closeArchiveEntry();

        /** write the private key to the zip stream **/
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem"));
        entry.setUnixMode(0600);
        zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY",
                Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate())));
        zipOut.closeArchiveEntry();

        /** write the X509 certificate to the zip stream **/
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem"));
        entry.setUnixMode(0600);
        zipOut.write(PEMFiles.getBytes(x509));
        zipOut.closeArchiveEntry();
    }
    /** close the zip output stream and return the bytes **/
    zipOut.close();
    return byteOut.toByteArray();
}

From source file:io.github.jeremgamer.maintenance.Maintenance.java

public void backupProcess(CommandSender sender) {

    Calendar cal = Calendar.getInstance();
    DateFormat dateFormat = new SimpleDateFormat("yyyy MM dd - HH mm ss");
    String zipFile = new File("").getAbsolutePath() + "/backups/" + dateFormat.format(cal.getTime()) + ".zip";
    File zip = new File(zipFile);
    String srcDir = new File("").getAbsolutePath();

    try {//from   w  ww  . ja v a  2  s .co m

        try {
            zip.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File dir = new File(srcDir);

        List<File> filesList = (List<File>) FileUtils.listFilesAndDirs(dir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        File[] files = filesList.toArray(new File[filesList.size()]);

        OutputStream out = new FileOutputStream(zip);
        ArchiveOutputStream zipOutput = new ZipArchiveOutputStream(out);
        String filePath;

        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {

            } else if (files[i].getAbsolutePath().contains(new File("").getAbsolutePath() + "\\backups\\")) {

            } else {

                filePath = files[i].getAbsolutePath().substring(srcDir.length() + 1);

                try {
                    ZipArchiveEntry entry = new ZipArchiveEntry(filePath);
                    entry.setSize(new File(files[i].getAbsolutePath()).length());
                    zipOutput.putArchiveEntry(entry);
                    IOUtils.copy(new FileInputStream(files[i].getAbsolutePath()), zipOutput);
                    zipOutput.closeArchiveEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        zipOutput.finish();
        zipOutput.close();
        out.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (IllegalArgumentException iae) {
        iae.printStackTrace();
    }

    sender.sendMessage(getConfig().getString("backupSuccess").replaceAll("&", ""));
    getLogger().info("Backup success!");
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testNonCanonicalPaths() throws InterruptedException, IOException {
    String names[] = { "foo/./", "foo/./bar/", "foo/./bar/baz.cpp", "foo/./bar/baz.h", };

    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        for (String name : names) {
            zip.putArchiveEntry(new ZipArchiveEntry(name));
            zip.closeArchiveEntry();//  w  w w.jav a 2 s .c  om
        }
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    for (String name : names) {
        assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name)));
    }
    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    for (String name : names) {
        assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name)));
    }
}

From source file:com.iisigroup.cap.log.TimeFolderSizeRollingFileAppender.java

public void zipFiles(List<String> fileList, String destUrl) throws IOException {

    FileUtils.forceMkdir(new File(FilenameUtils.getFullPathNoEndSeparator(destUrl)));
    BufferedInputStream origin = null;
    FileOutputStream fos = null;/*w w  w.j  av  a 2s .  c om*/
    BufferedOutputStream bos = null;
    ZipArchiveOutputStream out = null;
    byte data[] = new byte[BUFFER];
    try {
        fos = new FileOutputStream(destUrl);
        bos = new BufferedOutputStream(fos);
        out = new ZipArchiveOutputStream(bos);

        for (String fName : fileList) {
            File file = new File(fName);
            FileInputStream fi = new FileInputStream(file);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipArchiveEntry entry = new ZipArchiveEntry(file.getName());
            out.putArchiveEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            out.closeArchiveEntry();
            fi.close();
            origin.close();
        }

    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
        if (origin != null) {
            try {
                origin.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:io.selendroid.standalone.builder.SelendroidServerBuilder.java

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();

    File tmpDir = Files.createTempDir();
    if (deleteTmpFiles()) {
        tmpDir.deleteOnExit();//from  ww  w  . j  av a 2s.co  m
    }

    File customizedManifest = new File(tmpDir, "AndroidManifest.xml");
    if (deleteTmpFiles()) {
        customizedManifest.deleteOnExit();
    }
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    File manifestApkFile = File.createTempFile("manifest", ".apk");
    if (deleteTmpFiles()) {
        manifestApkFile.deleteOnExit();
    }

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(manifestApkFile.getAbsolutePath(), false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(manifestApkFile);
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = File.createTempFile("selendroid-server", ".apk");
    if (deleteTmpFiles()) {
        finalSelendroidServerFile.deleteOnExit();
    }

    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

From source file:com.cloudbees.jenkins.support.SupportPlugin.java

public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException {
    StringBuilder manifest = new StringBuilder();
    StringWriter errors = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errors);
    appendManifestHeader(manifest);//from   w  w w  .j ava 2s  . com
    List<Content> contents = appendManifestContents(manifest, errorWriter, components);
    contents.add(new StringContent("manifest.md", manifest.toString()));
    try {
        try (BulkChange change = new BulkChange(ContentMappings.get());
                ZipArchiveOutputStream binaryOut = new ZipArchiveOutputStream(
                        new BufferedOutputStream(outputStream, 16384))) {
            Optional<ContentFilter> maybeFilter = getContentFilter();
            Optional<FilteredOutputStream> maybeFilteredOut = maybeFilter
                    .map(filter -> new FilteredOutputStream(binaryOut, filter));
            OutputStream textOut = maybeFilteredOut.map(OutputStream.class::cast).orElse(binaryOut);
            OutputStreamSelector selector = new OutputStreamSelector(() -> binaryOut, () -> textOut);
            IgnoreCloseOutputStream unfilteredOut = new IgnoreCloseOutputStream(binaryOut);
            IgnoreCloseOutputStream filteredOut = new IgnoreCloseOutputStream(selector);
            for (Content content : contents) {
                if (content == null) {
                    continue;
                }
                final String name = maybeFilter.map(filter -> filter.filter(content.getName()))
                        .orElseGet(content::getName);
                final ZipArchiveEntry entry = new ZipArchiveEntry(name);
                entry.setTime(content.getTime());
                try {
                    binaryOut.putArchiveEntry(entry);
                    binaryOut.flush();
                    OutputStream out = content.shouldBeFiltered() ? filteredOut : unfilteredOut;
                    if (content instanceof PrefilteredContent && maybeFilter.isPresent()) {
                        ((PrefilteredContent) content).writeTo(out, maybeFilter.get());
                    } else {
                        content.writeTo(out);
                    }
                    out.flush();
                } catch (Throwable e) {
                    String msg = "Could not attach ''" + name + "'' to support bundle";
                    logger.log(Level.WARNING, msg, e);
                    errorWriter.println(msg);
                    errorWriter
                            .println("-----------------------------------------------------------------------");
                    errorWriter.println();
                    SupportLogFormatter.printStackTrace(e, errorWriter);
                    errorWriter.println();
                } finally {
                    maybeFilteredOut.ifPresent(FilteredOutputStream::reset);
                    selector.reset();
                    binaryOut.closeArchiveEntry();
                }
            }
            errorWriter.close();
            String errorContent = errors.toString();
            if (StringUtils.isNotBlank(errorContent)) {
                try {
                    binaryOut.putArchiveEntry(new ZipArchiveEntry("manifest/errors.txt"));
                    textOut.write(errorContent.getBytes(StandardCharsets.UTF_8));
                    textOut.flush();
                    binaryOut.closeArchiveEntry();
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Could not write manifest/errors.txt to zip archive", e);
                }
            }
            binaryOut.flush();
            change.commit();
        }
    } finally {
        outputStream.flush();
    }
}