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:org.activiti.spring.SpringProcessEngineConfiguration.java

protected void autoDeployResources(ProcessEngine processEngine) {
    if (deploymentResources != null && deploymentResources.length > 0) {
        RepositoryService repositoryService = processEngine.getRepositoryService();

        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering()
                .name(deploymentName);//  w w  w .ja v a 2s  . c o  m

        for (Resource resource : deploymentResources) {
            String resourceName = null;

            if (resource instanceof ContextResource) {
                resourceName = ((ContextResource) resource).getPathWithinContext();

            } else if (resource instanceof ByteArrayResource) {
                resourceName = resource.getDescription();

            } else {
                try {
                    resourceName = resource.getFile().getAbsolutePath();
                } catch (IOException e) {
                    resourceName = resource.getFilename();
                }
            }

            try {
                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip")
                        || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }
            } catch (IOException e) {
                throw new ActivitiException(
                        "couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
            }
        }

        deploymentBuilder.deploy();
    }
}

From source file:Main.java

/** Return true if this file is a zip file. */
public static boolean isZip(File file) throws IOException {
    if (file.exists() == false)
        return false;

    InputStream in = null;/* w  ww  . j a v  a  2  s. c  om*/
    try {
        in = new FileInputStream(file);
        ZipInputStream zipIn = new ZipInputStream(in);
        ZipEntry e = zipIn.getNextEntry();
        if (e == null)
            return false;
        int ctr = 0;
        while (e != null && ctr < 4) {
            e = zipIn.getNextEntry();
            ctr++;
        }
        return true;
    } catch (Throwable t) {
        return false;
    } finally {
        try {
            in.close();
        } catch (Throwable t) {
        }
    }
}

From source file:com.jadarstudios.rankcapes.bukkit.RankCapesBukkit.java

/**
 * Validates a cape pack and returns true if it is valid.
 *
 * @param pack to validate//w  w  w  .j  a va  2 s.c  om
 */
private void validatePack(byte[] pack) throws IOException, InvalidCapePackException, ParseException {
    boolean foundMetadata = false;

    if (pack == null) {
        throw new InvalidCapePackException("The cape pack was null");
    }

    if (!CapePackValidator.isZipFile(pack)) {
        throw new InvalidCapePackException("The cape pack is not a ZIP file.");
    }

    ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(pack));
    ZipEntry entry;

    // reads the zip and finds the files. if the pack config file is not found, return false.
    while ((entry = zipIn.getNextEntry()) != null)
    // if the zip contains a file names "pack.mcmeta"
    {
        if (entry.getName().equals("pack.mcmeta")) {
            foundMetadata = true;
            try {
                this.parseMetadata(zipIn);
            } finally {
                zipIn.close();
            }

            break;
        }
    }

    if (!foundMetadata) {
        throw new InvalidCapePackException("The Cape Pack metadata was not found.");
    }
}

From source file:com.android.build.gradle.internal.transforms.ExtractJarsTransform.java

private static void extractJar(@NonNull File outJarFolder, @NonNull File jarFile, boolean extractCode)
        throws IOException {
    mkdirs(outJarFolder);//w  w w.  j  a v a  2s  . c  o  m
    HashSet<String> lowerCaseNames = new HashSet<>();
    boolean foundCaseInsensitiveIssue = false;

    try (Closer closer = Closer.create()) {
        FileInputStream fis = closer.register(new FileInputStream(jarFile));
        ZipInputStream zis = closer.register(new ZipInputStream(fis));
        // loop on the entries of the intermediary package and put them in the final package.
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            try {
                String name = entry.getName();

                // do not take directories
                if (entry.isDirectory()) {
                    continue;
                }

                foundCaseInsensitiveIssue = foundCaseInsensitiveIssue
                        || !lowerCaseNames.add(name.toLowerCase(Locale.US));

                Action action = getAction(name, extractCode);
                if (action == Action.COPY) {
                    File outputFile = new File(outJarFolder, name.replace('/', File.separatorChar));
                    mkdirs(outputFile.getParentFile());

                    try (Closer closer2 = Closer.create()) {
                        java.io.OutputStream outputStream = closer2
                                .register(new BufferedOutputStream(new FileOutputStream(outputFile)));
                        ByteStreams.copy(zis, outputStream);
                        outputStream.flush();
                    }
                }
            } finally {
                zis.closeEntry();
            }
        }

    }

    if (foundCaseInsensitiveIssue) {
        LOGGER.error(
                "Jar '{}' contains multiple entries which will map to "
                        + "the same file on case insensitive file systems.\n"
                        + "This can be caused by obfuscation with useMixedCaseClassNames.\n"
                        + "This build will be incorrect on case insensitive " + "file systems.",
                jarFile.getAbsolutePath());
    }
}

From source file:com.cloudera.recordservice.tests.ClusterConfiguration.java

/**
 * This method unzips a conf dir return through the CM api and returns the
 * path of the unzipped directory as a string
 *//*from  www  .ja  v a  2 s.com*/
