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:com.adobe.communities.ugc.migration.importer.GenericUGCImporter.java

protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    UGCImportHelper.checkUserPrivileges(request.getResourceResolver(), rrf);

    ResourceResolver resolver;/* ww w  .j a v  a 2s . co  m*/
    try {
        resolver = serviceUserWrapper.getServiceResourceResolver(rrf,
                Collections.<String, Object>singletonMap(ResourceResolverFactory.SUBSERVICE, UGC_WRITER));
    } catch (final LoginException e) {
        throw new ServletException("Not able to invoke service user");
    }

    // finally get the uploaded file
    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()) {

        if (fileRequestParameters[0].getFileName().endsWith(".json")) {
            // if upload is a single json file...

            // get the resource we'll be adding new content to
            final String path = request.getRequestParameter("path").getString();
            final Resource resource = resolver.getResource(path);
            if (resource == null) {
                resolver.close();
                throw new ServletException("Could not find a valid resource for import");
            }
            final InputStream inputStream = fileRequestParameters[0].getInputStream();
            final JsonParser jsonParser = new JsonFactory().createParser(inputStream);
            jsonParser.nextToken(); // get the first token

            importFile(jsonParser, resource, resolver);
        } else if (fileRequestParameters[0].getFileName().endsWith(".zip")) {
            ZipInputStream zipInputStream;
            try {
                zipInputStream = new ZipInputStream(fileRequestParameters[0].getInputStream());
            } catch (IOException e) {
                resolver.close();
                throw new ServletException("Could not open zip archive");
            }

            try {
                final RequestParameter[] paths = request.getRequestParameters("path");
                int counter = 0;
                ZipEntry zipEntry = zipInputStream.getNextEntry();
                while (zipEntry != null && paths.length > counter) {
                    final String path = paths[counter].getString();
                    final Resource resource = resolver.getResource(path);
                    if (resource == null) {
                        resolver.close();
                        throw new ServletException("Could not find a valid resource for import");
                    }

                    final JsonParser jsonParser = new JsonFactory().createParser(zipInputStream);
                    jsonParser.nextToken(); // get the first token
                    importFile(jsonParser, resource, resolver);
                    zipInputStream.closeEntry();
                    zipEntry = zipInputStream.getNextEntry();
                    counter++;
                }
            } finally {
                zipInputStream.close();
            }
        } else {
            resolver.close();
            throw new ServletException("Unrecognized file input type");
        }
    } else {
        resolver.close();
        throw new ServletException("No file provided for UGC data");
    }
    resolver.close();
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java

private Map<String, String> getResources(byte[] document)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {

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

    ByteArrayInputStream bais = new ByteArrayInputStream(document);
    ZipInputStream zipInputStream = new ZipInputStream(bais);
    ZipEntry zipEntry;//from w w  w .j a va 2 s  . com
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!"[Content_Types].xml".equals(zipEntry.getName())) {
            continue;
        }
        Document contentTypesDocument = OOXMLSignatureFacet.loadDocument(zipInputStream);
        Element nsElement = contentTypesDocument.createElement("ns");
        nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
                "http://schemas.openxmlformats.org/package/2006/content-types");

        for (String contentType : OOXMLSignatureFacet.contentTypes) {
            NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument,
                    "/tns:Types/tns:Override[@ContentType='" + contentType + "']/@PartName", nsElement);
            for (int nodeIdx = 0; nodeIdx < nodeList.getLength(); nodeIdx++) {
                String partName = nodeList.item(nodeIdx).getTextContent();
                LOG.debug("part name: " + partName);
                partName = partName.substring(1); // remove '/'
                signatureResources.put(partName, contentType);
            }
        }
        break;
    }
    return signatureResources;
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java

public void unZip(String zipFile, String outputFolder) {
    byte[] buffer = new byte[1024];

    try {//from   w  ww . ja  v a 2  s .co m
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));

        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);

            log.info("file unzip : " + newFile.getAbsoluteFile());

            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:io.gromit.geolite2.geonames.CityFinder.java

