Example usage for java.util.zip ZipInputStream getNextEntry

List of usage examples for java.util.zip ZipInputStream getNextEntry

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream getNextEntry.

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java

public void unpackBundleZipToFS(String bundle_path, File fs_path) {
    URL zip_url = fBundle.getEntry(bundle_path);
    TestCase.assertNotNull(zip_url);// www. ja  v a2s  . c  om

    if (!fs_path.isDirectory()) {
        TestCase.assertTrue(fs_path.mkdirs());
    }

    try {
        InputStream in = zip_url.openStream();
        TestCase.assertNotNull(in);
        byte tmp[] = new byte[4 * 1024];
        int cnt;

        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry ze;

        while ((ze = zin.getNextEntry()) != null) {
            // System.out.println("Entry: \"" + ze.getName() + "\"");
            File entry_f = new File(fs_path, ze.getName());
            if (ze.getName().endsWith("/")) {
                // Directory
                continue;
            }
            if (!entry_f.getParentFile().exists()) {
                TestCase.assertTrue(entry_f.getParentFile().mkdirs());
            }
            FileOutputStream fos = new FileOutputStream(entry_f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length);

            while ((cnt = zin.read(tmp, 0, tmp.length)) > 0) {
                bos.write(tmp, 0, cnt);
            }
            bos.flush();
            bos.close();
            fos.close();

            zin.closeEntry();
        }
        zin.close();
    } catch (IOException e) {
        e.printStackTrace();
        TestCase.fail("Failed to unpack zip file: " + e.getMessage());
    }
}

From source file:io.fabric8.maven.generator.springboot.SpringBootGenerator.java

private void copyFilesToFatJar(List<File> libs, List<File> classes, File target) throws IOException {
    File tmpZip = File.createTempFile(target.getName(), null);
    tmpZip.delete();

    // Using Apache commons rename, because renameTo has issues across file systems
    FileUtils.moveFile(target, tmpZip);/*from w  w  w .  ja  va2s  .  c  om*/

    byte[] buffer = new byte[8192];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
    for (ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()) {
        if (matchesFatJarEntry(libs, ze.getName(), true) || matchesFatJarEntry(classes, ze.getName(), false)) {
            continue;
        }
        out.putNextEntry(ze);
        for (int read = zin.read(buffer); read > -1; read = zin.read(buffer)) {
            out.write(buffer, 0, read);
        }
        out.closeEntry();
    }

    for (File lib : libs) {
        try (InputStream in = new FileInputStream(lib)) {
            out.putNextEntry(createZipEntry(lib, getFatJarFullPath(lib, true)));
            for (int read = in.read(buffer); read > -1; read = in.read(buffer)) {
                out.write(buffer, 0, read);
            }
            out.closeEntry();
        }
    }

    for (File cls : classes) {
        try (InputStream in = new FileInputStream(cls)) {
            out.putNextEntry(createZipEntry(cls, getFatJarFullPath(cls, false)));
            for (int read = in.read(buffer); read > -1; read = in.read(buffer)) {
                out.write(buffer, 0, read);
            }
            out.closeEntry();
        }
    }

    out.close();
    tmpZip.delete();
}

From source file:aurelienribon.gdxsetupui.ProjectSetup.java

/**
 * The raw structure of all projects is contained in a zip file. This
 * method inflates this file in a temporary folder.
 * @throws IOException/*from  w ww .j a  v a  2  s .com*/
 */
public void inflateProjects() throws IOException {
    FileUtils.forceMkdir(tmpDst);
    FileUtils.cleanDirectory(tmpDst);

    InputStream is = Res.getStream("projects.zip");
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;

    while ((entry = zis.getNextEntry()) != null) {
        File file = new File(tmpDst, entry.getName());
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(file);
        } else {
            OutputStream os = new FileOutputStream(file);
            IOUtils.copy(zis, os);
            os.close();
        }
    }

    zis.close();
}

From source file:com.haha01haha01.harail.DatabaseDownloader.java

