Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry setUnixMode

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

Introduction

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

Prototype

public void setUnixMode(int mode) 

Source Link

Document

Sets Unix permissions in a way that is understood by Info-Zip's unzip command.

Usage

From source file:com.google.jenkins.plugins.persistentmaster.volume.zip.ZipCreator.java

private void copyDirectory(String filenameInZip) throws IOException {
    logger.finer("Adding directory: " + filenameInZip);
    // entries ending in / indicate a directory
    ZipArchiveEntry entry = new ZipArchiveEntry(filenameInZip + "/");
    // in addition, set the unix directory flag
    entry.setUnixMode(entry.getUnixMode() | UnixStat.DIR_FLAG);
    zipStream.putArchiveEntry(entry);// w ww . jav  a 2s.com
    zipStream.closeArchiveEntry();
}

From source file:com.gitblit.servlet.PtServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w w w. ja v  a  2 s. c o m*/
        response.setContentType("application/octet-stream");
        response.setDateHeader("Last-Modified", lastModified);
        response.setHeader("Cache-Control", "none");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        boolean windows = false;
        try {
            String useragent = request.getHeader("user-agent").toString();
            windows = useragent.toLowerCase().contains("windows");
        } catch (Exception e) {
        }

        byte[] pyBytes;
        File file = runtimeManager.getFileOrFolder("tickets.pt", "${baseFolder}/pt.py");
        if (file.exists()) {
            // custom script
            pyBytes = readAll(new FileInputStream(file));
        } else {
            // default script
            pyBytes = readAll(getClass().getResourceAsStream("/pt.py"));
        }

        if (windows) {
            // windows: download zip file with pt.py and pt.cmd
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.zip\"");

            OutputStream os = response.getOutputStream();
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);

            // add the Python script
            ZipArchiveEntry pyEntry = new ZipArchiveEntry("pt.py");
            pyEntry.setSize(pyBytes.length);
            pyEntry.setUnixMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setTime(lastModified);
            zos.putArchiveEntry(pyEntry);
            zos.write(pyBytes);
            zos.closeArchiveEntry();

            // add a Python launch cmd file
            byte[] cmdBytes = readAll(getClass().getResourceAsStream("/pt.cmd"));
            ZipArchiveEntry cmdEntry = new ZipArchiveEntry("pt.cmd");
            cmdEntry.setSize(cmdBytes.length);
            cmdEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            cmdEntry.setTime(lastModified);
            zos.putArchiveEntry(cmdEntry);
            zos.write(cmdBytes);
            zos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            ZipArchiveEntry txtEntry = new ZipArchiveEntry("readme.txt");
            txtEntry.setSize(txtBytes.length);
            txtEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setTime(lastModified);
            zos.putArchiveEntry(txtEntry);
            zos.write(txtBytes);
            zos.closeArchiveEntry();

            // cleanup
            zos.finish();
            zos.close();
            os.flush();
        } else {
            // unix: download a tar.gz file with pt.py set with execute permissions
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.tar.gz\"");

            OutputStream os = response.getOutputStream();
            CompressorOutputStream cos = new CompressorStreamFactory()
                    .createCompressorOutputStream(CompressorStreamFactory.GZIP, os);
            TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
            tos.setAddPaxHeadersForNonAsciiNames(true);
            tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);

            // add the Python script
            TarArchiveEntry pyEntry = new TarArchiveEntry("pt");
            pyEntry.setMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setModTime(lastModified);
            pyEntry.setSize(pyBytes.length);
            tos.putArchiveEntry(pyEntry);
            tos.write(pyBytes);
            tos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            TarArchiveEntry txtEntry = new TarArchiveEntry("README");
            txtEntry.setMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setModTime(lastModified);
            txtEntry.setSize(txtBytes.length);
            tos.putArchiveEntry(txtEntry);
            tos.write(txtBytes);
            tos.closeArchiveEntry();

            // cleanup
            tos.finish();
            tos.close();
            cos.close();
            os.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

@Test
public void testExtractSymlink() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);
        zip.putArchiveEntry(entry);/*www  . ja v a 2s .c  o  m*/
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

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

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

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    long time = ZipConstants.getFakeTime() / 1000 * 1000;

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("test.exe");
        entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        entry.setSize(DUMMY_FILE_CONTENTS.length);
        entry.setMethod(ZipEntry.STORED);
        entry.setTime(time);/* w ww . j a  va 2 s .  c  o m*/
        zip.putArchiveEntry(entry);
        zip.write(DUMMY_FILE_CONTENTS);
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE);
    Path exe = extractFolder.toAbsolutePath().resolve("test.exe");
    assertTrue(Files.exists(exe));
    assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time));
    assertTrue(Files.isExecutable(exe));
    assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result);
}

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