/**
 * Read cities./*w  w  w . j  a va  2 s.co  m*/
 *
 * @param citiesLocationUrl the cities location url
 * @return the city finder
 */
private CityFinder readCities(String citiesLocationUrl) {
    ZipInputStream zipis = null;
    CsvParserSettings settings = new CsvParserSettings();
    settings.setSkipEmptyLines(true);
    settings.trimValues(true);
    CsvFormat format = new CsvFormat();
    format.setDelimiter('\t');
    format.setLineSeparator("\n");
    format.setComment('\0');
    format.setCharToEscapeQuoteEscaping('\0');
    format.setQuote('\0');
    settings.setFormat(format);
    CsvParser parser = new CsvParser(settings);
    try {
        zipis = new ZipInputStream(new URL(citiesLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }
        RTree<City, Geometry> rtreeRead = RTree.create();
        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));
        for (String[] entry : lines) {
            City city = new City();
            city.setGeonameId(Integer.decode(entry[0]));
            city.setName(entry[1]);
            try {
                try {
                    city.setLatitude(Double.valueOf(entry[2]));
                    city.setLongitude(Double.valueOf(entry[3]));
                    rtreeRead = rtreeRead.add(city,
                            Geometries.pointGeographic(city.getLongitude(), city.getLatitude()));
                } catch (NumberFormatException | NullPointerException e) {
                }
                city.setCountryIsoCode(entry[4]);
                city.setSubdivisionOne(entry[5]);
                city.setSubdivisionTwo(entry[6]);
                city.setTimeZone(entry[7]);
            } catch (ArrayIndexOutOfBoundsException e) {
            }
            geonameMap.put(city.getGeonameId(), city);
        }
        this.rtree = rtreeRead;
        logger.info("loaded " + geonameMap.size() + " cities");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}

From source file:com.informatica.um.binge.api.impl.PluginsFactory.java

/**
 *  Extract the zip file into the output folder
 * @param fileName - Name of the zip file
 * @param outFolderName - output folder name.
 * @throws Exception/*  w  ww .  jav  a2  s  .  c o  m*/
 */
