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

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out to the stream.

Usage

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Compute delta.//w  w w .  j  a  va  2 s .c  o m
 *
 * @param source the source
 * @param target the target
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void computeDelta(ZipFile source, ZipFile target, ZipArchiveOutputStream output, PrintWriter list,
        String prefix) throws IOException {
    try {
        for (Enumeration<ZipArchiveEntry> enumer = target.getEntries(); enumer.hasMoreElements();) {
            calculatedDelta = null;
            ZipArchiveEntry targetEntry = enumer.nextElement();
            ZipArchiveEntry sourceEntry = findBestSource(source, target, targetEntry);
            String nextEntryName = prefix + targetEntry.getName();
            if (sourceEntry != null && zipFilesPattern.matcher(sourceEntry.getName()).matches()
                    && !equal(sourceEntry, targetEntry)) {
                nextEntryName += "!";
            }
            nextEntryName += "|" + Long.toHexString(targetEntry.getCrc());
            if (sourceEntry != null) {
                nextEntryName += ":" + Long.toHexString(sourceEntry.getCrc());
            } else {
                nextEntryName += ":0";
            }
            list.println(nextEntryName);
            if (targetEntry.isDirectory()) {
                if (sourceEntry == null) {
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    output.closeArchiveEntry();
                }
            } else {
                if (sourceEntry == null || sourceEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE
                        || targetEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE) { // new Entry od. alter Eintrag od. neuer Eintrag leer
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    try (InputStream in = target.getInputStream(targetEntry)) {
                        int read = 0;
                        while (-1 < (read = in.read(buffer))) {
                            output.write(buffer, 0, read);
                        }
                        output.flush();
                    }
                    output.closeArchiveEntry();
                } else {
                    if (!equal(sourceEntry, targetEntry)) {
                        if (zipFilesPattern.matcher(sourceEntry.getName()).matches()) {
                            File embeddedTarget = File.createTempFile("jardelta-tmp", ".zip");
                            File embeddedSource = File.createTempFile("jardelta-tmp", ".zip");
                            try (FileOutputStream out = new FileOutputStream(embeddedSource);
                                    InputStream in = source.getInputStream(sourceEntry);
                                    FileOutputStream out2 = new FileOutputStream(embeddedTarget);
                                    InputStream in2 = target.getInputStream(targetEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    out.write(buffer, 0, read);
                                }
                                out.flush();
                                read = 0;
                                while (-1 < (read = in2.read(buffer))) {
                                    out2.write(buffer, 0, read);
                                }
                                out2.flush();
                                computeDelta(new ZipFile(embeddedSource), new ZipFile(embeddedTarget), output,
                                        list, prefix + sourceEntry.getName() + "!");
                            } finally {
                                embeddedSource.delete();
                                embeddedTarget.delete();
                            }
                        } else {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(
                                    prefix + targetEntry.getName() + ".gdiff");
                            outputEntry.setTime(targetEntry.getTime());
                            outputEntry.setComment("" + targetEntry.getCrc());
                            output.putArchiveEntry(outputEntry);
                            if (calculatedDelta != null) {
                                output.write(calculatedDelta);
                                output.flush();
                            } else {
                                try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {
                                    Delta d = new Delta();
                                    DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));
                                    int sourceSize = (int) sourceEntry.getSize();
                                    byte[] sourceBytes = new byte[sourceSize];
                                    try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                        for (int erg = sourceStream.read(
                                                sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                        .read(sourceBytes, erg, sourceBytes.length - erg))
                                            ;
                                    }
                                    d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);
                                    output.write(outbytes.toByteArray());
                                }
                            }
                            output.closeArchiveEntry();
                        }
                    }
                }
            }
        }
    } finally {
        source.close();
        target.close();
    }
}

From source file:com.naryx.tagfusion.expression.function.file.Zip.java

/**
 * Performing Zip() operation/*from   ww w. j a v  a 2  s  .c  o m*/
 * 
 * @param session
 * @param zipfile
 * @param src
 * @param recurse
 * @param prefixx
 * @param compLvl
 * @param filter
 * @param overwrite
 * @param newpath
 * @throws cfmRunTimeException
 * @throws IOException
 */