private String unzipConf(String zipFileName) throws IOException {
    int num = rand_.nextInt(10000000);
    String outDir = "/tmp/" + "confDir" + "_" + num + "/";
    byte[] buffer = new byte[4096];
    FileInputStream fis;
    String filename = "";
    fis = new FileInputStream(zipFileName);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        filename = ze.getName();
        File unzippedFile = new File(outDir + filename);
        // Ensure that parent directories exist
        new File(unzippedFile.getParent()).mkdirs();
        FileOutputStream fos = new FileOutputStream(unzippedFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
    fis.close();
    return outDir + "recordservice-conf/";
}

From source file:com.adobe.communities.ugc.migration.importer.MessagesImportServlet.java

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

    final ResourceResolver resolver = request.getResourceResolver();

    UGCImportHelper.checkUserPrivileges(resolver, rrf);

    // first check to see if the caller provided an explicit selector for our MessagingOperationsService
    final RequestParameter serviceSelector = request.getRequestParameter("serviceSelector");
    // if no serviceSelector parameter was provided, we'll try going with whatever we get through the Reference
    if (null != serviceSelector && !serviceSelector.getString().equals("")) {
        // make sure the messagingServiceTracker was created by the activate method
        if (null == messagingServiceTracker) {
            throw new ServletException("Cannot use messagingServiceTracker");
        }// w ww. j av a2s . c  om
        // search for the MessagingOperationsService corresponding to the provided selector
        messagingService = messagingServiceTracker.getService(serviceSelector.getString());
        if (null == messagingService) {
            throw new ServletException(
                    "MessagingOperationsService for selector " + serviceSelector.getString() + "was not found");
        }
    }
    // finally get the uploaded file
    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()) {

        final Map<String, Object> messageModifiers = new HashMap<String, Object>();
        if (fileRequestParameters[0].getFileName().endsWith(".json")) {
            // if upload is a single json file...
            final InputStream inputStream = fileRequestParameters[0].getInputStream();
            final JsonParser jsonParser = new JsonFactory().createParser(inputStream);
            jsonParser.nextToken(); // get the first token
            importMessages(request, jsonParser, messageModifiers);
        } else if (fileRequestParameters[0].getFileName().endsWith(".zip")) {
            ZipInputStream zipInputStream;
            try {
                zipInputStream = new ZipInputStream(fileRequestParameters[0].getInputStream());
            } catch (IOException e) {
                throw new ServletException("Could not open zip archive");
            }
            ZipEntry zipEntry = zipInputStream.getNextEntry();
            while (zipEntry != null) {
                final JsonParser jsonParser = new JsonFactory().createParser(zipInputStream);
                jsonParser.nextToken(); // get the first token
                importMessages(request, jsonParser, messageModifiers);
                zipInputStream.closeEntry();
                zipEntry = zipInputStream.getNextEntry();
            }
            zipInputStream.close();
        } else {
            throw new ServletException("Unrecognized file input type");
        }
        if (!messageModifiers.isEmpty()) {
            try {
                Thread.sleep(3000); //wait 3 seconds to allow the messages to be indexed by solr for search
            } catch (final InterruptedException e) {
                // do nothing.
            }
            updateMessageDetails(request, messageModifiers);
        }
    } else {
        throw new ServletException("No file provided for UGC data");
    }
}

From source file:hudson.jbpm.PluginImpl.java

/**
 * Method supporting upload from the designer at /plugin/jbpm/upload
 *///w  w w  .ja v a  2s .c  o  m
public void doUpload(StaplerRequest req, StaplerResponse rsp)
        throws FileUploadException, IOException, ServletException {
    try {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        // Parse the request
        FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);

        if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
            throw new IOException("Not a process archive");
        }

        log.fine("Deploying process archive " + fileItem.getName());
        ZipInputStream zipInputStream = new ZipInputStream(fileItem.getInputStream());
        JbpmContext jbpmContext = getCurrentJbpmContext();
        log.fine("Preparing to parse process archive");
        ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
        log.fine("Created a processdefinition : " + processDefinition.getName());
        jbpmContext.deployProcessDefinition(processDefinition);
        zipInputStream.close();
        rsp.forwardToPreviousPage(req);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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  2s .c  o  m*/
    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:com.wavemaker.StudioInstallService.java

public static File unzipFile(File zipfile) {
    int BUFFER = 2048;

    String zipname = zipfile.getName();
    int extindex = zipname.lastIndexOf(".");

    try {/*from  w  w  w.  j av  a 2s .c o  m*/
        File zipFolder = new File(zipfile.getParentFile(), zipname.substring(0, extindex));
        if (zipFolder.exists())
            org.apache.commons.io.FileUtils.deleteDirectory(zipFolder);
        zipFolder.mkdir();

        File currentDir = zipFolder;
        //File currentDir = zipfile.getParentFile();

        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream(zipfile.toString());
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                File f = new File(currentDir, entry.getName());
                if (f.exists())
                    f.delete(); // relevant if this is the top level folder
                f.mkdir();
            } else {
                int count;
                byte data[] = new byte[BUFFER];
                //needed for non-dir file ace/ace.js created by 7zip
                File destFile = new File(currentDir, entry.getName());
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(currentDir.toString() + "/" + entry.getName());
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
        zis.close();

        return currentDir;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (File) null;

}

From source file:com.squareup.wire.schema.internal.parser.RpcMethodScanner.java

private List<RpcMethodDefinition> searchJar(String jarpath, String serviceName) throws IOException {

    List<RpcMethodDefinition> defs = new ArrayList<>();

    File jarFile = new File(jarpath);
    if (!jarFile.exists() || jarFile.isDirectory()) {
        return defs;
    }/*from w  w w .  ja  va  2  s  . c  o m*/

    ZipInputStream zip = new ZipInputStream(new FileInputStream(jarFile));
    ZipEntry ze;

    while ((ze = zip.getNextEntry()) != null) {
        String entryName = ze.getName();
        if (entryName.endsWith(".proto")) {
            ZipFile zipFile = new ZipFile(jarFile);
            try (InputStream in = zipFile.getInputStream(ze)) {
                defs.addAll(inspectProtoFile(in, serviceName));
                if (!defs.isEmpty()) {
                    zipFile.close();
                    break;
                }
            }
            zipFile.close();
        }
    }

    zip.close();

    return defs;
}