protected Multimap<String, File> extractZipFile(String fileName, String outFolderName) throws Exception {
    LOG.debug("Going to extract zip file {} to folder {}", fileName, outFolderName);
    Multimap<String, File> deps = HashMultimap.create(2, 5);
    File outFolder = new File(outFolderName);
    ZipInputStream zipInput = new ZipInputStream(new FileInputStream(new File(fileName)));
    ZipEntry ze = null;
    boolean status = outFolder.mkdirs();
    if (status)
        LOG.info("Successfully created  plugin folder  {}", outFolder.getAbsolutePath());
    else {
        throw new VDSException(VDSErrorCode.PLUGIN_FOLDER_CREATE_ERROR, outFolder.getAbsolutePath());
    }

    byte[] buffer = new byte[1024];
    while ((ze = zipInput.getNextEntry()) != null) {
        String name = ze.getName();
        // process files only
        if (ze.isDirectory() == false) {
            File file = new File(name);
            File newFile = null;
            if (file.getParentFile() != null && file.getParentFile().getName().equals(NATIVE)) {
                newFile = new File(nativeLibs, file.getName());
            } else if (file.getParentFile() != null && file.getParentFile().getName().equals(LIB)) {
                newFile = Paths.get(outFolderName, LIB, file.getName()).toFile();
                deps.put(LIB, newFile);
            } else {
                newFile = new File(outFolderName, file.getName());
                if (name.endsWith(".jar"))
                    deps.put(LIB, newFile);
            }
            newFile.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zipInput.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
        }
    }
    return deps;
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

public void importFromZipStep2(InputStream is) throws WPBIOException {
    ZipInputStream zis = new ZipInputStream(is);
    // we need to stop the notifications during import
    dataStorage.stopNotifications();/*www  .ja va 2 s.  co  m*/
    try {
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null) {
            String name = ze.getName();
            if (name.indexOf(PATH_SITE_PAGES) >= 0) {
                if (name.indexOf("pageSource.txt") >= 0) {
                    importWebPageSource(zis, ze.getName());
                }
            } else if (name.indexOf(PATH_SITE_PAGES_MODULES) >= 0) {
                if (name.indexOf("moduleSource.txt") >= 0) {
                    importWebPageModuleSource(zis, ze.getName());
                }
            } else if (name.indexOf(PATH_ARTICLES) >= 0) {
                if (name.indexOf("articleSource.txt") >= 0) {
                    importArticleSource(zis, ze.getName());
                }
            } else if (name.indexOf(PATH_FILES) >= 0) {
                if (name.indexOf("/content/") >= 0 && !name.endsWith("/")) {
                    importFileContent(zis, ze.getName());
                }
            }
            zis.closeEntry();
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("cannot import from  zip step 2", e);
    } finally {
        dataStorage.startNotifications();
    }
    resetCache();
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private CTTypes getContentTypes() throws IOException, JAXBException {
    URL ooxmlUrl = this.signatureService.getOfficeOpenXMLDocumentURL();
    ZipInputStream zipInputStream = new ZipInputStream(ooxmlUrl.openStream());
    ZipEntry zipEntry;/*w  ww  . j av a 2 s . co m*/
    InputStream contentTypesInputStream = null;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!"[Content_Types].xml".equals(zipEntry.getName())) {
            continue;
        }
        contentTypesInputStream = zipInputStream;
        break;
    }
    if (null == contentTypesInputStream) {
        return null;
    }
    JAXBContext jaxbContext = JAXBContext
            .newInstance(be.fedict.eid.applet.service.signer.jaxb.opc.contenttypes.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    JAXBElement<CTTypes> contentTypesElement = (JAXBElement<CTTypes>) unmarshaller
            .unmarshal(contentTypesInputStream);
    return contentTypesElement.getValue();
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java

@SuppressWarnings("unchecked")
private boolean isIdPackageObjectValid(String signatureId, XMLObject idPackageObject, byte[] document)
        throws IOException, TransformerException, SAXException, ParserConfigurationException {

    Manifest manifest;//ww  w .  j  av a 2  s.  c  o m
    SignatureProperties signatureProperties;
    if (2 != idPackageObject.getContent().size()) {
        LOG.error("Expect Manifest + SignatureProperties elements in \"idPackageObject\".");
        return false;
    }
    manifest = (Manifest) idPackageObject.getContent().get(0);
    signatureProperties = (SignatureProperties) idPackageObject.getContent().get(1);

    // Manifest
    List<Reference> refs = manifest.getReferences();
    ByteArrayInputStream bais = new ByteArrayInputStream(document);
    ZipInputStream zipInputStream = new ZipInputStream(bais);
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {

        if (validZipEntryStream(zipEntry.getName())) {
            // check relationship refs
            String relationshipReferenceURI = OOXMLSignatureFacet
                    .getRelationshipReferenceURI(zipEntry.getName());
            if (null == findReferenceFromURI(refs, relationshipReferenceURI)) {
                LOG.error("Did not find relationship ref: \"" + relationshipReferenceURI + "\"");
                if (relationshipReferenceURI.startsWith("/customXml")) {
                    continue;
                }
                return false;
            }
        }
    }

    // check streams signed
    for (Map.Entry<String, String> resourceEntry : getResources(document).entrySet()) {

        String resourceReferenceURI = OOXMLSignatureFacet.getResourceReferenceURI(resourceEntry.getKey(),
                resourceEntry.getValue());
        if (null == findReferenceFromURI(refs, resourceReferenceURI)) {
            LOG.error("Did not find resource ref: \"" + resourceReferenceURI + "\"");
            return false;
        }
    }

    // SignatureProperties
    if (signatureProperties.getProperties().size() != 1) {
        LOG.error("Unexpected # of SignatureProperty's in idPackageObject");
        return false;
    }
    if (!validateSignatureProperty((SignatureProperty) signatureProperties.getProperties().get(0),
            signatureId)) {
        return false;
    }

    return true;
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private CTRelationships getRelationships(String relsEntryName) throws IOException, JAXBException {
    URL ooxmlUrl = this.signatureService.getOfficeOpenXMLDocumentURL();
    ZipInputStream zipInputStream = new ZipInputStream(ooxmlUrl.openStream());
    ZipEntry zipEntry;//from www  . ja va 2  s.  c om
    InputStream relationshipsInputStream = null;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (false == relsEntryName.equals(zipEntry.getName())) {
            continue;
        }
        relationshipsInputStream = zipInputStream;
        break;
    }
    if (null == relationshipsInputStream) {
        return null;
    }
    JAXBContext jaxbContext = JAXBContext
            .newInstance(be.fedict.eid.applet.service.signer.jaxb.opc.relationships.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    JAXBElement<CTRelationships> relationshipsElement = (JAXBElement<CTRelationships>) unmarshaller
            .unmarshal(relationshipsInputStream);
    return relationshipsElement.getValue();
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Deserializes examplars stored in archives in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getArchiveDirectory()/*ww  w  .  j a v a 2 s  . co  m*/
 */
public void deserializeArchivedVersions() throws RuntimeException {
    System.out.println("Deserializing archived instances in " + getArchiveDirectory() + ".");

    File archive = new File(getArchiveDirectory());

    if (!archive.exists() || !archive.isDirectory()) {
        return;
    }

    String[] listing = archive.list();

    for (String archiveName : listing) {
        if (!(archiveName.endsWith(".zip"))) {
            continue;
        }

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            ZipFile zipFile = new ZipFile(file);
            ZipEntry entry = zipFile.getEntry("class_fields.ser");
            InputStream inputStream = zipFile.getInputStream(entry);
            ObjectInputStream objectIn = new ObjectInputStream(inputStream);
            Map<String, List<String>> classFields = (Map<String, List<String>>) objectIn.readObject();
            zipFile.close();

            for (String className : classFields.keySet()) {

                //                    if (classFields.equals("HypotheticalGraph")) continue;

                List<String> fieldNames = classFields.get(className);
                Class<?> clazz = Class.forName(className);
                ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz);

                if (streamClass == null) {
                    System.out.println();
                }

                for (String fieldName : fieldNames) {
                    assert streamClass != null;
                    ObjectStreamField field = streamClass.getField(fieldName);

                    if (field == null) {
                        throw new RuntimeException("Field '" + fieldName + "' was dropped from class '"
                                + className + "' as a serializable field! Please " + "put it back!!!"
                                + "\nIt used to be in " + className + " in this archive: " + archiveName + ".");
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not read class_fields.ser in archive + " + archiveName + " .", e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }

        System.out.println("...Deserializing instances in " + archiveName + "...");
        ZipEntry zipEntry = null;

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            FileInputStream in = new FileInputStream(file);
            ZipInputStream zipinputstream = new ZipInputStream(in);

            while ((zipEntry = zipinputstream.getNextEntry()) != null) {
                if (!zipEntry.getName().endsWith(".ser")) {
                    continue;
                }

                ObjectInputStream objectIn = new ObjectInputStream(zipinputstream);
                objectIn.readObject();
                zipinputstream.closeEntry();
            }

            zipinputstream.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(
                    "Could not read object zipped file " + zipEntry.getName() + " in archive " + archiveName
                            + ". " + "Perhaps the class was renamed, moved to another package, or "
                            + "removed. In any case, please put it back where it was.",
                    e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }
    }

    System.out.println("Finished deserializing archived instances.");
}