protected void zipOperation(cfSession session, ZipArchiveOutputStream zipOut, File src, boolean recurse,
        String prefix, int compLvl, FilenameFilter filter, String newpath) throws cfmRunTimeException {
    if (src != null) {
        FileInputStream nextFileIn;
        ZipArchiveEntry nextEntry = null;
        byte[] buffer = new byte[4096];
        int readBytes;
        zipOut.setLevel(compLvl);

        try {
            List<File> files = new ArrayList<File>();
            int srcDirLen;
            if (src.isFile()) {
                String parentPath = src.getParent();
                srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1;
                files.add(src);

            } else {
                String parentPath = src.getAbsolutePath();
                srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1;
                getFiles(src, files, recurse, filter);
            }

            int noFiles = files.size();
            File nextFile;
            boolean isDir;
            for (int i = 0; i < noFiles; i++) {
                nextFile = (File) files.get(i);

                isDir = nextFile.isDirectory();

                if (noFiles == 1 && newpath != null) {
                    // NEWPATH
                    nextEntry = new ZipArchiveEntry(newpath.replace('\\', '/') + (isDir ? "/" : ""));
                } else {
                    // PREFIX
                    nextEntry = new ZipArchiveEntry(
                            prefix + nextFile.getAbsolutePath().substring(srcDirLen).replace('\\', '/')
                                    + (isDir ? "/" : ""));
                }

                try {
                    zipOut.putArchiveEntry(nextEntry);
                } catch (IOException e) {
                    throwException(session,
                            "Failed to add entry to zip file [" + nextEntry + "]. Reason: " + e.getMessage());
                }

                if (!isDir) {
                    nextEntry.setTime(nextFile.lastModified());
                    nextFileIn = new FileInputStream(nextFile);
                    try {
                        while (nextFileIn.available() > 0) {
                            readBytes = nextFileIn.read(buffer);
                            zipOut.write(buffer, 0, readBytes);
                        }
                        zipOut.flush();
                    } catch (IOException e) {
                        throwException(session, "Failed to write entry [" + nextEntry
                                + "] to zip file. Reason: " + e.getMessage());
                    } finally {
                        // nextEntry close
                        StreamUtil.closeStream(nextFileIn);
                    }
                }
                zipOut.closeArchiveEntry();
            }
        } catch (IOException ioe) {
            throwException(session, "Failed to create zip file: " + ioe.getMessage());
        }
    }
}

From source file:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Apply delta./*from   w  w w. j ava2 s  .co  m*/
 *
 * @param patch the patch
 * @param source the source
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list,
        String prefix) throws IOException {
    String fileName = null;
    try {
        for (fileName = (next == null ? list.readLine()
                : next); fileName != null; fileName = (next == null ? list.readLine() : next)) {
            if (next != null)
                next = null;
            if (!fileName.startsWith(prefix)) {
                next = fileName;
                return;
            }
            int crcDelim = fileName.lastIndexOf(':');
            int crcStart = fileName.lastIndexOf('|');
            long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16);
            long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16);
            fileName = fileName.substring(prefix.length(), crcStart);
            if ("META-INF/file.list".equalsIgnoreCase(fileName))
                continue;
            if (fileName.contains("!")) {
                String[] embeds = fileName.split("\\!");
                ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc);
                File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip");
                File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip");
                Exception thrown = null;
                try (FileOutputStream out = new FileOutputStream(originalFile);
                        InputStream in = source.getInputStream(original)) {
                    int read = 0;
                    while (-1 < (read = in.read(buffer))) {
                        out.write(buffer, 0, read);
                    }
                    out.flush();
                    applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list,
                            prefix + embeds[0] + "!");
                } catch (Exception e) {
                    thrown = e;
                    throw e;
                } finally {
                    originalFile.delete();
                    try (FileInputStream in = new FileInputStream(outputFile)) {
                        if (thrown == null) {
                            ZipArchiveEntry outEntry = copyEntry(original);
                            output.putArchiveEntry(outEntry);
                            int read = 0;
                            while (-1 < (read = in.read(buffer))) {
                                output.write(buffer, 0, read);
                            }
                            output.flush();
                            output.closeArchiveEntry();
                        }
                    } finally {
                        outputFile.delete();
                    }
                }
            } else {
                try {
                    ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc);
                    if (patchEntry != null) { // new Entry
                        ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName);
                        output.putArchiveEntry(outputEntry);
                        if (!patchEntry.isDirectory()) {
                            try (InputStream in = patch.getInputStream(patchEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    output.write(buffer, 0, read);
                                }
                            }
                        }
                        closeEntry(output, outputEntry, crc);
                    } else {
                        ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc);
                        if (sourceEntry == null) {
                            throw new FileNotFoundException(
                                    fileName + " not found in " + sourceName + " or " + patchName);
                        }
                        if (sourceEntry.isDirectory()) {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            output.putArchiveEntry(outputEntry);
                            closeEntry(output, outputEntry, crc);
                            continue;
                        }
                        patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc);
                        if (patchEntry != null) { // changed Entry
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            outputEntry.setTime(patchEntry.getTime());
                            output.putArchiveEntry(outputEntry);
                            byte[] sourceBytes = new byte[(int) sourceEntry.getSize()];
                            try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                for (int erg = sourceStream
                                        .read(sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                .read(sourceBytes, erg, sourceBytes.length - erg))
                                    ;
                            }
                            InputStream patchStream = patch.getInputStream(patchEntry);
                            GDiffPatcher diffPatcher = new GDiffPatcher();
                            diffPatcher.patch(sourceBytes, patchStream, output);
                            patchStream.close();
                            outputEntry.setCrc(crc);
                            closeEntry(output, outputEntry, crc);
                        } else { // unchanged Entry
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            output.putArchiveEntry(outputEntry);
                            try (InputStream in = source.getInputStream(sourceEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    output.write(buffer, 0, read);
                                }
                            }
                            output.flush();
                            closeEntry(output, outputEntry, crc);
                        }
                    }
                } catch (PatchException pe) {
                    IOException ioe = new IOException();
                    ioe.initCause(pe);
                    throw ioe;
                }
            }
        }
    } catch (Exception e) {
        System.err.println(prefix + fileName);
        throw e;
    } finally {
        source.close();
        output.close();
    }
}

