Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:com.github.nethad.clustermeister.integration.JPPFTestNode.java

private void unzipNode(InputStream fileToUnzip, File targetDir) {
    //        Enumeration entries;
    ZipInputStream zipFile;//from  w  w w  .  ja  va  2  s .  com
    try {
        zipFile = new ZipInputStream(fileToUnzip);
        ZipEntry entry;
        while ((entry = zipFile.getNextEntry()) != null) {
            //                ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                // Assume directories are stored parents first then children.
                System.err.println("Extracting directory: " + entry.getName());
                // This is not robust, just for demonstration purposes.
                (new File(targetDir, entry.getName())).mkdir();
                continue;
            }
            System.err.println("Extracting file: " + entry.getName());
            File targetFile = new File(targetDir, entry.getName());
            copyInputStream_notClosing(zipFile, new BufferedOutputStream(new FileOutputStream(targetFile)));
            //                zipFile.closeEntry();
        }
        zipFile.close();
    } catch (IOException ioe) {
        System.err.println("Unhandled exception:");
        ioe.printStackTrace();
    }
}

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  a2  s .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:com.jkoolcloud.tnt4j.streams.inputs.ZipLineStream.java

@Override
protected void initialize() throws Exception {
    super.initialize();

    if (StringUtils.isEmpty(zipFileName)) {
        throw new IllegalStateException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "TNTInputStream.property.undefined", StreamProperties.PROP_FILENAME));
    }/*from   w  w w. j  a v  a  2 s  . c o m*/
    logger().log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
            "ZipLineStream.initializing.stream"), zipFileName);

    InputStream fis = loadFile(zipPath);

    try {
        if (ArchiveTypes.JAR.name().equalsIgnoreCase(archType)) {
            zipStream = new JarInputStream(fis);
        } else if (ArchiveTypes.GZIP.name().equalsIgnoreCase(archType)) {
            zipStream = new GZIPInputStream(fis);
        } else {
            zipStream = new ZipInputStream(fis);
        }
    } catch (IOException exc) {
        Utils.close(fis);

        throw exc;
    }

    if (zipStream instanceof GZIPInputStream) {
        lineReader = new LineNumberReader(new BufferedReader(new InputStreamReader(zipStream)));
    } else {
        hasNextEntry();
    }
}

From source file:com.yahoo.parsec.gradle.utils.FileUtils.java

/**
 * List dir file paths./*  ww  w .  ja  v  a  2  s .com*/
 *
 * @param directory directory
 * @return List of file paths
 * @throws IOException IOException
 */
public List<Path> listDirFilePaths(String directory) throws IOException {
    CodeSource src = getClass().getProtectionDomain().getCodeSource();
    List<Path> paths = new ArrayList<>();

    try {
        if (src != null) {
            URL jar = src.getLocation();
            ZipInputStream zip = new ZipInputStream(jar.openStream());
            ZipEntry zipEntry;

            while ((zipEntry = zip.getNextEntry()) != null) {
                String entryName = zipEntry.getName();
                if (entryName.startsWith(directory + "/")) {
                    paths.add(Paths.get("/" + entryName));
                }
            }
        }
    } catch (IOException e) {
        throw e;
    }

    return paths;
}

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

@Override
protected Document getEnvelopingDocument() throws ParserConfigurationException, IOException, SAXException {
    FileInputStream fileInputStream = new FileInputStream(this.tmpFile);
    ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
    ZipEntry zipEntry;/*from  w  w w  . j a  va 2s .co m*/
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream);
            return documentSignaturesDocument;
        }
    }
    Document document = ODFUtil.getNewDocument();
    Element rootElement = document.createElementNS(ODFUtil.SIGNATURE_NS, ODFUtil.SIGNATURE_ELEMENT);
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ODFUtil.SIGNATURE_NS);
    document.appendChild(rootElement);
    return document;
}

From source file:m3.classe.M3ClassLoader.java

private DataInputStream getStreamFromJar2(String name, File path) throws MAKException {
    Exception exception;/*from   www . j  a v a 2 s.c  om*/
    try {
        DataInputStream dis = null;
        InputStream is = null;
        is = new FileInputStream(path);
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry = findZipEntry(name, zis);
        if (entry != null)
            ;
        return new DataInputStream(zis);
    } catch (FileNotFoundException e) {
        exception = e;
    } catch (MAKException e) {
        exception = e;
    }
    throw new MAKException("Failed to get " + name + " from jar " + path, exception);
}

From source file:com.github.jknack.amd4j.ClosureMinifier.java

/**
 * Build the default list of google closure external variable files.
 * Taken from: com.google.javascript.jscomp.CommandLineRunner
 *
 * @return a mutable list of source files.
 * @throws IOException On error when working with externs.zip
 *//*from w  ww.j a  v a 2  s .c  o m*/
protected List<SourceFile> getDefaultExterns() throws IOException {
    ZipInputStream zip = null;
    try {
        InputStream input = CommandLineRunner.class.getResourceAsStream("/externs.zip");
        notNull(input, "The externs.zip file was not found within the closure classpath");

        zip = new ZipInputStream(input);
        Map<String, SourceFile> externsMap = Maps.newHashMap();
        ZipEntry entry = zip.getNextEntry();
        while (entry != null) {
            BufferedInputStream entryStream = new BufferedInputStream(ByteStreams.limit(zip, entry.getSize()));
            externsMap.put(entry.getName(), SourceFile.fromInputStream(
                    // Give the files an odd prefix, so that they do not conflict
                    // with the user's files.
                    "externs.zip//" + entry.getName(), entryStream));
            entry = zip.getNextEntry();
        }

        Preconditions.checkState(externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
                "Externs zip must match our hard-coded list of externs.");

        // Order matters, so the resources must be added to the result list
        // in the expected order.
        List<SourceFile> externs = Lists.newArrayList();
        for (String key : DEFAULT_EXTERNS_NAMES) {
            externs.add(externsMap.get(key));
        }

        return externs;
    } finally {
        IOUtils.closeQuietly(zip);
    }
}

