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:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param zip// w w  w  .j a v  a2 s.  c om
 * @param name
 * @return
 * @throws java.io.IOException
 */
public static InputStream getFile(InputStream zip, String name) throws IOException {
    ZipInputStream in = new ZipInputStream(zip);
    ZipEntry entry;
    while ((entry = in.getNextEntry()) != null) {
        String entityName = entry.getName();
        if (!entry.isDirectory() && entityName.contains(name)) {
            return in;
        }
    }
    in.close();
    return null;
}

From source file:gov.nih.nci.caarray.web.action.project.ProjectSamplesActionTest.java

@Test
public void testDownload() throws Exception {
    assertEquals("noSampleData", this.action.download());

    final CaArrayFile rawFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_IDF);
    final CaArrayFile derivedFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_SDRF);

    final Project p = new Project();
    p.getExperiment().setPublicIdentifier("test");
    final Sample s = new Sample();
    final Extract e = new Extract();
    s.getExtracts().add(e);/*from   www .  j a va2  s.co  m*/
    final LabeledExtract le = new LabeledExtract();
    e.getLabeledExtracts().add(le);
    final Hybridization h = new Hybridization();
    le.getHybridizations().add(h);
    final RawArrayData raw = new RawArrayData();
    h.addArrayData(raw);
    final DerivedArrayData derived = new DerivedArrayData();
    h.getDerivedDataCollection().add(derived);
    raw.setDataFile(rawFile);
    derived.setDataFile(derivedFile);

    this.action.setCurrentSample(s);
    this.action.setProject(p);
    final List<CaArrayFile> files = new ArrayList<CaArrayFile>(s.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(2, files.size());
    assertEquals("missing_term_source.idf", files.get(0).getName());
    assertEquals("missing_term_source.sdrf", files.get(1).getName());

    this.action.download();
    assertEquals("application/zip", this.mockResponse.getContentType());
    assertEquals("filename=\"caArray_test_files.zip\"", this.mockResponse.getHeader("Content-disposition"));

    final ZipInputStream zis = new ZipInputStream(
            new ByteArrayInputStream(this.mockResponse.getContentAsByteArray()));
    ZipEntry ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.idf", ze.getName());
    ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.sdrf", ze.getName());
    assertNull(zis.getNextEntry());
    IOUtils.closeQuietly(zis);
}

From source file:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public void deploy(String name) throws XMLConfigException, FileNotFoundException {

    Path configurationArchivePath = getConfigurationPath(name);

    Path current = Paths.get(XMLConfig.getBaseConfigPath());
    Path staging = current.getParent().resolve("deploy");
    Path destination = current.getParent().resolve(name);

    if (LOCK.tryLock()) {

        if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) {

            try {

                ZipInputStream configurationArchive = new ZipInputStream(
                        Files.newInputStream(configurationArchivePath, StandardOpenOption.READ));

                LOG.debug("Starting deploy of configuration " + name);
                ZipEntry zipEntry = null;

                for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) {

                    if (!Files.isDirectory(cfgFile)) {

                        Path target = staging.resolve(current.relativize(cfgFile));
                        Files.createDirectories(target);

                        Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING);
                    }/*from  w  ww .j a va 2 s  . c  o  m*/

                }

                LOG.debug("Staging new config " + name);

                while ((zipEntry = configurationArchive.getNextEntry()) != null) {

                    Path entryPath = staging.resolve(zipEntry.getName());

                    LOG.debug("Adding resource: " + entryPath);
                    if (zipEntry.isDirectory()) {
                        entryPath.toFile().mkdirs();
                    } else {

                        Path parent = entryPath.getParent();
                        if (!Files.exists(parent)) {
                            Files.createDirectories(parent);
                        }

                        Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }

                }

                //**** Deleting old config dir
                LOG.debug("Removing old config: " + current);
                Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(java.nio.file.Path::toFile).forEach(File::delete);

                LOG.debug("Deploy new config " + name + " in path " + destination);
                Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE);

                setXMLConfigBasePath(destination.toString());
                LOG.debug("Deploy complete");
                deployListeners.forEach(l -> l.onDeploy(destination));

            } catch (Exception e) {

                if (Objects.nonNull(staging) && Files.exists(staging)) {
                    LOG.error("Deploy failed, rollback to previous configuration", e);
                    try {
                        Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                                .map(java.nio.file.Path::toFile).forEach(File::delete);

                        setXMLConfigBasePath(current.toString());
                    } catch (IOException | InvalidSyntaxException rollbackException) {
                        LOG.error("Failed to delete old configuration", e);
                    }
                } else {
                    LOG.error("Deploy failed", e);
                }

                throw new XMLConfigException("Deploy failed", e);
            } finally {
                LOCK.unlock();
            }
        } else {
            throw new FileNotFoundException(configurationArchivePath.toString());
        }
    } else {
        throw new IllegalStateException("A deploy is already in progress");
    }

}