From source file:net.test.aliyun.z7.Task.java

public void doWork() throws Throwable {
    //init task to DB
    System.out.println("do Task " + index + "\t from :" + oldKey);
    ///*from w w w  .  j  av  a2s . co  m*/
    //1. 
    System.out.print("\t save to Local -> working... ");
    OSSObject ossObject = client.getObject("files-subtitle", oldKey);
    File rarFile = new File(this.tempPath, ossObject.getObjectMetadata().getContentDisposition());
    rarFile.getParentFile().mkdirs();
    FileOutputStream fos = new FileOutputStream(rarFile, false);
    InputStream inStream = ossObject.getObjectContent();
    IOUtils.copy(inStream, fos);
    fos.flush();
    fos.close();
    System.out.print("-> finish.\n");
    //
    //2.
    System.out.print("\t extract rar -> working... ");
    String extToosHome = "C:\\Program Files (x86)\\7-Zip";
    String rarFileStr = rarFile.getAbsolutePath();
    String toDir = rarFileStr.substring(0, rarFileStr.length() - ".rar".length());
    //
    //
    int extract = Zip7Object.extract(extToosHome, rarFile.getAbsolutePath(), toDir);
    if (extract != 0) {
        if (extract != 2)
            System.out.println();
        FileUtils.deleteDir(new File(toDir));
        rarFile.delete();
        throw new Exception("extract error.");
    }
    System.out.print("-> finish.\n");
    //
    //3.
    System.out.print("\t package zip-> working... ");
    String zipFileName = rarFile.getAbsolutePath();
    zipFileName = zipFileName.substring(0, zipFileName.length() - ".rar".length()) + ".zip";
    ZipArchiveOutputStream outStream = new ZipArchiveOutputStream(new File(zipFileName));
    outStream.setEncoding("GBK");
    Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(),
            FileFilterUtils.directoryFileFilter());
    StringBuffer buffer = new StringBuffer();
    while (itFile.hasNext()) {
        File it = itFile.next();
        if (it.isDirectory())
            continue;
        String entName = it.getAbsolutePath().substring(toDir.length() + 1);
        ZipArchiveEntry ent = new ZipArchiveEntry(it, entName);
        outStream.putArchiveEntry(ent);
        InputStream itInStream = new FileInputStream(it);
        IOUtils.copy(itInStream, outStream);
        itInStream.close();
        outStream.flush();
        outStream.closeArchiveEntry();
        buffer.append(ent.getName());
    }
    outStream.flush();
    outStream.close();
    System.out.print("-> finish.\n");
    //
    //4.
    FileUtils.deleteDir(new File(toDir));
    System.out.print("\t delete temp dir -> finish.\n");
    //
    //5.save to
    System.out.print("\t save to oss -> working... ");
    ObjectMetadata omd = ossObject.getObjectMetadata();
    String contentDisposition = omd.getContentDisposition();
    contentDisposition = contentDisposition.substring(0, contentDisposition.length() - ".rar".length())
            + ".zip";
    omd.setContentDisposition(contentDisposition);
    omd.setContentLength(new File(zipFileName).length());
    InputStream zipInStream = new FileInputStream(zipFileName);
    PutObjectResult result = client.putObject("files-subtitle-format-zip", newKey, zipInStream, omd);
    zipInStream.close();
    new File(zipFileName).delete();
    System.out.print("-> OK:" + result.getETag());
    System.out.print("-> finish.\n");
    //
    //6.save files info
    int res = jdbc.update("update `oss-subtitle` set files=? , size=? , lastTime=now() where oss_key =?",
            buffer.toString(), omd.getContentLength(), newKey);
    System.out.println("\t save info to db -> " + res);
}

