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

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

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the current archive entry.

Usage

From source file:org.apache.camel.processor.aggregate.ZipAggregationStrategy.java

@Override
public void onCompletion(Exchange exchange) {
    List<Exchange> list = exchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class);
    try {//w w w .jav  a2s .  c  o m
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipArchiveOutputStream zout = new ZipArchiveOutputStream(bout);
        for (Exchange item : list) {
            String name = item.getProperty(ZIP_ENTRY_NAME,
                    item.getProperty(Exchange.FILE_NAME, item.getExchangeId(), String.class), String.class);
            byte[] body = item.getIn().getBody(byte[].class);
            ZipArchiveEntry entry = new ZipArchiveEntry(name);
            entry.setSize(body.length);
            zout.putArchiveEntry(entry);
            zout.write(body);
            zout.closeArchiveEntry();
        }
        zout.close();
        exchange.getIn().setBody(bout.toByteArray());
        exchange.removeProperty(Exchange.GROUPED_EXCHANGE);
    } catch (Exception e) {
        throw new RuntimeException("Unable to zip exchanges!", e);
    }
}

From source file:org.apache.karaf.tooling.ArchiveMojo.java

private void addFileToZip(ZipArchiveOutputStream tOut, Path f, String base) throws IOException {
    if (Files.isDirectory(f)) {
        String entryName = base + f.getFileName().toString() + "/";
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        tOut.putArchiveEntry(zipEntry);/*w w w .j  a v a  2  s. com*/
        tOut.closeArchiveEntry();
        try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) {
            for (Path child : children) {
                addFileToZip(tOut, child, entryName);
            }
        }
    } else if (useSymLinks && Files.isSymbolicLink(f)) {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DEFAULT_FILE_PERM);
        tOut.putArchiveEntry(zipEntry);
        tOut.write(Files.readSymbolicLink(f).toString().getBytes());
        tOut.closeArchiveEntry();
    } else {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setSize(Files.size(f));
        if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin"))) {
            if (!entryName.endsWith(".bat")) {
                zipEntry.setUnixMode(0755);
            } else {
                zipEntry.setUnixMode(0644);
            }
        }
        tOut.putArchiveEntry(zipEntry);
        Files.copy(f, tOut);
        tOut.closeArchiveEntry();
    }
}

From source file:org.apache.tika.server.writer.ZipWriter.java

private static void zipStoreBuffer(ZipArchiveOutputStream zip, String name, byte[] dataBuffer)
        throws IOException {
    ZipEntry zipEntry = new ZipEntry(name != null ? name : UUID.randomUUID().toString());
    zipEntry.setMethod(ZipOutputStream.STORED);

    zipEntry.setSize(dataBuffer.length);
    CRC32 crc32 = new CRC32();
    crc32.update(dataBuffer);// w  w  w . j  ava2s  . c  o  m
    zipEntry.setCrc(crc32.getValue());

    try {
        zip.putArchiveEntry(new ZipArchiveEntry(zipEntry));
    } catch (ZipException ex) {
        if (name != null) {
            zipStoreBuffer(zip, "x-" + name, dataBuffer);
            return;
        }
    }

    zip.write(dataBuffer);

    zip.closeArchiveEntry();
}

From source file:org.mycore.services.zipper.MCRZipServlet.java

@Override
protected void sendMetadataCompressed(String fileName, byte[] content, long lastModified,
        ZipArchiveOutputStream container) throws IOException {
    ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
    entry.setSize(content.length);/*from  w  w  w.ja  v  a  2s.c  om*/
    entry.setTime(lastModified);
    container.putArchiveEntry(entry);
    container.write(content);
    container.closeArchiveEntry();
}

From source file:org.orderofthebee.addons.support.tools.repo.LogFilesZIPPost.java

/**
 *
 * {@inheritDoc}/*w  w  w . ja  v  a 2  s  .  c  o  m*/
 */
