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.yahoo.druid.hadoop.DruidRecordReader.java

private void getSegmentFiles(String pathStr, File dir, FileSystem fs) throws IOException {
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException(dir + " does not exist and creation failed");
    }//from ww w .j  a va  2s.  c  o  m

    final File tmpDownloadFile = File.createTempFile("dataSegment", ".zip");
    if (tmpDownloadFile.exists() && !tmpDownloadFile.delete()) {
        logger.warn("Couldn't clear out temporary file [%s]", tmpDownloadFile);
    }

    try {
        final Path inPath = new Path(pathStr);
        fs.copyToLocalFile(false, inPath, new Path(tmpDownloadFile.toURI()));

        long size = 0L;
        try (final ZipInputStream zipInputStream = new ZipInputStream(
                new BufferedInputStream(new FileInputStream(tmpDownloadFile)))) {
            final byte[] buffer = new byte[1 << 13];
            for (ZipEntry entry = zipInputStream.getNextEntry(); entry != null; entry = zipInputStream
                    .getNextEntry()) {
                final String fileName = entry.getName();
                try (final FileOutputStream fos = new FileOutputStream(
                        dir.getAbsolutePath() + File.separator + fileName)) {
                    for (int len = zipInputStream.read(buffer); len >= 0; len = zipInputStream.read(buffer)) {
                        size += len;
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }
    } finally {
        if (tmpDownloadFile.exists() && !tmpDownloadFile.delete()) {
            logger.warn("Temporary download file could not be deleted [%s]", tmpDownloadFile);
        }
    }
}

From source file:ch.rgw.compress.CompEx.java

public static byte[] expand(InputStream in) {
    ByteArrayOutputStream baos;//from   w w w . j av a  2 s . c o m
    byte[] siz = new byte[4];
    try {
        in.read(siz);
        long size = BinConverter.byteArrayToInt(siz, 0);
        long typ = size & ~0x1fffffff;
        size &= 0x1fffffff;
        byte[] ret = new byte[(int) size];

        switch ((int) typ) {
        case BZIP2:
            CBZip2InputStream bzi = new CBZip2InputStream(in);
            int off = 0;
            int l = 0;
            while ((l = bzi.read(ret, off, ret.length - off)) > 0) {
                off += l;
            }

            bzi.close();
            in.close();
            return ret;
        case GLZ:
            GLZ glz = new GLZ();
            baos = new ByteArrayOutputStream();
            glz.expand(in, baos);
            return baos.toByteArray();
        case HUFF:
            HuffmanInputStream hin = new HuffmanInputStream(in);
            off = 0;
            l = 0;
            while ((l = hin.read(ret, off, ret.length - off)) > 0) {
                off += l;
            }
            hin.close();
            return ret;
        case ZIP:
            ZipInputStream zi = new ZipInputStream(in);
            zi.getNextEntry();
            off = 0;
            l = 0;
            while ((l = zi.read(ret, off, ret.length - off)) > 0) {
                off += l;
            }

            zi.close();
            return ret;
        default:
            throw new Exception("Invalid compress format");
        }
    } catch (Exception ex) {
        ExHandler.handle(ex);
        return null;
    }

}

From source file:com.cloudbees.plugins.deployer.CloudbeesDeployWarTest.java

public static void assertOnArchive(InputStream inputStream) throws IOException {
    List<String> fileNames = new ArrayList<String>();
    ZipInputStream zipInputStream = null;
    try {//from   w w w .  j av  a  2  s . c o m
        zipInputStream = new ZipInputStream(inputStream);
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            fileNames.add(zipEntry.getName());
            zipEntry = zipInputStream.getNextEntry();
        }
    } finally {
        IOUtils.closeQuietly(zipInputStream);
    }
    assertTrue(fileNames.contains("META-INF/maven/org.olamy.puzzle.translate/translate-puzzle-webapp/pom.xml"));
    assertTrue(fileNames.contains("WEB-INF/lib/javax.inject-1.jar"));
}

From source file:io.apicurio.hub.api.codegen.OpenApi2ThorntailTest.java

/**
 * Test method for {@link io.apicurio.hub.api.codegen.OpenApi2Thorntail#generate()}.
 *//*  w  ww.  j  a  v  a2  s  .  co  m*/
@Test
public void testGenerateOnly_GatewayApiNoTypes() throws IOException {
    OpenApi2Thorntail generator = new OpenApi2Thorntail() {
        /**
         * @see io.apicurio.hub.api.codegen.OpenApi2Thorntail#processApiDoc()
         */
        @Override
        protected String processApiDoc() {
            try {
                return IOUtils.toString(OpenApi2ThorntailTest.class.getClassLoader()
                        .getResource("OpenApi2ThorntailTest/gateway-api-notypes.codegen.json"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };
    generator.setUpdateOnly(false);
    generator.setSettings(new ThorntailProjectSettings("io.openapi.simple", "simple-api", "io.openapi.simple"));
    generator.setOpenApiDocument(
            getClass().getClassLoader().getResource("OpenApi2ThorntailTest/gateway-api.json"));
    ByteArrayOutputStream outputStream = generator.generate();

    //        FileUtils.writeByteArrayToFile(new File("C:\\Users\\ewittman\\tmp\\output.zip"), outputStream.toByteArray());

    // Validate the result
    try (ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(outputStream.toByteArray()))) {
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            if (!zipEntry.isDirectory()) {
                String name = zipEntry.getName();
                //                    System.out.println(name);
                Assert.assertNotNull(name);

                URL expectedFile = getClass().getClassLoader().getResource(
                        getClass().getSimpleName() + "/_expected-gatewayApiNoTypes/simple-api/" + name);
                Assert.assertNotNull("Could not find expected file for entry: " + name, expectedFile);
                String expected = IOUtils.toString(expectedFile);

                String actual = IOUtils.toString(zipInputStream);
                //                    System.out.println("-----");
                //                    System.out.println(actual);
                //                    System.out.println("-----");
                Assert.assertEquals("Expected vs. actual failed for entry: " + name, normalizeString(expected),
                        normalizeString(actual));
            }
            zipEntry = zipInputStream.getNextEntry();
        }
    }

}

From source file:org.talend.license.LicenseRetriver.java

Collection<File> checkout(final String version, final File root, final String url) {
    try {/*from   www.j a v a  2  s.  c o  m*/
        return connector.doGet(url, new ResponseHandler<Collection<File>>() {

            public Collection<File> handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                Collection<File> files = new LinkedList<File>();
                InputStream stream = response.getEntity().getContent();
                ZipInputStream zip = new ZipInputStream(stream);
                String regex = Configer.getLicenseFile().replaceAll("%version", version);
                Pattern pattern = Pattern.compile(regex);
                while (true) {
                    ZipEntry entry = zip.getNextEntry();
                    if (null == entry) {
                        break;
                    }
                    try {
                        String name = entry.getName();
                        Matcher matcher = pattern.matcher(name);
                        if (matcher.find()) {
                            int count = matcher.groupCount();
                            String fname = null;
                            for (int i = 1; i <= count; i++) {
                                fname = matcher.group(i);
                                if (StringUtils.isEmpty(fname)) {
                                    continue;
                                }
                                break;
                            }

                            logger.info("found a available license {}", fname);
                            File target = new File(root, fname);
                            if (target.exists()) {
                                files.add(target);// TODO
                                continue;
                            }
                            FileOutputStream fos = new FileOutputStream(target);
                            IOUtils.copy(zip, fos);
                            IOUtils.closeQuietly(fos);
                            files.add(target);
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                }
                return files;
            }
        });
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.joliciel.talismane.machineLearning.linearsvm.LinearSVMOneVsRestModel.java

@Override
public void loadModelFromStream(InputStream inputStream) {
    // load model or use it directly
    try {/*  w  ww .  j  a v a2s. com*/
        models = new ArrayList<Model>();
        ZipInputStream zis = new ZipInputStream(inputStream);
        ZipEntry zipEntry = null;
        while ((zipEntry = zis.getNextEntry()) != null) {
            LOG.debug("Reading " + zipEntry.getName());
            Reader reader = new InputStreamReader(zis, "UTF-8");
            Model model = Model.load(reader);
            models.add(model);
        }
    } catch (UnsupportedEncodingException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:ca.uhn.fhir.jpa.term.TerminologyLoaderSvc.java

private void extractFiles(List<byte[]> theZipBytes, List<String> theExpectedFilenameFragments) {
    Set<String> foundFragments = new HashSet<String>();

    for (byte[] nextZipBytes : theZipBytes) {
        ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(new ByteArrayInputStream(nextZipBytes)));
        try {// w  w w  .j  a v a  2 s.  c  o m
            for (ZipEntry nextEntry; (nextEntry = zis.getNextEntry()) != null;) {
                for (String next : theExpectedFilenameFragments) {
                    if (nextEntry.getName().contains(next)) {
                        foundFragments.add(next);
                    }
                }
            }
        } catch (IOException e) {
            throw new InternalErrorException(e);
        } finally {
            IOUtils.closeQuietly(zis);
        }
    }

    for (String next : theExpectedFilenameFragments) {
        if (!foundFragments.contains(next)) {
            throw new InvalidRequestException(
                    "Invalid input zip file, expected zip to contain the following name fragments: "
                            + theExpectedFilenameFragments + " but found: " + foundFragments);
        }
    }

}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(final String signatureZipEntryName,
        final OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    final ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    final ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(this.getOfficeOpenXMLDocument()));
    ZipEntry zipEntry;//w ww  .j a v a  2s .  com
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        zipOutputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
        if ("[Content_Types].xml".equals(zipEntry.getName())) { //$NON-NLS-1$
            final Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            final Element typesElement = contentTypesDocument.getDocumentElement();

            // We need to add an Override element.
            final Element overrideElement = contentTypesDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/content-types", "Override"); //$NON-NLS-1$ //$NON-NLS-2$
            overrideElement.setAttribute("PartName", "/" + signatureZipEntryName); //$NON-NLS-1$ //$NON-NLS-2$
            overrideElement.setAttribute("ContentType", //$NON-NLS-1$
                    "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"); //$NON-NLS-1$
            typesElement.appendChild(overrideElement);

            final Element nsElement = contentTypesDocument.createElement("ns"); //$NON-NLS-1$
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", //$NON-NLS-1$
                    "http://schemas.openxmlformats.org/package/2006/content-types"); //$NON-NLS-1$
            final NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument,
                    "/tns:Types/tns:Default[@Extension='sigs']", nsElement); //$NON-NLS-1$
            if (0 == nodeList.getLength()) {
                // Add Default element for 'sigs' extension.
                final Element defaultElement = contentTypesDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/content-types", "Default"); //$NON-NLS-1$ //$NON-NLS-2$
                defaultElement.setAttribute("Extension", "sigs"); //$NON-NLS-1$ //$NON-NLS-2$
                defaultElement.setAttribute("ContentType", //$NON-NLS-1$
                        "application/vnd.openxmlformats-package.digital-signature-origin"); //$NON-NLS-1$
                typesElement.appendChild(defaultElement);
            }

            writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false);
        } else if ("_rels/.rels".equals(zipEntry.getName())) { //$NON-NLS-1$
            final Document relsDocument = loadDocumentNoClose(zipInputStream);

            final Element nsElement = relsDocument.createElement("ns"); //$NON-NLS-1$
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$
            final NodeList nodeList = XPathAPI.selectNodeList(relsDocument,
                    "/tns:Relationships/tns:Relationship[@Type='http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin']", //$NON-NLS-1$
                    nsElement);
            if (0 == nodeList.getLength()) {
                final Element relationshipElement = relsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
                        "Relationship"); //$NON-NLS-1$
                relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$
                relationshipElement.setAttribute("Type", //$NON-NLS-1$
                        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin"); //$NON-NLS-1$
                relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs"); //$NON-NLS-1$ //$NON-NLS-2$

                relsDocument.getDocumentElement().appendChild(relationshipElement);
            }

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if (zipEntry.getName().startsWith("_xmlsignatures/_rels/") //$NON-NLS-1$
                && zipEntry.getName().endsWith(".rels")) { //$NON-NLS-1$

            hasOriginSigsRels = true;
            final Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
                    "Relationship"); //$NON-NLS-1$
            relationshipElement.setAttribute("Id", "rel-" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$
            relationshipElement.setAttribute("Type", //$NON-NLS-1$
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

            relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

            writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
        } else {
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }

    if (!hasOriginSigsRels) {
        // Add signature relationships document.
        addOriginSigsRels(signatureZipEntryName, zipOutputStream);
        addOriginSigs(zipOutputStream);
    }

    // Return.
    zipInputStream.close();
    return zipOutputStream;
}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Unzip it/*from  ww w.  j  a  v  a 2 s.c o  m*/
 *
 * @param zipFile input zip file
 * @param outputFolder
 * @throws java.io.FileNotFoundException
 */
public static void unzip(String zipFile, String outputFolder) throws FileNotFoundException, IOException {
    byte[] buffer = new byte[1024];

    try (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);
            if (ze.isDirectory()) {
                newFile.mkdirs();
            } else {
                try (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();
    }
}

From source file:com.eviware.soapui.impl.wsdl.support.FileAttachment.java

public InputStream getInputStream() throws IOException {
    BufferedInputStream inputStream = null;

    if (isCached()) {
        ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(config.getData()));
        zipInputStream.getNextEntry();/*from w  w  w. j  ava2s .com*/
        inputStream = new BufferedInputStream(zipInputStream);
    } else {
        String url = urlProperty.expand();
        inputStream = new BufferedInputStream(
                url == null ? new ByteArrayInputStream(new byte[0]) : new FileInputStream(url));
    }

    AttachmentEncoding encoding = getEncoding();
    if (encoding == AttachmentEncoding.BASE64) {
        ByteArrayOutputStream data = Tools.readAll(inputStream, Tools.READ_ALL);
        return new ByteArrayInputStream(Base64.encodeBase64(data.toByteArray()));
    } else if (encoding == AttachmentEncoding.HEX) {
        ByteArrayOutputStream data = Tools.readAll(inputStream, Tools.READ_ALL);
        return new ByteArrayInputStream(new String(Hex.encodeHex(data.toByteArray())).getBytes());
    }

    return inputStream;
}