@Test
public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);

        // Mark the file as being executable.
        Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE);

        long externalAttributes = entry.getExternalAttributes()
                + (MorePosixFilePermissions.toMode(filePermissions) << 16);
        entry.setExternalAttributes(externalAttributes);

        zip.putArchiveEntry(entry);/*from   w w w  .  j  a va 2 s  .  co m*/
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

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

@Test
public void testStripsPrefixAndIgnoresSiblings() throws IOException {
    byte[] bazDotSh = "echo \"baz.sh\"\n".getBytes(Charsets.UTF_8);
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        zip.putArchiveEntry(new ZipArchiveEntry("foo"));
        zip.closeArchiveEntry();/*from  www . j  a  v a 2  s.c o m*/
        zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/baz.txt"));
        zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length);
        zip.closeArchiveEntry();

        ZipArchiveEntry exeEntry = new ZipArchiveEntry("foo/bar/baz.sh");
        exeEntry.setUnixMode(
                (int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        exeEntry.setMethod(ZipEntry.STORED);
        exeEntry.setSize(bazDotSh.length);
        zip.putArchiveEntry(exeEntry);
        zip.write(bazDotSh);

        zip.closeArchiveEntry();
        zip.putArchiveEntry(new ZipArchiveEntry("sibling"));
        zip.closeArchiveEntry();
        zip.putArchiveEntry(new ZipArchiveEntry("sibling/some/dir/and/file.txt"));
        zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length);
        zip.closeArchiveEntry();
    }

    Path extractFolder = Paths.get("output_dir", "nested");

    ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmpFolder.getRoot());

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(zipFile, filesystem, extractFolder,
            Optional.of(Paths.get("foo")), ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);

    assertFalse(filesystem.isDirectory(extractFolder.resolve("sibling")));
    assertFalse(filesystem.isDirectory(extractFolder.resolve("foo")));
    assertFalse(filesystem.isDirectory(extractFolder.resolve("some")));

    Path bazDotTxtPath = extractFolder.resolve("bar").resolve("baz.txt");
    Path bazDotShPath = extractFolder.resolve("bar").resolve("baz.sh");

    assertTrue(filesystem.isDirectory(extractFolder.resolve("bar")));
    assertTrue(filesystem.isFile(bazDotTxtPath));
    assertTrue(filesystem.isFile(bazDotShPath));
    assertTrue(filesystem.isExecutable(bazDotShPath));
    assertEquals(new String(bazDotSh), filesystem.readFileIfItExists(bazDotShPath).get());
    assertEquals(new String(DUMMY_FILE_CONTENTS), filesystem.readFileIfItExists(bazDotTxtPath).get());
}

From source file:com.mulesoft.jockey.maven.GenerateMojo.java

private void copyArchiveFile(File file, ArchiveOutputStream os, boolean zipFile) throws IOException {
    if (file.isDirectory()) {
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                copyArchiveFile(child, os, zipFile);
            }/*from www.  ja v a2 s. c  o m*/
        }
    } else {
        String relativePath = file.getAbsolutePath();
        relativePath = relativePath.substring(new File(buildDirectory).getAbsolutePath().length() + 1);
        relativePath = relativePath.replaceAll("\\\\", "/");

        if (zipFile) {
            ZipArchiveEntry entry = new ZipArchiveEntry(relativePath);

            os.putArchiveEntry(entry);
            if (isScript(file)) {
                entry.setUnixMode(EXECUTABLE_MODE);
            }
        } else {
            TarArchiveEntry entry = new TarArchiveEntry(relativePath);
            if (isScript(file)) {
                entry.setMode(EXECUTABLE_MODE);
            }
            entry.setSize(file.length());
            os.putArchiveEntry(entry);
        }

        IOUtils.copy(new FileInputStream(file), os);
        os.closeArchiveEntry();
    }
}

From source file:com.android.repository.util.InstallerUtilTest.java

