Example usage for org.apache.commons.compress.archivers.zip ZipArchiveInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

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

/**
 * Extract the archive file to the directory.
 * @param baseDir The base directory to compress. (NotNull)
 * @param filter The file filter, which doesn't need to accept the base directory. (NotNull)
 */// w  ww . ja v a2 s  . c o m
public void extract(File baseDir, FileFilter filter) {
    if (baseDir == null) {
        String msg = "The argument 'baseDir' should not be null.";
        throw new IllegalArgumentException(msg);
    }
    if (baseDir.exists() && !baseDir.isDirectory()) {
        String msg = "The baseDir should be directory but not: " + baseDir;
        throw new IllegalArgumentException(msg);
    }
    baseDir.mkdirs();
    final String baseDirPath = resolvePath(baseDir);
    InputStream ins = null;
    ZipArchiveInputStream archive = null;
    try {
        ins = new FileInputStream(_zipFile);
        archive = new ZipArchiveInputStream(ins, "UTF-8", true);
        ZipArchiveEntry entry;
        while ((entry = archive.getNextZipEntry()) != null) {
            final String entryName = resolveFileSeparator(entry.getName()); // just in case
            final File file = new File(baseDirPath + "/" + entryName);
            if (!filter.accept(file)) {
                continue;
            }
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                OutputStream out = null;
                try {
                    out = new FileOutputStream(file);
                    IOUtils.copy(archive, out);
                    out.close();
                } catch (IOException e) {
                    String msg = "Failed to IO-copy the file: " + file.getPath();
                    throw new IllegalStateException(msg, e);
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException ignored) {
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        String msg = "Failed to extract the files from " + _zipFile.getPath();
        throw new IllegalArgumentException(msg, e);
    } finally {
        if (archive != null) {
            try {
                archive.close();
            } catch (IOException ignored) {
            }
        }
        if (ins != null) {
            try {
                ins.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java

/**
 * Decompresses zip files./*  www .j  a  v a2 s .com*/
 * @param zipFile           The zip file to decompress.
 * @throws IOException
 * @throws MojoExecutionException
 */
private static void unZip(File zipFile, File output_dir) throws IOException, MojoExecutionException {

    ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(zipFile));
    ZipArchiveEntry ze;
    String name, parent;
    try {
        ze = zis.getNextZipEntry();
        // check for at least one zip entry
        if (ze == null) {
            throw new MojoExecutionException("Could not decompress " + zipFile);
        }

        while (ze != null) {
            name = ze.getName();

            //make directories
            if (ze.isDirectory()) {
                mkdirs(output_dir, name);
            } else {
                parent = getParentDirAbsolutePath(name);
                mkdirs(output_dir, parent);

                File outFile = new File(output_dir, name);
                outFile.createNewFile();

                // check for match in executable list
                if (executableFiles.contains(name)) {
                    Files.setPosixFilePermissions(outFile.toPath(),
                            PosixFilePermissions.fromString("rwxr-x---"));
                }

                FileOutputStream fos = new FileOutputStream(outFile);

                copyInputStreamToOutputStream(zis, fos);
                fos.close();
            }
            ze = zis.getNextZipEntry();
        }
    } finally {
        zis.close();
    }
}

From source file:org.jwebsocket.util.Tools.java

/**
 * Uncompress a byte array using zip compression
 *
 * @param aBA/*www  . j a v a  2  s . c  om*/
 * @param aBase64Decode If TRUE, the byte array is Base64 decoded before uncompress
 * @return
 * @throws Exception
 */
public static byte[] unzip(byte[] aBA, Boolean aBase64Decode) throws Exception {
    if (aBase64Decode) {
        aBA = Base64.decodeBase64(aBA);
    }
    ByteArrayInputStream lBAIS = new ByteArrayInputStream(aBA);
    ZipArchiveInputStream lAIOS = new ZipArchiveInputStream(lBAIS);
    // ATTENTION: do not comment next line!!!
    lAIOS.getNextZipEntry();

    ByteArrayOutputStream lBAOS = new ByteArrayOutputStream();
    IOUtils.copy(lAIOS, lBAOS);
    lAIOS.close();

    return lBAOS.toByteArray();
}

From source file:org.mitre.xtext.converters.ArchiveNavigator.java

public File unzip(File zipFile) throws IOException {

    String _working = tempDir.getAbsolutePath() + File.separator + FilenameUtils.getBaseName(zipFile.getPath());
    File workingDir = new File(_working);
    workingDir.mkdir();// w  w  w  . j a  va 2s  .c o  m

    InputStream input = new BufferedInputStream(new FileInputStream(zipFile));
    try {
        ZipArchiveInputStream in = (ZipArchiveInputStream) (new ArchiveStreamFactory()
                .createArchiveInputStream("zip", input));

        ZipArchiveEntry zipEntry;
        while ((zipEntry = (ZipArchiveEntry) in.getNextEntry()) != null) {
            if (filterEntry(zipEntry)) {
                continue;
            }

            try {
                File tmpFile = saveArchiveEntry(zipEntry, in, _working);
                converter.convert(tmpFile);

            } catch (IOException err) {
                log.error("Unable to save item, FILE=" + zipEntry.getName() + "!" + zipEntry.getName(), err);
            }
        }
        in.close();
    } catch (ArchiveException ae) {
        throw new IOException(ae);
    }

    return workingDir;
}

From source file:org.ngrinder.script.util.CompressionUtil.java

public void unzip(InputStream is, File destDir, String charsetName) throws IOException {
    ZipArchiveInputStream zis;
    ZipArchiveEntry entry;//from www  . j  a v a  2s. c  om
    String name;
    File target;
    int nWritten = 0;
    BufferedOutputStream bos;
    byte[] buf = new byte[1024 * 8];

    zis = new ZipArchiveInputStream(is, charsetName, false);
    while ((entry = zis.getNextZipEntry()) != null) {
        name = entry.getName();
        target = new File(destDir, name);
        if (entry.isDirectory()) {
            target.mkdirs(); /* does it always work? */
        } else {
            target.createNewFile();
            bos = new BufferedOutputStream(new FileOutputStream(target));
            while ((nWritten = zis.read(buf)) >= 0) {
                bos.write(buf, 0, nWritten);
            }
            bos.close();
        }
    }
    zis.close();
}

From source file:org.opensextant.xtext.collectors.ArchiveNavigator.java

public File unzip(File zipFile) throws IOException, ConfigException {

    // String _working = FilenameUtils.concat(getWorkingDir(),
    // FilenameUtils.getBaseName(zipFile.getPath()));
    // if (_working == null){
    // throw new IOException("Invalid archive path for "+zipFile.getPath());
    // }/*from ww w . j  ava2s . c  om*/

    // File workingDir = new File(_working);
    // workingDir.mkdir();
    File workingDir = saveDir;

    InputStream input = new BufferedInputStream(new FileInputStream(zipFile));
    ZipArchiveInputStream in = null;
    try {
        in = (ZipArchiveInputStream) (new ArchiveStreamFactory().createArchiveInputStream("zip", input));

        ZipArchiveEntry zipEntry;
        while ((zipEntry = (ZipArchiveEntry) in.getNextEntry()) != null) {
            if (filterEntry(zipEntry)) {
                continue;
            }

            try {
                File tmpFile = saveArchiveEntry(zipEntry, in, workingDir);
                converter.convert(tmpFile);

            } catch (IOException err) {
                log.error("Unable to save item, FILE=" + zipEntry.getName() + "!" + zipEntry.getName(), err);
            }
        }
        return workingDir;

    } catch (ArchiveException ae) {
        throw new IOException(ae);
    } finally {
        in.close();
    }
}

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

/**
 * Method extracts the VCF file stored within the zipped import file to the
 * given destination file. It further returns the corresponding hmac stored
 * within the archive./*from   ww w .  j  a  v  a2s . co m*/
 * 
 * @param sourceFile
 *            import archive
 * @param tmpFile
 *            temporary file to extract the CVF to
 * @return byte[] array containing the hmac of the VCF
 * @throws Exception
 */
public static byte[] unwrapVCF(File sourceFile, File tmpFile) throws FileNotFoundException, IOException {

    ZipArchiveInputStream in = null;
    FileOutputStream fos = null;
    String hmacString = null;
    try {

        in = new ZipArchiveInputStream(new FileInputStream(sourceFile));
        ArchiveEntry entry;
        // ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // ENTRY 1: vcard contents
        in.getNextEntry();
        fos = new FileOutputStream(tmpFile);
        IOUtils.copy(in, fos);

        // ENTRY 2: sha-256 hmac
        entry = in.getNextEntry();
        hmacString = entry.getName();

        return Utils.hexToBytes(hmacString);
    } catch (StringIndexOutOfBoundsException e) {
        logger.error("Error parsing hmac: " + hmacString + " is no valid hex String", e);
        throw e;
    } catch (Exception e) {
        logger.error("Error unwrapping VCF file", e);
        throw e;
    } finally {
        if (fos != null) {
            fos.flush();
            fos.close();
        }
        if (in != null) {
            in.close();
        }
    }
}

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

public static PanboxFilePairingLoadReturnContainer loadPairingFile(File inputFile, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, IllegalArgumentException {
    ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(inputFile));
    try {//w  ww.java  2  s . com
        byte[] buffer = new byte[1048576]; //1MB

        ArchiveEntry entry;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;

        // ENTRY 1: devicename
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for device name.");
            throw new IllegalArgumentException("Could not find entry for device name.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String devicename = new String(baos.toByteArray());

        // ENTRY 2: eMail
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for eMail.");
            throw new IllegalArgumentException("Could not find entry for eMail.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String eMail = new String(baos.toByteArray());

        // ENTRY 3: firstName
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for first name.");
            throw new IllegalArgumentException("Could not find entry for first name.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String firstName = new String(baos.toByteArray());

        // ENTRY 4: lastName
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for last name.");
            throw new IllegalArgumentException("Could not find entry for last name.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String lastName = new String(baos.toByteArray());

        // ENTRY 5: devKeyStore.p12
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for device key store.");
            throw new IllegalArgumentException("Could not find entry for device key store.");
        }

        KeyStore devKeyStore = KeyStore.getInstance("PKCS12");
        devKeyStore.load(in, password);
        PrivateKey devPKey = (PrivateKey) devKeyStore.getKey(devicename.toLowerCase(), password);
        Certificate[] devCert = devKeyStore.getCertificateChain(devicename.toLowerCase());

        // ENTRY 6: knownDevices.list/knownDevices.bks
        entry = in.getNextEntry(); // knownDevices.list

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for knownDevices.list.");
            throw new IllegalArgumentException("Could not find entry for knownDevices.list.");
        }

        Map<String, X509Certificate> devices = new HashMap<String, X509Certificate>();

        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        Map<String, String> deviceNames = new HashMap<String, String>();

        String line;
        while ((line = br.readLine()) != null) {
            String[] values = line.split(DELIMITER);
            deviceNames.put(values[0], values[1]);
        }

        entry = in.getNextEntry(); // knownDevices.bks

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for knownDevices.bks.");
            throw new IllegalArgumentException("Could not find entry for knownDevices.bks.");
        }

        KeyStore devicesStore = KeyStore.getInstance("BKS");
        devicesStore.load(in, password);

        for (Entry<String, String> device : deviceNames.entrySet()) {
            X509Certificate deviceCert = (X509Certificate) devicesStore.getCertificate(device.getKey());
            devices.put(device.getValue(), deviceCert);
        }

        // ENTRY 7: contacts.vcard
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for contacts.");
            throw new IllegalArgumentException("Could not find entry for contacts.");
        }

        File contacts = File.createTempFile("panbox" + (new Random().nextInt(65536) - 32768), null);
        FileOutputStream fos = new FileOutputStream(contacts);
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.flush();
        fos.close();

        // ENTRY 8: ownerKeyStore/ownerCertStore.jks
        entry = in.getNextEntry();

        ByteArrayOutputStream tmp = new ByteArrayOutputStream();
        IOUtils.copy(in, tmp);
        ByteArrayInputStream buf = new ByteArrayInputStream(tmp.toByteArray());

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for owner key store.");
            throw new IllegalArgumentException("Could not find entry for owner key store.");
        }

        KeyStore ownerKeyStore = null;
        try {
            // Check if pairing is MASTER
            ownerKeyStore = KeyStore.getInstance("PKCS12");
            ownerKeyStore.load(buf, password);
            // At this point we know it's a PKCS11 file!
            PrivateKey ownerEncKey = (PrivateKey) ownerKeyStore.getKey("ownerEncKey", password);
            Certificate[] ownerEncCert = ownerKeyStore.getCertificateChain("ownerEncKey");
            PrivateKey ownerSignKey = (PrivateKey) ownerKeyStore.getKey("ownerSignKey", password);
            Certificate[] ownerSignCert = ownerKeyStore.getCertificateChain("ownerSignKey");
            in.close();
            removeInputFile(inputFile);

            return new PanboxFilePairingLoadReturnContainer(eMail, firstName, lastName, password, devicename,
                    devPKey, devCert[0], ownerSignKey, ownerSignCert[0], ownerEncKey, ownerEncCert[0], devices,
                    contacts);
        } catch (Exception e) {
            // SLAVE
            try {
                buf = new ByteArrayInputStream(tmp.toByteArray());
                ownerKeyStore = KeyStore.getInstance("BKS");
                ownerKeyStore.load(buf, password);
                Certificate ownerEncCert = ownerKeyStore.getCertificate("ownerEncCert");
                Certificate ownerSignCert = ownerKeyStore.getCertificate("ownerSignCert");
                in.close();
                removeInputFile(inputFile);

                return new PanboxFilePairingLoadReturnContainer(eMail, firstName, lastName, password,
                        devicename, devPKey, devCert[0], null, ownerSignCert, null, ownerEncCert, devices,
                        contacts);
            } catch (Exception ex) {
                logger.error(
                        "PanboxClient : loadPairingFile : Could not determine if pairing file was master or slave.");
                throw new IllegalArgumentException("Pairing type was unknown. Broken file?");
            }
        }
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
            | UnrecoverableKeyException | IllegalArgumentException e) {
        in.close();
        throw e;
    }

}

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

/**
 * Extract all files from Tar into the specified directory
 * /*  w w  w.  j a v a 2  s . c  o  m*/
 * @param tarFile
 * @param directory
 * @return the list of extracted filenames
 * @throws IOException
 */
public static List<String> unZip(File tarFile, File directory) throws IOException {
    List<String> result = new ArrayList<String>();
    InputStream inputStream = new FileInputStream(tarFile);
    ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream);
    ZipArchiveEntry entry = in.getNextZipEntry();
    while (entry != null) {
        if (entry.isDirectory()) {
            entry = in.getNextZipEntry();
            continue;
        }
        File curfile = new File(directory, entry.getName());
        File parent = curfile.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(curfile);
        IOUtils.copy(in, out);
        out.close();
        result.add(entry.getName());
        entry = in.getNextZipEntry();
    }
    in.close();
    return result;
}

From source file:org.xwiki.xar.XarPackage.java

/**
 * Find and add the entries located in the passed XAR file.
 * // ww  w. ja va2  s. c  o  m
 * @param xarStream an input stream to a XAR file
 * @throws IOException when failing to read the file
 * @throws XarException when failing to parse the XAR package
 */
public void read(InputStream xarStream) throws IOException, XarException {
    ZipArchiveInputStream zis = new ZipArchiveInputStream(xarStream, "UTF-8", false);

    try {
        for (ZipArchiveEntry entry = zis.getNextZipEntry(); entry != null; entry = zis.getNextZipEntry()) {
            if (!entry.isDirectory() && zis.canReadEntryData(entry)) {
                readEntry(zis, entry);
            }
        }
    } finally {
        zis.close();
    }
}