private boolean unpackZip(File output_dir, File zipname) {
    InputStream is;//from w ww.  j  av a  2 s. c om
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(zipname);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        while ((ze = zis.getNextEntry()) != null) {
            filename = ze.getName();

            // Need to create directories if not exists, or
            // it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(output_dir, filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(new File(output_dir, filename));

            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

            fout.close();
            zis.closeEntry();
        }

        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;//from   w  w  w. j av  a 2  s  .com
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            break;
        }
    }
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    if (null == zipEntry) {
        return signatureInfos;
    }
    XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);
    Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream);
    NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
        Element signatureElement = (Element) signatureNodeList.item(idx);
        xadesValidation.prepareDocument(signatureElement);

        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
        ZIPURIDereferencer dereferencer = new ZIPURIDereferencer(document);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean valid = xmlSignature.validate(domValidateContext);
        if (!valid) {
            continue;
        }

        // check whether all files have been signed properly
        SignedInfo signedInfo = xmlSignature.getSignedInfo();
        @SuppressWarnings("unchecked")
        List<Reference> references = signedInfo.getReferences();
        Set<String> referenceUris = new HashSet<String>();
        for (Reference reference : references) {
            String referenceUri = reference.getURI();
            referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8"));
        }
        zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
        while (null != (zipEntry = zipInputStream.getNextEntry())) {
            if (ODFUtil.isSignatureFile(zipEntry)) {
                continue;
            }
            if (!referenceUris.contains(zipEntry.getName())) {
                LOG.warn("no ds:Reference for ZIP entry: " + zipEntry.getName());
                return signatureInfos;
            }
        }

        if (null != originalDocument) {
            for (Reference reference : references) {
                if (null != reference.getType()) {
                    /*
                       * We skip XAdES and eID identity ds:Reference.
                       */
                    continue;
                }
                String digestAlgo = reference.getDigestMethod().getAlgorithm();
                LOG.debug("ds:Reference digest algo: " + digestAlgo);
                String referenceUri = reference.getURI();
                LOG.debug("ds:Reference URI: " + referenceUri);
                byte[] digestValue = reference.getDigestValue();

                org.apache.xml.security.signature.XMLSignature xmldsig = new org.apache.xml.security.signature.XMLSignature(
                        documentSignaturesDocument, "",
                        org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
                        Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS);
                xmldsig.addDocument(referenceUri, null, digestAlgo);
                ResourceResolverSpi zipResourceResolver = new ZIPResourceResolver(originalDocument);
                xmldsig.addResourceResolver(zipResourceResolver);
                org.apache.xml.security.signature.SignedInfo apacheSignedInfo = xmldsig.getSignedInfo();
                org.apache.xml.security.signature.Reference apacheReference = apacheSignedInfo.item(0);
                apacheReference.generateDigestValue();
                byte[] originalDigestValue = apacheReference.getDigestValue();
                if (!Arrays.equals(originalDigestValue, digestValue)) {
                    throw new RuntimeException("not original document");
                }
            }
            /*
             * So we already checked whether no files were changed, and that
             * no files were added compared to the original document. Still
             * have to check whether no files were removed.
             */
            ZipInputStream originalZipInputStream = new ZipInputStream(
                    new ByteArrayInputStream(originalDocument));
            ZipEntry originalZipEntry;
            Set<String> referencedEntryNames = new HashSet<String>();
            for (Reference reference : references) {
                if (null != reference.getType()) {
                    continue;
                }
                referencedEntryNames.add(reference.getURI());
            }
            while (null != (originalZipEntry = originalZipInputStream.getNextEntry())) {
                if (ODFUtil.isSignatureFile(originalZipEntry)) {
                    continue;
                }
                if (!referencedEntryNames.contains(originalZipEntry.getName())) {
                    LOG.warn("missing ds:Reference for ZIP entry: " + originalZipEntry.getName());
                    throw new RuntimeException(
                            "missing ds:Reference for ZIP entry: " + originalZipEntry.getName());
                }
            }
        }

        X509Certificate signer = keySelector.getCertificate();
        SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature,
                signatureElement, signer);
        signatureInfos.add(signatureInfo);
    }
    return signatureInfos;
}

From source file:msearch.io.MSFilmlisteLesen.java