@Override
public void execute(final WebScriptRequest req, final WebScriptResponse res) throws IOException {
    final Map<String, Object> model = new HashMap<>();
    final Status status = new Status();
    final Cache cache = new Cache(this.getDescription().getRequiredCache());
    model.put("status", status);
    model.put("cache", cache);

    final Object parsedContent = req.parseContent();
    if (!(parsedContent instanceof FormData)) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                "No or invalid request data provided - only form data is supported");
    }

    final FormData rqData = (FormData) parsedContent;
    final List<String> filePaths = new ArrayList<>();
    final String[] paths = rqData.getParameters().get("paths");
    filePaths.addAll(Arrays.asList(paths));

    final List<File> files = this.validateFilePaths(filePaths);

    final File logFileZip = TempFileProvider.createTempFile("ootbee-support-tools-logFiles", "zip");
    try {
        try {
            final ZipArchiveOutputStream zipOS = new ZipArchiveOutputStream(logFileZip);
            try {
                for (final File logFile : files) {
                    final ArchiveEntry archiveEntry = zipOS.createArchiveEntry(logFile, logFile.getName());
                    zipOS.putArchiveEntry(archiveEntry);

                    final FileInputStream fis = new FileInputStream(logFile);
                    try {
                        final byte[] buf = new byte[10240];
                        while (fis.read(buf) != -1) {
                            zipOS.write(buf);
                        }
                    } finally {
                        fis.close();
                    }

                    zipOS.closeArchiveEntry();
                }
            } finally {
                zipOS.close();
            }
        } catch (final IOException ioEx) {
            throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Error creating ZIP file", ioEx);
        }

        this.delegate.streamContent(req, res, logFileZip, logFileZip.lastModified(), false, "log-files.zip",
                model);
    } finally {
        // eager cleanup
        if (!logFileZip.delete()) {
            logFileZip.deleteOnExit();
        }
    }
}

From source file:org.orderofthebee.addons.support.tools.share.LogFileHandler.java

protected void createZip(final List<File> files, final File logFileZip) {
    try {/* w w w  .  j  av  a2 s.co  m*/
        final ZipArchiveOutputStream zipOS = new ZipArchiveOutputStream(logFileZip);
        try {
            for (final File logFile : files) {
                final ArchiveEntry archiveEntry = zipOS.createArchiveEntry(logFile, logFile.getName());
                zipOS.putArchiveEntry(archiveEntry);

                final FileInputStream fis = new FileInputStream(logFile);
                try {
                    final byte[] buf = new byte[10240];
                    while (fis.read(buf) != -1) {
                        zipOS.write(buf);
                    }
                } finally {
                    fis.close();
                }

                zipOS.closeArchiveEntry();
            }
        } finally {
            zipOS.close();
        }
    } catch (final IOException ioEx) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Error creating ZIP file", ioEx);
    }
}

From source file:org.orderofthebee.addons.support.tools.share.LogFilesZIPPost.java

/**
 *
 * {@inheritDoc}/* ww  w  .ja v  a  2 s .  c o m*/
 */
@Override
public void execute(final WebScriptRequest req, final WebScriptResponse res) throws IOException {
    final Map<String, Object> model = new HashMap<>();
    final Status status = new Status();
    final Cache cache = new Cache(this.getDescription().getRequiredCache());
    model.put("status", status);
    model.put("cache", cache);

    final Object parsedContent = req.parseContent();
    if (!(parsedContent instanceof FormData)) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                "No or invalid request data provided - only form data is supported");
    }

    final FormData rqData = (FormData) parsedContent;
    final List<String> filePaths = new ArrayList<>();
    final String[] paths = rqData.getParameters().get("paths");
    filePaths.addAll(Arrays.asList(paths));

    final List<File> files = this.validateFilePaths(filePaths);

    final File logFileZip = TempFileProvider.createTempFile("ootbee-support-tools-logFiles", "zip");
    try {
        try {
            final ZipArchiveOutputStream zipOS = new ZipArchiveOutputStream(logFileZip);
            try {
                for (final File logFile : files) {
                    final ArchiveEntry archiveEntry = zipOS.createArchiveEntry(logFile, logFile.getName());
                    zipOS.putArchiveEntry(archiveEntry);

                    final FileInputStream fis = new FileInputStream(logFile);
                    try {
                        final byte[] buf = new byte[10240];
                        while (fis.read(buf) != -1) {
                            zipOS.write(buf);
                        }
                    } finally {
                        fis.close();
                    }

                    zipOS.closeArchiveEntry();
                }
            } finally {
                zipOS.close();
            }
        } catch (final IOException ioEx) {
            throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Error creating ZIP file", ioEx);
        }

        this.streamContent(req, res, logFileZip, logFileZip.lastModified(), false, "log-files.zip", model,
                "application/zip");
    } finally {
        // eager cleanup
        if (!logFileZip.delete()) {
            logFileZip.deleteOnExit();
        }
    }
}