From source file:org.calrissian.restdoclet.writer.swagger.SwaggerWriter.java

private static void copySwagger() throws IOException {
    ZipInputStream swaggerZip = null;
    FileOutputStream out = null;//from   w w w.  jav a 2s.c o m
    try {
        swaggerZip = new ZipInputStream(
                Thread.currentThread().getContextClassLoader().getResourceAsStream(SWAGGER_UI_ARTIFACT));
        ZipEntry entry;
        while ((entry = swaggerZip.getNextEntry()) != null) {
            final File swaggerFile = new File(".", entry.getName());
            if (entry.isDirectory()) {
                if (!swaggerFile.isDirectory() && !swaggerFile.mkdirs()) {
                    throw new RuntimeException("Unable to create directory: " + swaggerFile);
                }
            } else {
                copy(swaggerZip, new FileOutputStream(swaggerFile));
            }
        }
    } finally {
        close(swaggerZip, out);
    }
}

From source file:com.amazonaws.eclipse.elasticbeanstalk.git.AWSGitPushCommand.java

private void extractZipFile(File zipFile, File destination) throws IOException {
    int BUFFER = 2048;

    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    BufferedOutputStream dest = null;
    try {/*w w  w. j  a va2 s .co  m*/
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk

            if (entry.isDirectory())
                continue;

            File entryFile = new File(destination, entry.getName());
            if (!entryFile.getParentFile().exists()) {
                entryFile.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(entryFile);
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
        }
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(dest);
    }
}

From source file:org.universAAL.itests.IntegrationTest.java

/**
 * Helper method for extracting zipped archive provided as input stream into
 * given directory.//from w ww . j  a  va  2 s .  c  om
 *
 * @param is
 * @param destDirStr
 */
