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:org.openengsb.connector.git.internal.GitServiceImpl.java

@Override
public File export(CommitRef ref) {
    RevWalk rw = null;//from w  ww . j  a v a2s.c om
    File tmp = null;
    try {
        if (repository == null) {
            initRepository();
        }

        LOGGER.debug("Resolving HEAD and reference [{}]", ref.getStringRepresentation());
        AnyObjectId headId = repository.resolve(Constants.HEAD);
        AnyObjectId refId = repository.resolve(ref.getStringRepresentation());
        if (headId == null || refId == null) {
            throw new ScmException("HEAD or reference [" + ref.getStringRepresentation() + "] doesn't exist.");
        }
        rw = new RevWalk(repository);
        RevCommit head = rw.parseCommit(headId);
        RevCommit commit = rw.parseCommit(refId);

        LOGGER.debug("Checking out working copy of revision");
        checkoutIndex(commit);

        tmp = File.createTempFile("repository", ".zip");
        LOGGER.debug("Exporting repository to archive");
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(tmp);
        packRepository(localWorkspace, zos);
        zos.close();

        LOGGER.debug("Checking out working copy of former HEAD revision");
        checkoutIndex(head);
    } catch (IOException e) {
        throw new ScmException(e);
    } finally {
        if (rw != null) {
            rw.release();
        }
    }
    return tmp;
}

From source file:org.opengion.fukurou.util.ZipArchive.java

/**
 * ???????ZIP????//from   ww  w.  ja  v a  2  s  . co m
 * ??DEFAULT_COMPRESSION??
 * ???????????CRC?
 * ????????????????????(?????
 * ???????)
 * ???????????????????????
 * ?ZIP???????????????
 *
 * @param files     ??
 * @param zipFile   ZIP??
 * @param encording ?(Windows???"Windows-31J" ???)
 * @return ZIP???
 * @og.rev 4.1.0.2 (2008/02/01) ?
 * @og.rev 5.7.1.2 (2013/12/20) org.apache.commons.compress ?(??)
 */
public static List<File> compress(final File[] files, final File zipFile, final String encording) {
    List<File> list = new ArrayList<File>();
    ZipArchiveOutputStream zos = null;

    try {
        zos = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
        if (encording != null) {
            zos.setEncoding(encording); // "Windows-31J"
        }

        // ZIP????
        addZipEntry(list, zos, "", files); // ??????
    } catch (FileNotFoundException ex) {
        String errMsg = "ZIP?????[??=" + zipFile + "]";
        throw new RuntimeException(errMsg, ex);
    } finally {
        Closer.ioClose(zos);
        //              zos.finish();
        //              zos.flush();
        //              zos.close();
    }

    return list;
}

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

/**
 *
 * {@inheritDoc}/*from ww  w. ja  v a2  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 {//from ww  w.  ja  v  a  2 s  .  c om
        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}/*from w  ww.j a v a 2s  .  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.owasp.dependencytrack.util.ZipUtil.java

/**
 * Creates a zip file at the specified path with the contents of the specified directory.
 *
 * @param directoryPath The path of the directory where the archive will be created. eg. c:/temp
 * @param zipPath The full path of the archive to create. eg. c:/temp/archive.zip
 * @throws IOException If anything goes wrong
 *///from   www . j  a v  a 2  s  .c  o m
public static void createZip(String directoryPath, String zipPath) throws IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    ZipArchiveOutputStream tOut = null;

    try {
        fOut = new FileOutputStream(new File(zipPath));
        bOut = new BufferedOutputStream(fOut);
        tOut = new ZipArchiveOutputStream(bOut);
        addFileToZip(tOut, directoryPath, "");
        tOut.finish();
    } finally {
        IOUtils.closeQuietly(tOut);
        IOUtils.closeQuietly(bOut);
        IOUtils.closeQuietly(fOut);
    }
}

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

public static void protectVCF(File targetFile, File vCardFile, char[] password) throws Exception {
    ZipArchiveOutputStream out = null;/*from w  ww. j ava  2 s  .  c o  m*/
    try {
        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  ww . j  a  v a 2  s  .  c om
 * 
 * @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.pepstock.jem.commands.CreateNode.java

private static void zipDirectory(File directoryPath, File zipPath) throws IOException {
    FileOutputStream fOut = new FileOutputStream(zipPath);
    BufferedOutputStream bOut = new BufferedOutputStream(fOut);
    ZipArchiveOutputStream tOut = new ZipArchiveOutputStream(bOut);
    zip(directoryPath, directoryPath, tOut);
    tOut.finish();//w  ww. j av  a 2s.  c o  m
    tOut.close();
    bOut.close();
    fOut.close();
}

From source file:org.pepstock.jem.util.ZipUtil.java

/** 
  * Creates a zip output stream  at the specified path with the contents of the specified directory. 
  * /*from   ww w .  ja v  a2  s . c  om*/
  * @param folder folder to zip 
  * @param zipOutputStream output stream. Usually a bytearray 
  * @throws IOException if any error occurs 
  */
public static void createZip(File folder, OutputStream zipOutputStream) throws IOException {
    BufferedOutputStream bufferedOutputStream = null;
    ZipArchiveOutputStream zipArchiveOutputStream = null;
    try {
        bufferedOutputStream = new BufferedOutputStream(zipOutputStream);
        zipArchiveOutputStream = new ZipArchiveOutputStream(bufferedOutputStream);
        addFileToZip(zipArchiveOutputStream, folder);
    } finally {
        if (zipArchiveOutputStream != null) {
            zipArchiveOutputStream.finish();
            zipArchiveOutputStream.close();
        }
        if (bufferedOutputStream != null) {
            bufferedOutputStream.close();
        }
        if (zipOutputStream != null) {
            zipOutputStream.close();
        }
    }

}