private boolean filmlisteEntpackenKopieren(File vonDatei, File nachDatei) {
    boolean ret = false;
    String vonDateiName = vonDatei.getName();
    BufferedInputStream in;/*from   w w w.ja  va 2  s .  com*/
    if (vonDateiName.equals(nachDatei.getName())) {
        return true;
    }
    try {
        if (vonDatei.getName().endsWith(MSConst.FORMAT_XZ)) {
            in = new BufferedInputStream(new XZInputStream(new FileInputStream(vonDatei)));
        } else if (vonDateiName.endsWith(MSConst.FORMAT_BZ2)) {
            in = new BufferedInputStream(new BZip2CompressorInputStream(new FileInputStream(vonDatei)));
        } else if (vonDateiName.endsWith(MSConst.FORMAT_ZIP)) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(vonDatei));
            zipInputStream.getNextEntry();
            in = new BufferedInputStream(zipInputStream);
        } else {
            Files.copy(Paths.get(vonDatei.getPath()), Paths.get(nachDatei.getPath()),
                    StandardCopyOption.REPLACE_EXISTING);
            return true;
            //in = new BufferedInputStream(new FileInputStream(vonDatei));
        }
        FileOutputStream fOut;
        byte[] buffer = new byte[1024];
        int n = 0;
        int count = 0;
        int countMax;
        if (vonDateiName.endsWith(MSConst.FORMAT_XZ) || vonDateiName.endsWith(MSConst.FORMAT_BZ2)
                || vonDateiName.endsWith(MSConst.FORMAT_ZIP)) {
            countMax = 44;
        } else {
            countMax = 250;
        }
        fOut = new FileOutputStream(nachDatei);
        this.notifyProgress(vonDateiName);
        while (!MSConfig.getStop() && (n = in.read(buffer)) != -1) {
            fOut.write(buffer, 0, n);
            ++count;
            if (count > countMax) {
                this.notifyProgress(vonDateiName);
                count = 0;
            }
        }
        if (MSConfig.getStop()) {
            ret = false;
        } else {
            ret = true;
        }
        try {
            fOut.close();
            in.close();
        } catch (Exception e) {
        }
    } catch (Exception ex) {
        MSLog.fehlerMeldung(915236765, MSLog.FEHLER_ART_PROG,
                "MSearchIoXmlFilmlisteLesen.filmlisteEntpackenKopieren", ex);
    }
    return ret;
}

From source file:ml.shifu.shifu.util.IndependentTreeModelUtils.java

public boolean convertZipSpecToBinary(File zipSpecFile, File outputGbtFile) {
    ZipInputStream zipInputStream = null;
    FileOutputStream fos = null;/*from  w w w .  j  a va 2  s.co  m*/

    try {
        zipInputStream = new ZipInputStream(new FileInputStream(zipSpecFile));
        IndependentTreeModel treeModel = null;
        List<List<TreeNode>> trees = null;

        ZipEntry zipEntry = null;
        do {
            zipEntry = zipInputStream.getNextEntry();
            if (zipEntry != null) {
                if (zipEntry.getName().equals(MODEL_CONF)) {
                    ByteArrayOutputStream byos = new ByteArrayOutputStream();
                    IOUtils.copy(zipInputStream, byos);
                    treeModel = JSONUtils.readValue(new ByteArrayInputStream(byos.toByteArray()),
                            IndependentTreeModel.class);
                } else if (zipEntry.getName().equals(MODEL_TREES)) {
                    DataInputStream dataInputStream = new DataInputStream(zipInputStream);
                    int size = dataInputStream.readInt();
                    trees = new ArrayList<List<TreeNode>>(size);
                    for (int i = 0; i < size; i++) {
                        int forestSize = dataInputStream.readInt();
                        List<TreeNode> forest = new ArrayList<TreeNode>(forestSize);
                        for (int j = 0; j < forestSize; j++) {
                            TreeNode treeNode = new TreeNode();
                            treeNode.readFields(dataInputStream);
                            forest.add(treeNode);
                        }
                        trees.add(forest);
                    }
                }
            }
        } while (zipEntry != null);

        if (treeModel != null && CollectionUtils.isNotEmpty(trees)) {
            treeModel.setTrees(trees);
            fos = new FileOutputStream(outputGbtFile);
            treeModel.saveToInputStream(fos);
        } else {
            return false;
        }
    } catch (IOException e) {
        logger.error("Error occurred when convert the zip format model to binary.", e);
        return false;
    } finally {
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(fos);
    }

    return true;
}