private void unzipInpuStream(final InputStream is, final String destDirStr) {
    try {
        File destDir = new File(destDirStr);
        final int BUFFER = 1024;
        BufferedOutputStream dest = null;
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            if (entry.getName().startsWith("META-INF")) {
                // META-INF (which includes MANIFEST) should not be
                // unpacked. It should be just ignored
                continue;
            }
            if (entry.isDirectory()) {
                File newDir = new File(destDir, entry.getName());
                newDir.mkdirs();
            } else {
                int count;
                byte[] data = new byte[BUFFER];
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(new File(destDir, 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();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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();/*from  w w w  .  j  av  a  2  s . c  o 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:eu.delving.services.TestDataSetCycle.java

@Test
public void testSipZipCycle() throws Exception {
    ClientContext clientContext = new ClientContext();
    // import//from ww w  .  j a v  a 2 s  .  c  o  m
    Ear importEar = new Ear("Import First Time");
    factory.getDataSetStore().importFile(MockInput.sampleFile(), importEar);
    Assert.assertTrue("import first time", importEar.getResultBoolean());
    Facts facts = Facts.read(new FileInputStream(FACTS_FILE));
    factory.getDataSetStore().setFacts(facts);
    // upload
    DataSetClient client = new DataSetClient(clientContext);
    Ear uploadFactsEar = new Ear("Upload facts first time");
    client.uploadFile(FileType.FACTS, MockFileStoreFactory.SPEC, FACTS_FILE, uploadFactsEar);
    Assert.assertTrue("upload facts first time", uploadFactsEar.getResultBoolean());
    Ear uploadSourceEar = new Ear("Upload source First Time");
    client.uploadFile(FileType.SOURCE, MockFileStoreFactory.SPEC, factory.getDataSetStore().getSourceFile(),
            uploadSourceEar);
    Assert.assertTrue("upload source first time", uploadSourceEar.getResultBoolean());
    client.setListFetchingEnabled(true);
    /* run it once */ client.setListFetchingEnabled(false);
    // delete local store
    factory.getDataSetStore().delete();
    // download a new version
    factory.getFileStore().createDataSetStore(MockFileStoreFactory.SPEC);
    Thread.sleep(1000);
    Assert.assertNotNull("data set info missing", clientContext.dataSetInfo);
    Assert.assertEquals(14141L, (long) clientContext.dataSetInfo.recordCount);
    clientContext.dataSetInfo = null;
    HttpMethod method = new GetMethod(String.format("%s/fetch/%s-sip.zip?accessKey=%s",
            clientContext.getServerUrl(), MockFileStoreFactory.SPEC, clientContext.getAccessKey()));
    httpClient.executeMethod(method);
    factory.getDataSetStore().acceptSipZip(new ZipInputStream(method.getResponseBodyAsStream()),
            new Ear("Unzip"));
    Assert.assertTrue("Hash is wrong!", Hasher.checkHash(factory.getDataSetStore().getSourceFile()));
    // upload this new version
    uploadFactsEar = new Ear("Upload facts Again");
    client.uploadFile(FileType.FACTS, MockFileStoreFactory.SPEC, factory.getDataSetStore().getFactsFile(),
            uploadFactsEar);
    Assert.assertTrue("upload facts again", uploadFactsEar.getResultBoolean());
    uploadSourceEar = new Ear("Upload source Again");
    client.uploadFile(FileType.SOURCE, MockFileStoreFactory.SPEC, factory.getDataSetStore().getSourceFile(),
            uploadSourceEar);
    Assert.assertFalse("upload source again should have been deemed unnecessary",
            uploadSourceEar.getResultBoolean());
}

From source file:edu.cmu.cs.lti.util.general.BasicConvenience.java

/**
 * Returns a reader for the specified file using the specified encoding. Any characters in the
 * input that are malformed or invalid for that encoding are replaced with the specified
 * substitution string.// w w  w .j  av  a2  s .co  m
 * 
 * @param f
 * @param encoding
 * @param substitution
 * @return
 * @throws FileNotFoundException
 */
public static BufferedReader getEncodingSafeBufferedReader(File f, String encoding, String substitution)
        throws FileNotFoundException {
    BufferedReader cin;
    Charset cs = Charset.forName(encoding);
    CharsetDecoder decoder = cs.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPLACE);
    decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    decoder.replaceWith(substitution);

    InputStream is = new FileInputStream(f);
    if (f.toString().endsWith(".zip"))
        is = new ZipInputStream(is);

    cin = new BufferedReader(new InputStreamReader(is, decoder));
    return cin;
}

From source file:eu.europa.ec.markt.dss.validation.SignedDocumentValidator.java

private static SignedDocumentValidator getInstanceForAsics(Document document) throws IOException {

    ZipInputStream asics = new ZipInputStream(document.openStream());

    try {/*from www .  j ava2 s.  com*/

        ByteArrayOutputStream datafile = null;
        ByteArrayOutputStream signatures = null;
        ZipEntry entry;

        boolean cadesSigned = false;
        boolean xadesSigned = false;

        while ((entry = asics.getNextEntry()) != null) {
            if (entry.getName().equalsIgnoreCase(SIGNATURES_P7S)) {
                if (xadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                cadesSigned = true;
            } else if (entry.getName().equalsIgnoreCase(SIGNATURES_XML)) {
                if (cadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                xadesSigned = true;
            } else if (entry.getName().equalsIgnoreCase(MIMETYPE)) {
                ByteArrayOutputStream mimetype = new ByteArrayOutputStream();
                IOUtils.copy(asics, mimetype);
                mimetype.close();
                if (!Arrays.equals(mimetype.toByteArray(), MIMETYPE_ASIC_S.getBytes())) {
                    throw new NotETSICompliantException(MSG.UNRECOGNIZED_TAG);
                }
            } else if (entry.getName().indexOf("/") == -1) {
                if (datafile == null) {
                    datafile = new ByteArrayOutputStream();
                    IOUtils.copy(asics, datafile);
                    datafile.close();
                } else {
                    throw new ProfileException("ASiC-S profile support only one data file");
                }
            }
        }

        if (xadesSigned) {
            ASiCXMLDocumentValidator xmlValidator = new ASiCXMLDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()), datafile.toByteArray());
            return xmlValidator;
        } else if (cadesSigned) {
            CMSDocumentValidator pdfValidator = new CMSDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()));
            pdfValidator.setExternalContent(new InMemoryDocument(datafile.toByteArray()));
            return pdfValidator;
        } else {
            throw new RuntimeException("Is not xades nor cades signed");
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            asics.close();
        } catch (IOException e) {
        }
    }

}