From source file:be.fedict.eid.applet.service.signer.odf.ODFUtil.java

/**
 * Check if an ODF package is self-contained, i.e. content files don't have
 * OLE objects linked to external files//from w w w .ja v a2s  .c  o  m
 * 
 * @param odfUrl
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static boolean isSelfContained(URL odfUrl)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    InputStream odfInputStream = odfUrl.openStream();
    List zipEntries = getZipEntriesAsList(odfInputStream);

    odfInputStream = odfUrl.openStream();
    ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
    ZipEntry zipEntry;

    XPathFactory factory = XPathFactory.newInstance();
    /* Maybe a bit overkill, but implementations can use other prefixes */
    ODFNamespaceContext namespaceContext = new ODFNamespaceContext();

    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expression = xpath.compile("//draw:object/@xlink:href|" + "//draw:object-ole/@xlink:href|"
            + "//draw:image/@xlink:href|" + "//draw:floating-frame/@xlink:href");

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (isContentFile(zipEntry)) {
            /* TODO: pure SAX is probably more memory-efficient */
            Document content = ODFUtil.loadDocument(odfZipInputStream);
            NodeList nodes = (NodeList) expression.evaluate(content, XPathConstants.NODESET);
            return checkNodes(nodes, zipEntries);
        }
    }
    return true;
}

From source file:org.opendatakit.api.forms.FormService.java

@POST
@ApiOperation(value = "Upload a zipped form definition as multipart/form-data.", response = FormUploadResult.class)
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
@Path("{appId}/{odkClientVersion}")
public Response doPost(@Context HttpServletRequest req, @Context HttpServletResponse resp,
        @PathParam("odkClientVersion") String odkClientVersion, @PathParam("appId") String appId,
        @Context UriInfo info) throws IOException {
    logger.debug("Uploading...");
    ServiceUtils.examineRequest(req.getServletContext(), req);

    req.getContentLength();//from w  w  w.  j ava  2s.  co  m
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new WebApplicationException(ErrorConsts.NO_MULTI_PART_CONTENT,
                HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        TablesUserPermissions userPermissions = ContextUtils.getTablesUserPermissions(callingContext);
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
        Map<String, byte[]> files = null;
        String tableId = null;
        List<String> regionalOffices = new ArrayList<>();

        // unzipping files

        for (FileItem item : items) {

            // Retrieve all Regional Office IDs to which a form definition
            // is going to be assigned to
            if (item.getFieldName().equals(WebConsts.OFFICE_ID)) {
                regionalOffices.add(item.getString());
            }

            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());

            if (fieldName.equals(WebConsts.ZIP_FILE)) {
                if (fileName == null || !(fileName.endsWith(".zip"))) {
                    throw new WebApplicationException(ErrorConsts.NO_ZIP_FILE,
                            HttpServletResponse.SC_BAD_REQUEST);
                }

                InputStream fileStream = item.getInputStream();
                ZipInputStream zipStream = new ZipInputStream(fileStream);
                files = processZipInputStream(zipStream);
            }
        }

        tableId = getTableIdFromFiles(files);

        FormUploadResult formUploadResult = uploadFiles(odkClientVersion, appId, tableId, userPermissions,
                files, regionalOffices);

        FileManifestManager manifestManager = new FileManifestManager(appId, odkClientVersion, callingContext);
        OdkTablesFileManifest manifest = manifestManager.getManifestForTable(tableId);
        FileManifestService.fixDownloadUrls(info, appId, odkClientVersion, manifest);

        formUploadResult.setManifest(manifest);
        String eTag = Integer.toHexString(manifest.hashCode()); // Is this
                                                                // right?

        return Response.status(Status.CREATED).entity(formUploadResult).header(HttpHeaders.ETAG, eTag)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();

    } catch (FileUploadException | ODKDatastoreException | ODKTaskLockException | PermissionDeniedException
            | TableAlreadyExistsException e) {
        logger.error("Error uploading zip", e);
        throw new WebApplicationException(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString(),
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    }
}

From source file:org.openmrs.contrib.metadatarepository.service.impl.PackageManagerImpl.java

public MetadataPackage deserializePackage(byte[] file) {
    Map<String, String> files = new LinkedHashMap<String, String>();

    InputStream input = new ByteArrayInputStream(file);

    ZipInputStream zip = new ZipInputStream(input);
    try {//from  w  w  w.ja va2s. co  m
        for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
            String file1 = IOUtils.toString(zip, ENCODING);
            files.put(entry.getName(), file1);
        }
    } catch (IOException e) {
        throw new APIException("error", e);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {

                log.error(e);
            }
        }
    }
    String header = files.get(HEADER_FILE);

    XStream xstream = new XStream(new DomDriver());

    MetadataPackage deserializedPackage = new MetadataPackage();
    xstream.registerConverter(new DateTimeConverter());
    xstream.alias("package", MetadataPackage.class);
    xstream.omitField(MetadataPackage.class, "file");
    xstream.omitField(MetadataPackage.class, "user");
    xstream.omitField(MetadataPackage.class, "downloadCount");
    xstream.omitField(MetadataPackage.class, "serializedPackage");
    xstream.omitField(MetadataPackage.class, "modules");
    xstream.omitField(MetadataPackage.class, "items");
    xstream.omitField(MetadataPackage.class, "relatedItems");
    deserializedPackage = (MetadataPackage) xstream.fromXML(header);

    return deserializedPackage;
}