From source file:com.nkapps.billing.services.BankStatementServiceImpl.java

@Override
public File extractedFile(File file) throws Exception {
    File extractedFile = null;/*from   w  ww  .  j  a  va  2  s .  co m*/

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        String extFileName = ze.getName();
        extractedFile = new File(getUploadDir() + File.separator + extFileName);
        if (!extractedFile.exists()) {
            extractedFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(extractedFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();

    return extractedFile;
}

From source file:org.businessmanager.geodb.OpenGeoDBImpl.java

private void init() {
    InputStream rs = getClass().getClassLoader().getResourceAsStream("geodb.zip");
    ZipInputStream zipInputStream = new ZipInputStream(rs);
    ZipEntry ze;/*from  w  w  w. j ava 2s .  c  o  m*/
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream, "UTF-8"));

        while ((ze = zipInputStream.getNextEntry()) != null) {
            String lname = ze.getName().substring(0, ze.getName().lastIndexOf(".tab")).toLowerCase();

            String line;
            OpenGeoDBMapper mapper = new OpenGeoDBMapper();

            while ((line = reader.readLine()) != null) {

                if (line.length() > 0) {
                    if (line.startsWith("#"))
                        continue;
                    OpenGeoEntry entry = OpenGeoEntry.fromCSVLine(line, "\t");

                    if (entry != null) {
                        String[] plz = entry.getPlz();

                        for (String plzEntry : plz) {
                            mapper.putZipCode(plzEntry.trim(), entry);
                        }
                        mapper.putAreaCode(entry.getVorwahl(), entry);
                    }
                }

            }
            mappers.put(lname, mapper);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.griddynamics.deming.ecommerce.api.endpoint.catalog.CatalogManagerEndpoint.java

@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importCatalog(@FormDataParam("file") InputStream uploadInputStream)
        throws ServiceException, IOException {
    removeCatalog();//from w ww .  j av  a2  s . co  m

    try {
        ZipInputStream inputStream = new ZipInputStream(uploadInputStream);

        try {
            byte[] buf = new byte[1024];

            for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
                    .getNextEntry()) {
                try {
                    String entryName = entry.getName();
                    entryName = entryName.replace('/', File.separatorChar);
                    entryName = entryName.replace('\\', File.separatorChar);

                    LOGGER.debug("Entry name: {}", entryName);

                    if (entry.isDirectory()) {
                        LOGGER.debug("Entry ({}) is directory", entryName);
                    } else if (PRODUCT_CATALOG_FILE.equals(entryName)) {
                        ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream(1024);

                        for (int n = inputStream.read(buf, 0, 1024); n > -1; n = inputStream.read(buf, 0,
                                1024)) {
                            jsonBytes.write(buf, 0, n);
                        }

                        byte[] bytes = jsonBytes.toByteArray();

                        ObjectMapper mapper = new ObjectMapper();

                        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
                        mapper.registerModule(jaxbAnnotationModule);

                        ImportCategoryWrapper catalog = mapper.readValue(bytes, ImportCategoryWrapper.class);
                        escape(catalog);
                        saveCategoryTree(catalog);
                    } else {
                        MultipartFile file = new MultipartFileAdapter(inputStream, entryName);
                        dmgStaticAssetStorageService.createStaticAssetStorageFromFile(file);
                    }

                } finally {
                    inputStream.closeEntry();
                }
            }
        } finally {
            inputStream.close();
        }

    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Unable load catalog.\n").build();
    }

    Thread rebuildSearchIndex = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
                searchService.rebuildIndex();
            } catch (Exception e) {
                /* nothing */}
        }
    });
    rebuildSearchIndex.start();

    return Response.status(Response.Status.OK).entity("Catalog was imported successfully!\n").build();
}