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

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

Introduction

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

Prototype

public ArchiveEntry getNextEntry() throws IOException 

Source Link

Usage

From source file:com.glaf.core.util.ZipUtils.java

/**
 * /*from ww w . ja  v  a  2 s  . com*/
 * zip
 * 
 * @param zipFilePath
 *            zip,  "/var/data/aa.zip"
 * 
 * @param saveFileDir
 *            ?, "/var/test/"
 */
public static void decompressZip(String zipFilePath, String saveFileDir) {
    if (isEndsWithZip(zipFilePath)) {
        File file = new File(zipFilePath);
        if (file.exists() && file.isFile()) {
            InputStream inputStream = null;
            ZipArchiveInputStream zais = null;
            try {
                inputStream = new FileInputStream(file);
                zais = new ZipArchiveInputStream(inputStream);
                ArchiveEntry archiveEntry = null;
                while ((archiveEntry = zais.getNextEntry()) != null) {
                    String entryFileName = archiveEntry.getName();
                    String entryFilePath = saveFileDir + entryFileName;
                    byte[] content = new byte[(int) archiveEntry.getSize()];
                    zais.read(content);
                    OutputStream os = null;
                    try {
                        File entryFile = new File(entryFilePath);
                        os = new BufferedOutputStream(new FileOutputStream(entryFile));
                        os.write(content);
                    } catch (IOException e) {
                        throw new IOException(e);
                    } finally {
                        IOUtils.closeStream(os);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeStream(zais);
                IOUtils.closeStream(inputStream);
            }
        }
    }
}

From source file:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid./*from  w  w w. jav  a 2s  . c  o m*/
 *
 * @param is The stream
 * @return
 * @throws java.io.IOException
 */
public TriangleMesh[] loadMeshes(InputStream is) throws IOException {
    ZipArchiveInputStream zis = null;
    TriangleMesh[] ret_val = null;

    try {
        zis = new ZipArchiveInputStream(is);

        ArchiveEntry entry = null;
        int cnt = 0;

        while ((entry = zis.getNextEntry()) != null) {
            // TODO: not sure we can depend on this being first
            if (entry.getName().equals("manifest.xml")) {
                mf = parseManifest(zis);

                ret_val = new TriangleMesh[mf.getParts().size()];
            } else {
                MeshReader reader = new MeshReader(zis, "", FilenameUtils.getExtension(entry.getName()));
                IndexedTriangleSetBuilder its = new IndexedTriangleSetBuilder();
                reader.getTriangles(its);

                // TODO: in this case we could return a less heavy triangle mesh struct?
                WingedEdgeTriangleMesh mesh = new WingedEdgeTriangleMesh(its.getVertices(), its.getFaces());
                ret_val[cnt++] = mesh;
            }
        }
    } finally {
        zis.close();
    }

    return ret_val;
}

From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializer.java

/**
 * Deserializes the identified stream ({@code streamId}) from the supplied input stream into the package state.
 * If {@code streamId} is {@code null}, then all streams found in the supplied input stream are deserialized to
 * {@code state}.//from w ww  . j a  v a2  s  .c o  m
 * <p>
 * If the specified stream is not found, this method will do nothing.  If an unrecognized stream is encountered, it
 * will be skipped.
 * </p>
 * <p>
 * An unrecognized stream is a Zip entry with a name that is not present in the {@code StreamId enum}.  Unrecognized
 * streams can be encountered when the supplied {@code streamId} is {@code null}.
 * </p>
 *
 * @param state the package state to be populated
 * @param streamId the stream to be deserialized, may be {@code null} to specify all streams found in the supplied
 *                 input stream
 * @param in the input stream containing the identified {@code streamId}
 * @throws RuntimeException when there are errors accessing fields of the state using reflection
 * @throws StreamChecksumMismatch when {@code failOnChecksumMismatch} is {@code true} and a checksum mismatch is
 *                                encountered
 */
void deserialize(PackageState state, StreamId streamId, ZipArchiveInputStream in) {
    ArchiveEntry entry;
    Object deserializedStream;
    boolean all = streamId == null;

    // deserialize the specified stream identifier (or all stream identifiers if streamId is null) from the
    // inputStream to the package state

    try {
        while ((entry = in.getNextEntry()) != null) {
            if (entry.getSize() == 0) {
                // Skip empty entries
                continue;
            }
            if (all || streamId.name().equals(entry.getName())) {
                if (all) {
                    try {
                        streamId = StreamId.valueOf(entry.getName().toUpperCase());
                    } catch (IllegalArgumentException e) {
                        LOG.warn(String.format(WARN_UNKNOWN_STREAM, entry.getName().toUpperCase()));
                        continue;
                    }
                }

                if (!hasPropertyDescription(streamId)) {
                    throw new NullPointerException(String.format(ERR_MISSING_DESCRIPTOR, streamId));
                }
                if (!hasUnmarshaller(streamId)) {
                    throw new NullPointerException(
                            String.format(ERR_MISSING_SPRINGMARSHALLER, streamId, streamId));
                }

                CRC32CalculatingInputStream crcIn = new CRC32CalculatingInputStream(in);
                long expectedCrc = ((ZipArchiveEntry) entry).getCrc();

                deserializedStream = marshallerMap.get(streamId).getUnmarshaller()
                        .unmarshal(new StreamSource(crcIn));

                long actualCrc = crcIn.resetCrc();
                if (actualCrc != expectedCrc) {
                    if (failOnChecksumMismatch) {
                        throw new StreamChecksumMismatch(String.format(WARN_CRC_MISMATCH, streamId,
                                Long.toHexString(expectedCrc), Long.toHexString(actualCrc)));
                    } else {
                        LOG.warn(String.format(WARN_CRC_MISMATCH, streamId, Long.toHexString(expectedCrc),
                                Long.toHexString(actualCrc)));
                    }
                }
                propertyDescriptors.get(streamId).getWriteMethod().invoke(state, deserializedStream);
            }
        }
    } catch (StreamChecksumMismatch e) {
        throw e; // don't wrap this exception, throw it as-is per Javadoc
    } catch (Exception e) {
        if (streamId == null) {
            throw new RuntimeException(String.format(ERR_UNMARSHALLING_ARCHIVE, e.getMessage()), e);
        } else {
            throw new RuntimeException(
                    String.format(ERR_UNMARSHALLING_STREAMID_ARCHIVE, streamId, e.getMessage()), e);
        }
    }
}

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 av a2  s .co  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.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  w w w .  j a  v  a 2  s.  c o m*/

    // 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  www.  j  av a2  s.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 {/*from w ww.j  av  a  2s. 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.slc.sli.ingestion.landingzone.ZipFileUtilTest.java

private void assertTargetMatchesZip(File targetDir, File zipFile) throws IOException {
    InputStream zipStream = null;
    ZipArchiveInputStream zipFileStrm = null;
    try {// w w  w.  ja  va2  s  . com
        zipStream = new BufferedInputStream(new FileInputStream(zipFile));
        zipFileStrm = new ZipArchiveInputStream(zipStream);

        ArchiveEntry entry;
        ArrayList<String> zipFileSet = new ArrayList<String>();
        while ((entry = zipFileStrm.getNextEntry()) != null) {
            zipFileSet.add(File.separator + entry.getName().replace('/', File.separatorChar));
        }

        ArrayList<String> extractedFileSet = new ArrayList<String>();
        addExtractedFiles(targetDir, File.separator, extractedFileSet);
        Collections.sort(zipFileSet);
        Collections.sort(extractedFileSet);

        Assert.assertEquals(extractedFileSet, zipFileSet);
    } finally {
        IOUtils.closeQuietly(zipStream);
        IOUtils.closeQuietly(zipFileStrm);
    }
}

From source file:org.sourcepit.tools.shared.resources.internal.harness.SharedResourcesUtils.java

private static void importArchive(ZipArchiveInputStream zipIn, String archiveEntry, File outDir,
        boolean keepArchivePaths, String encoding, IFilteredCopier copier, IFilterStrategy strategy)
        throws IOException {
    boolean found = false;

    ArchiveEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        final String entryName = entry.getName();

        if (archiveEntry == null || entryName.startsWith(archiveEntry + "/")
                || entryName.equals(archiveEntry)) {
            found = true;/*from   www  . ja  va 2s .  co  m*/

            boolean isDir = entry.isDirectory();

            final String fileName;
            if (archiveEntry == null || keepArchivePaths) {
                fileName = entryName;
            } else {
                if (entryName.startsWith(archiveEntry + "/")) {
                    fileName = entryName.substring(archiveEntry.length() + 1);
                } else if (!isDir && entryName.equals(archiveEntry)) {
                    fileName = new File(entryName).getName();
                } else {
                    throw new IllegalStateException();
                }
            }

            final File file = new File(outDir, fileName);
            if (entry.isDirectory()) {
                file.mkdir();
            } else {
                file.createNewFile();
                OutputStream out = new FileOutputStream(file);
                try {
                    if (copier != null && strategy.filter(fileName)) {
                        copy(zipIn, out, encoding, copier, file);
                    } else {
                        IOUtils.copy(zipIn, out);
                    }
                } finally {
                    IOUtils.closeQuietly(out);
                }
            }
        }
        entry = zipIn.getNextEntry();
    }

    if (!found) {
        throw new FileNotFoundException(archiveEntry);
    }
}

From source file:org.xwiki.extension.xar.internal.handler.packager.Packager.java

private XarMergeResult importXARToWiki(String comment, InputStream xarInputStream, WikiReference wikiReference,
        PackageConfiguration configuration)
        throws IOException, ComponentLookupException, XWikiException, FilterException {
    XarMergeResult mergeResult = new XarMergeResult();

    ZipArchiveInputStream zis = new ZipArchiveInputStream(xarInputStream);

    XWikiContext xcontext = this.xcontextProvider.get();

    String currentWiki = xcontext.getWikiId();
    try {//from   w  w  w.  java  2 s  .com
        xcontext.setWikiId(wikiReference.getName());

        this.observation.notify(new XARImportingEvent(), null, xcontext);

        for (ArchiveEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
            if (!entry.isDirectory()) {
                // Only import what should be imported
                if (!entry.getName().equals(XarModel.PATH_PACKAGE)
                        && (configuration.getEntriesToImport() == null
                                || configuration.getEntriesToImport().contains(entry.getName()))) {
                    XarEntryMergeResult entityMergeResult = importDocumentToWiki(comment, wikiReference, zis,
                            configuration);
                    if (entityMergeResult != null) {
                        mergeResult.addMergeResult(entityMergeResult);
                    }
                }
            }
        }
    } finally {
        this.observation.notify(new XARImportedEvent(), null, xcontext);

        xcontext.setWikiId(currentWiki);
    }

    return mergeResult;
}