public void testUnzip() throws Exception {
    if (new MockFileOp().isWindows()) {
        // can't run on windows.
        return;/*w w w.java2 s . c om*/
    }
    // zip needs a real file, so no MockFileOp for us.
    FileOp fop = FileOpUtils.create();

    Path root = Files.createTempDirectory("InstallerUtilTest");
    Path outRoot = Files.createTempDirectory("InstallerUtilTest");
    try {
        Path file1 = root.resolve("foo");
        Files.write(file1, "content".getBytes());
        Path dir1 = root.resolve("bar");
        Files.createDirectories(dir1);
        Path file2 = dir1.resolve("baz");
        Files.write(file2, "content2".getBytes());
        Files.createSymbolicLink(root.resolve("link1"), dir1);
        Files.createSymbolicLink(root.resolve("link2"), file2);

        Path outZip = outRoot.resolve("out.zip");
        try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(outZip.toFile());
                Stream<Path> listing = Files.walk(root)) {
            listing.forEach(path -> {
                try {
                    ZipArchiveEntry archiveEntry = (ZipArchiveEntry) out.createArchiveEntry(path.toFile(),
                            root.relativize(path).toString());
                    out.putArchiveEntry(archiveEntry);
                    if (Files.isSymbolicLink(path)) {
                        archiveEntry.setUnixMode(UnixStat.LINK_FLAG | archiveEntry.getUnixMode());
                        out.write(path.getParent().relativize(Files.readSymbolicLink(path)).toString()
                                .getBytes());
                    } else if (!Files.isDirectory(path)) {
                        out.write(Files.readAllBytes(path));
                    }
                    out.closeArchiveEntry();
                } catch (Exception e) {
                    fail();
                }
            });
        }
        Path unzipped = outRoot.resolve("unzipped");
        Files.createDirectories(unzipped);
        InstallerUtil.unzip(outZip.toFile(), unzipped.toFile(), fop, 1, new FakeProgressIndicator());
        assertEquals("content", new String(Files.readAllBytes(unzipped.resolve("foo"))));
        Path resultDir = unzipped.resolve("bar");
        Path resultFile2 = resultDir.resolve("baz");
        assertEquals("content2", new String(Files.readAllBytes(resultFile2)));
        Path resultLink = unzipped.resolve("link1");
        assertTrue(Files.isDirectory(resultLink));
        assertTrue(Files.isSymbolicLink(resultLink));
        assertTrue(Files.isSameFile(resultLink, resultDir));
        Path resultLink2 = unzipped.resolve("link2");
        assertEquals("content2", new String(Files.readAllBytes(resultLink2)));
        assertTrue(Files.isSymbolicLink(resultLink2));
        assertTrue(Files.isSameFile(resultLink2, resultFile2));
    } finally {
        fop.deleteFileOrFolder(root.toFile());
        fop.deleteFileOrFolder(outRoot.toFile());
    }
}

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.j  a v  a 2  s.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:org.apache.ant.compress.taskdefs.Zip.java

public Zip() {
    setFactory(new ZipStreamFactory() {
        public ArchiveOutputStream getArchiveStream(OutputStream stream, String encoding) throws IOException {
            ZipArchiveOutputStream o = (ZipArchiveOutputStream) super.getArchiveStream(stream, encoding);
            configure(o);//from w  ww. j a v a 2 s .  co m
            return o;
        }

        public ArchiveOutputStream getArchiveOutputStream(File f, String encoding) throws IOException {
            ZipArchiveOutputStream o = (ZipArchiveOutputStream) super.getArchiveOutputStream(f, encoding);
            configure(o);
            return o;
        }
    });
    setEntryBuilder(new ArchiveBase.EntryBuilder() {
        public ArchiveEntry buildEntry(ArchiveBase.ResourceWithFlags r) {
            boolean isDir = r.getResource().isDirectory();
            ZipArchiveEntry ent = new ZipArchiveEntry(r.getName());
            ent.setTime(round(r.getResource().getLastModified(), 2000));
            ent.setSize(isDir ? 0 : r.getResource().getSize());

            if (!isDir && r.getCollectionFlags().hasModeBeenSet()) {
                ent.setUnixMode(r.getCollectionFlags().getMode());
            } else if (isDir && r.getCollectionFlags().hasDirModeBeenSet()) {
                ent.setUnixMode(r.getCollectionFlags().getDirMode());
            } else if (r.getResourceFlags().hasModeBeenSet()) {
                ent.setUnixMode(r.getResourceFlags().getMode());
            } else {
                ent.setUnixMode(isDir ? ArchiveFileSet.DEFAULT_DIR_MODE : ArchiveFileSet.DEFAULT_FILE_MODE);
            }

            if (r.getResourceFlags().getZipExtraFields() != null) {
                ent.setExtraFields(r.getResourceFlags().getZipExtraFields());
            }

            if (keepCompression && r.getResourceFlags().hasCompressionMethod()) {
                ent.setMethod(r.getResourceFlags().getCompressionMethod());
            }

            return ent;
        }
    });
    setFileSetBuilder(new ArchiveBase.FileSetBuilder() {
        public ArchiveFileSet buildFileSet(Resource dest) {
            ArchiveFileSet afs = new ZipFileSet();
            afs.setSrcResource(dest);
            return afs;
        }
    });
}