From source file:org.dbflute.helper.io.compress.DfZipArchiver.java

/**
 * Compress the directory's elements to archive file.
 * @param baseDir The base directory to compress. (NotNull)
 * @param filter The file filter, which doesn't need to accept the base directory. (NotNull)
 */// w w w  . j a  v a2s.co  m
public void compress(File baseDir, FileFilter filter) {
    if (baseDir == null) {
        String msg = "The argument 'baseDir' should not be null.";
        throw new IllegalArgumentException(msg);
    }
    if (!baseDir.isDirectory()) {
        String msg = "The baseDir should be directory but not: " + baseDir;
        throw new IllegalArgumentException(msg);
    }
    if (!baseDir.exists()) {
        String msg = "Not found the baseDir in the file system: " + baseDir;
        throw new IllegalArgumentException(msg);
    }
    OutputStream out = null;
    ZipArchiveOutputStream archive = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(_zipFile));
        archive = new ZipArchiveOutputStream(out);
        archive.setEncoding("UTF-8");

        addAll(archive, baseDir, baseDir, filter);

        archive.finish();
        archive.flush();
        out.flush();
    } catch (IOException e) {
        String msg = "Failed to compress the files to " + _zipFile.getPath();
        throw new IllegalStateException(msg, e);
    } finally {
        if (archive != null) {
            try {
                archive.close();
            } catch (IOException ignored) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }
    }
}

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 {//w  w  w.  ja va 2s.  c om
        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//  w  w  w.ja v  a2 s .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.waarp.common.tar.ZipUtility.java

/**
 * Create a new Zip from a root directory
 * /*  w ww  . j av  a  2  s.  co m*/
 * @param directory
 *            the base directory
 * @param filename
 *            the output filename
 * @param absolute
 *            store absolute filepath (from directory) or only filename
 * @return True if OK
 */
public static boolean createZipFromDirectory(String directory, String filename, boolean absolute) {
    File rootDir = new File(directory);
    File saveFile = new File(filename);
    // recursive call
    ZipArchiveOutputStream zaos;
    try {
        zaos = new ZipArchiveOutputStream(new FileOutputStream(saveFile));
    } catch (FileNotFoundException e) {
        return false;
    }
    try {
        recurseFiles(rootDir, rootDir, zaos, absolute);
    } catch (IOException e2) {
        try {
            zaos.close();
        } catch (IOException e) {
            // ignore
        }
        return false;
    }
    try {
        zaos.finish();
    } catch (IOException e1) {
        // ignore
    }
    try {
        zaos.flush();
    } catch (IOException e) {
        // ignore
    }
    try {
        zaos.close();
    } catch (IOException e) {
        // ignore
    }
    return true;
}

From source file:org.waarp.common.tar.ZipUtility.java

/**
 * Create a new Zip from an array of Files (only name of files will be used)
 * //  w  w  w  . j  a va2 s.c o  m
 * @param files
 *            array of files to add
 * @param filename
 *            the output filename
 * @return True if OK
 */
public static boolean createZipFromFiles(File[] files, String filename) {
    File saveFile = new File(filename);
    ZipArchiveOutputStream zaos;
    try {
        zaos = new ZipArchiveOutputStream(new FileOutputStream(saveFile));
    } catch (FileNotFoundException e) {
        return false;
    }
    for (File file : files) {
        try {
            addFile(file, zaos);
        } catch (IOException e) {
            try {
                zaos.close();
            } catch (IOException e1) {
                // ignore
            }
            return false;
        }
    }
    try {
        zaos.finish();
    } catch (IOException e1) {
        // ignore
    }
    try {
        zaos.flush();
    } catch (IOException e) {
        // ignore
    }
    try {
        zaos.close();
    } catch (IOException e) {
        // ignore
    }
    return true;
}