From source file:org.panbox.core.identitymgmt.VCardProtector.java

public static void protectVCF(File targetFile, File vCardFile, char[] password) throws Exception {
    ZipArchiveOutputStream out = null;
    try {//from  w  w w  . j av a 2 s  . c o  m
        out = new ZipArchiveOutputStream(new FileOutputStream(targetFile));

        byte[] vCardData = IOUtils.toByteArray(new FileInputStream(vCardFile));
        byte[] passwordBytes = Utils.toBytes(password);

        vcfMac.init(new SecretKeySpec(passwordBytes, KeyConstants.VCARD_HMAC));
        byte[] hmac = vcfMac.doFinal(vCardData);

        String fileName = Utils.bytesToHex(hmac);

        // first entry is the vcard itself
        ZipArchiveEntry entry = new ZipArchiveEntry(vCardFile.getName());
        entry.setSize(vCardData.length);
        out.putArchiveEntry(entry);
        out.write(vCardData);
        out.flush();
        out.closeArchiveEntry();

        // second entry is the hmac value
        entry = new ZipArchiveEntry(fileName);
        entry.setSize(fileName.length());
        out.putArchiveEntry(entry);
        out.closeArchiveEntry();
        out.flush();
    } catch (IOException | InvalidKeyException e) {
        logger.error("Could not create protected VCF export file!", e);
        throw e;
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:org.panbox.core.pairing.file.PanboxFilePairingUtils.java

/**
 * Stores a pairing file at the specified path for the specified device and
 * type//from  w w  w . ja  v a  2s  .c  o  m
 * 
 * @param outputFile
 *            Pairing file to be saved
 * @param devicename
 *            Name of the device that should be paired
 * @param password
 *            Password of the identity
 */
public static PanboxFilePairingWriteReturnContainer storePairingFile(File outputFile, String devicename,
        char[] password, PairingType type, DeviceType devType, String eMail, String firstName, String lastName,
        PrivateKey privEncKey, X509Certificate encCert, PrivateKey privSignKey, X509Certificate signCert,
        Map<String, X509Certificate> devices, Collection<VCard> contacts)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container to: "
            + outputFile.getAbsolutePath());

    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(outputFile));

    // 1. add device name to pairing file
    ZipArchiveEntry entry = new ZipArchiveEntry("devicename");
    entry.setSize(devicename.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(devicename.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 2. add device name to pairing file
    entry = new ZipArchiveEntry("email");
    entry.setSize(eMail.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(eMail.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 3. add device name to pairing file
    entry = new ZipArchiveEntry("firstname");
    entry.setSize(firstName.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(firstName.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 4. add device name to pairing file
    entry = new ZipArchiveEntry("lastname");
    entry.setSize(lastName.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(lastName.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 5. generate and add a new device key + cert for the newly device
    KeyPair devKey = CryptCore.generateKeypair();
    X509Certificate devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(),
            new PairingIPersonDummy(eMail, firstName, lastName));

    KeyStore devKeyStore = KeyStore.getInstance("PKCS12");
    devKeyStore.load(null, null);
    devKeyStore.setKeyEntry(devicename, (Key) devKey.getPrivate(), password, new Certificate[] { devCert });
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    devKeyStore.store(baos, password);
    baos.flush();

    byte[] data = baos.toByteArray();
    entry = new ZipArchiveEntry("devicekey.p12");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    out.closeArchiveEntry();

    // 6. add device certs and names for all known devices

    baos = new ByteArrayOutputStream();
    ByteArrayOutputStream deviceNamesFile = new ByteArrayOutputStream();
    KeyStore deviceKeyStore = KeyStore.getInstance("BKS");
    deviceKeyStore.load(null, null);
    int i = 0;

    for (Entry<String, X509Certificate> device : devices.entrySet()) {
        deviceKeyStore.setCertificateEntry("device" + i, device.getValue());
        deviceNamesFile.write(("device" + i + DELIMITER + device.getKey() + "\n").getBytes());
        ++i;
    }

    deviceKeyStore.store(baos, password);
    baos.flush();
    deviceNamesFile.flush();

    byte[] data2 = deviceNamesFile.toByteArray();
    entry = new ZipArchiveEntry("knownDevices.list");
    entry.setSize(data2.length);
    out.putArchiveEntry(entry);
    out.write(data2);
    out.flush();

    data = baos.toByteArray();
    entry = new ZipArchiveEntry("knownDevices.bks");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    // 7. add vcard for all known contacts

    File tempContacts = File.createTempFile("panboxContacts", null);
    AbstractAddressbookManager.exportContacts(contacts, tempContacts);
    FileInputStream fis = new FileInputStream(tempContacts);
    data = new byte[(int) tempContacts.length()];
    fis.read(data);
    fis.close();
    tempContacts.delete();

    entry = new ZipArchiveEntry("contacts.vcard");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    // 8. add owner certs or keys in case of main/restricted
    KeyStore ownerKeyStore = null;
    if (type == PairingType.MASTER) {
        ownerKeyStore = KeyStore.getInstance("PKCS12");
        ownerKeyStore.load(null, null);
        ownerKeyStore.setKeyEntry("ownerEncKey", privEncKey, password, new Certificate[] { encCert });
        ownerKeyStore.setKeyEntry("ownerSignKey", privSignKey, password, new Certificate[] { signCert });
        entry = new ZipArchiveEntry("ownerKeys.p12");
    } else {
        ownerKeyStore = KeyStore.getInstance("BKS");
        ownerKeyStore.load(null, null);
        ownerKeyStore.setCertificateEntry("ownerEncCert", encCert);
        ownerKeyStore.setCertificateEntry("ownerSignCert", signCert);
        entry = new ZipArchiveEntry("ownerCerts.bks");
    }
    baos = new ByteArrayOutputStream();
    ownerKeyStore.store(baos, password);
    baos.flush();

    data = baos.toByteArray();
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    out.closeArchiveEntry();

    out.flush();
    out.close();
    logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container finished.");

    return new PanboxFilePairingWriteReturnContainer(devicename, devCert, devType);
}

From source file:org.sigmah.server.file.impl.BackupArchiveJob.java

/**
 * <p>//ww  w .ja  v  a2 s .c o  m
 * Recursively browses the given {@code root} repository elements to populate the given {@code zipOutputStream} with
 * corresponding files.
 * </p>
 * <p>
 * If a referenced file cannot be found in the storage folder, it will be ignored (a {@code WARN} log is generated).
 * </p>
 * 
 * @param root
 *          The root repository element.
 * @param zipOutputStream
 *          The stream to populate with files hierarchy.
 * @param actualPath
 *          The current repository path.
 */
private void zipRepository(final RepositoryElement root, final ZipArchiveOutputStream zipOutputStream,
        final String actualPath) {

    final String path = (actualPath.equals("") ? root.getName() : actualPath + "/" + root.getName());

    if (root instanceof FileElement) {

        final FileElement file = (FileElement) root;
        final String fileStorageId = file.getStorageId();

        if (fileStorageProvider.exists(fileStorageId)) {
            try (final InputStream is = new BufferedInputStream(fileStorageProvider.open(fileStorageId),
                    ResponseHelper.BUFFER_SIZE)) {

                zipOutputStream.putArchiveEntry(new ZipArchiveEntry(path));

                final byte data[] = new byte[ResponseHelper.BUFFER_SIZE];

                while ((is.read(data)) != -1) {
                    zipOutputStream.write(data);
                }

                zipOutputStream.closeArchiveEntry();

            } catch (final IOException e) {
                LOG.warn("File '" + fileStorageId + "' cannot be found ; continuing with next file.", e);
            }
        } else {
            LOG.warn("File '{0}' does not exists on the server ; continuing with next file.", fileStorageId);
        }

    } else if (root instanceof FolderElement) {

        final FolderElement folder = (FolderElement) root;

        for (final RepositoryElement element : folder.getChildren()) {
            zipRepository(element, zipOutputStream, path);
        }
    }
}