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:be.fedict.eid.dss.document.zip.ZIPResourceResolver.java

private InputStream findZIPEntry(Attr dsReferenceUri) throws IOException {
    String entryName = dsReferenceUri.getValue();
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(this.document));
    ZipEntry zipEntry;/*from  ww w. j  a  v  a 2s .  c  om*/
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (entryName.equals(zipEntry.getName())) {
            return zipInputStream;
        }
    }
    return null;
}

From source file:it.geosolutions.tools.compress.file.Extractor.java

/**
 * Unzips the files from a zipfile into a directory. All of the files will be put in a single
 * direcotry. If the zipfile contains a hierarchycal structure, it will be ignored.
 * /*from w w w. j a v  a  2 s .c  om*/
 * @param zipFile
 *            The zipfile to be examined
 * @param destDir
 *            The direcotry where the extracted files will be stored.
 * @return The list of the extracted files, or null if an error occurred.
 * @throws IllegalArgumentException
 *             if the destination dir is not writeable.
 * @deprecated use Extractor.unZip instead which support complex zip structure
 */
public static List<File> unzipFlat(final File zipFile, final File destDir) {
    // if (!destDir.isDirectory())
    // throw new IllegalArgumentException("Not a directory '" + destDir.getAbsolutePath()
    // + "'");

    if (!destDir.canWrite())
        throw new IllegalArgumentException("Unwritable directory '" + destDir.getAbsolutePath() + "'");

    try {
        List<File> ret = new ArrayList<File>();
        ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile));

        for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream
                .getNextEntry()) {
            String entryName = zipentry.getName();
            if (zipentry.isDirectory())
                continue;

            File outFile = new File(destDir, entryName);
            ret.add(outFile);
            FileOutputStream fileoutputstream = new FileOutputStream(outFile);

            org.apache.commons.io.IOUtils.copy(zipinputstream, fileoutputstream);
            fileoutputstream.close();
            zipinputstream.closeEntry();
        }

        zipinputstream.close();
        return ret;
    } catch (Exception e) {
        LOGGER.warn("Error unzipping file '" + zipFile.getAbsolutePath() + "'", e);
        return null;
    }
}

From source file:com.sastix.cms.server.services.content.impl.ZipFileHandlerServiceImpl.java

@Override
public DataMaps unzip(byte[] bytes) throws IOException {
    Map<String, String> foldersMap = new HashMap<>();

    Map<String, byte[]> extractedBytesMap = new HashMap<>();
    InputStream byteInputStream = new ByteArrayInputStream(bytes);
    //validate that it is a zip file
    if (isZipFile(bytes)) {
        try {//from w ww  .  j  ava  2 s  . c o m
            //get the zip file content
            ZipInputStream zis = new ZipInputStream(byteInputStream);
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                if (!ze.isDirectory()) {//if entry is a directory, we should not add it as a file
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        ByteBuffer bufIn = ByteBuffer.allocate(1024);
                        int bytesRead;
                        while ((bytesRead = zis.read(bufIn.array())) > 0) {
                            baos.write(bufIn.array(), 0, bytesRead);
                            bufIn.rewind();
                        }
                        bufIn.clear();
                        extractedBytesMap.put(fileName, baos.toByteArray());
                    } finally {
                        baos.close();
                    }
                } else {
                    foldersMap.put(fileName, fileName);
                }
                ze = zis.getNextEntry();
            }
            zis.closeEntry();
            zis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    DataMaps dataMaps = new DataMaps();
    dataMaps.setBytesMap(extractedBytesMap);
    dataMaps.setFoldersMap(foldersMap);
    return dataMaps;
}

From source file:com.nkapps.billing.services.BankStatementServiceImpl.java

@Override
public File extractedFile(File file) throws Exception {
    File extractedFile = null;//from  w  w w  . java 2s .c  o  m

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        String extFileName = ze.getName();
        extractedFile = new File(getUploadDir() + File.separator + extFileName);
        if (!extractedFile.exists()) {
            extractedFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(extractedFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();

    return extractedFile;
}

From source file:name.martingeisse.webide.plugin.PluginBundleWicketResource.java

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {

    // fetch the JAR file
    final SQLQuery query = EntityConnectionManager.getConnection().createQuery();
    query.from(QPluginBundles.pluginBundles);
    query.where(QPluginBundles.pluginBundles.id.eq(pluginBundleId));
    final Object[] row = (Object[]) (Object) query.singleResult(QPluginBundles.pluginBundles.jarfile);
    final byte[] jarData = (byte[]) row[0];
    String matchingEntryName;/*w  w w  .j a  v a2  s.co  m*/
    final byte[] matchingEntryData;

    // if requested, load a single file from the JAR
    if (localPath != null) {
        final String localPathText = localPath.withLeadingSeparator(false).withTrailingSeparator(false)
                .toString();
        try {
            final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(jarData));
            while (true) {
                final ZipEntry entry = zipInputStream.getNextEntry();
                if (entry == null) {
                    zipInputStream.close();
                    final ResourceResponse response = new ResourceResponse();
                    response.setError(404, "Plugin bundle (id " + pluginBundleId + ") does not contain file: "
                            + localPathText);
                    response.setStatusCode(404);
                    return response;
                }
                if (localPathText.equals(entry.getName())) {
                    matchingEntryName = entry.getName();
                    matchingEntryData = IOUtils.toByteArray(zipInputStream);
                    zipInputStream.close();
                    break;
                }
            }
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        matchingEntryName = null;
        matchingEntryData = null;
    }

    // build the response
    final ResourceResponse response = new ResourceResponse();
    response.setCacheDuration(Duration.NONE);
    response.setContentDisposition(ContentDisposition.ATTACHMENT);
    if (matchingEntryData == null) {
        response.setFileName("plugin-bundle-" + pluginBundleId + ".jar");
    } else {
        final int lastSlashIndex = matchingEntryName.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            matchingEntryName = matchingEntryName.substring(lastSlashIndex + 1);
        }
        response.setFileName(matchingEntryName);
    }
    response.setWriteCallback(new WriteCallback() {
        @Override
        public void writeData(final Attributes attributes) throws IOException {
            attributes.getResponse().write(matchingEntryData == null ? jarData : matchingEntryData);
        }
    });
    return response;

}

From source file:br.eti.ranieri.opcoesweb.importacao.offline.ImportadorOffline.java

public void importar(URL url, ConfiguracaoImportacao configuracaoImportacao) throws Exception {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new Exception("Requisio HTTP retornou cdigo de erro: " + connection.getResponseCode());
    }/*from  ww w  .  j  av  a 2  s  . c o m*/

    List<CotacaoBDI> cotacoes = null;
    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(connection.getInputStream());
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            if ("BDIN".equals(entry.getName())) {
                cotacoes = parser.parseBDI(zip);
                zip.closeEntry();
                break;
            } else if (entry.getName().startsWith("COTAHIST_") && entry.getName().endsWith(".TXT")) {
                cotacoes = parser.parseHistorico(zip);
                zip.closeEntry();
                break;
            }
        }
        zip.close();
    } catch (ZipException e) {
        log.error("Formato invalido de arquivo zip", e);
    } catch (IOException e) {
        log.error("Erro de leitura do arquivo zip", e);
    } finally {
        if (zip != null)
            IOUtils.closeQuietly(zip);
    }

    calcularBlackScholes(cotacoes, configuracaoImportacao);
}

From source file:com.intuit.tank.agent.AgentStartup.java

public void run() {
    logger.info("Starting up...");
    if (AmazonUtil.usingEip()) {
        try {//from  www  .j a v a2 s .co  m
            logger.info("Using EIP. Sleeping for " + WAIT_FOR_RESTART_TIME + " ms.");
            Thread.sleep(WAIT_FOR_RESTART_TIME);
        } catch (InterruptedException e1) {
            logger.info("Exception waiting.");
            System.exit(0);
        }
    }
    try {
        if (controllerBase == null) {
            controllerBase = AmazonUtil.getControllerBaseUrl();
        }

        logger.info("Starting up: ControllerBaseUrl=" + controllerBase);
        URL url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SETTINGS);
        logger.info("Starting up: making call to tank service url to get settings.xml " + url.toExternalForm());
        InputStream settingsStream = url.openStream();
        try {
            String settings = IOUtils.toString(settingsStream);
            FileUtils.writeStringToFile(new File("settings.xml"), settings);
            logger.info("got settings file...");
        } finally {
            IOUtils.closeQuietly(settingsStream);
        }
        url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SUPPORT);
        logger.info("Making call to tank service url to get support files " + url.toExternalForm());
        ZipInputStream zip = new ZipInputStream(url.openStream());
        try {
            ZipEntry entry = zip.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                logger.info("Got file from controller: " + name);
                File f = new File(name);
                FileOutputStream fout = FileUtils.openOutputStream(f);
                try {
                    IOUtils.copy(zip, fout);
                } finally {
                    IOUtils.closeQuietly(fout);
                }
                entry = zip.getNextEntry();
            }
        } finally {
            IOUtils.closeQuietly(zip);
        }
        // now start the harness
        String jvmArgs = AmazonUtil.getUserDataAsMap().get(TankConstants.KEY_JVM_ARGS);
        logger.info("Starting apiharness with command: " + API_HARNESS_COMMAND + " -http=" + controllerBase
                + " " + jvmArgs);
        Runtime.getRuntime().exec(API_HARNESS_COMMAND + " -http=" + controllerBase + " " + jvmArgs);
    } catch (Exception e) {
        logger.error("Error in AgentStartup " + e, e);
    }
}

From source file:com.moss.fskit.Unzipper.java

public boolean isDirectoryWrapper(File zipFile) throws UnzipException {
    try {//from w  ww.j  a v a  2  s.  c o m
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile));

        boolean firstEntryWasDirectory = false;
        int numEntries = 0;
        for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
            String name = entry.getName().trim();
            if (name.startsWith("/"))
                name = name.substring(1);
            if (name.endsWith("/"))
                name = name.substring(0, name.length() - 2);

            if (name.indexOf('/') == -1) {
                // This is at the 'root' level.
                numEntries++;
                if (numEntries == 1 && entry.isDirectory()) {
                    firstEntryWasDirectory = true;
                }
            }
        }
        in.close();
        return (numEntries == 1) && firstEntryWasDirectory;
    } catch (IOException e) {
        throw new UnzipException("Error processing " + zipFile.getAbsolutePath(), e);
    }

}

From source file:com.facebook.buck.zip.ZipScrubberStepIntegrationTest.java

@Test
public void modificationTimes() throws Exception {

    // Create a dummy ZIP file.
    Path zip = tmp.newFile("output.zip");
    try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
        ZipEntry entry = new ZipEntry("file1");
        byte[] data = "data1".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);//from w  w w  . j a va 2 s .co m
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();

        entry = new ZipEntry("file2");
        data = "data2".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();
    }

    // Execute the zip scrubber step.
    ExecutionContext executionContext = TestExecutionContext.newInstance();
    ZipScrubberStep step = new ZipScrubberStep(new ProjectFilesystem(tmp.getRoot()), Paths.get("output.zip"));
    assertEquals(0, step.execute(executionContext).getExitCode());

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new FileInputStream(zip.toFile()))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:org.trustedanalytics.hadoop.admin.tools.HadoopClientParamsImporter.java

static Optional<Map<String, String>> scanConfigZipArchive(InputStream source)
        throws IOException, XPathExpressionException {

    InputStream zipInputStream = new ZipInputStream(new BufferedInputStream(source));
    ZipEntry zipFileEntry;/*www. ja  va  2 s  . c om*/
    Map<String, String> ret = new HashMap<>();
    while ((zipFileEntry = ((ZipInputStream) zipInputStream).getNextEntry()) != null) {
        if (!zipFileEntry.getName().endsWith("-site.xml")) {
            continue;
        }
        byte[] bytes = IOUtils.toByteArray(zipInputStream);
        InputSource is = new InputSource(new ByteArrayInputStream(bytes));
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate(CONF_PROPERTY_XPATH, is, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node propNode = nodeList.item(i);
            String key = (String) xPath.evaluate("name/text()", propNode, XPathConstants.STRING);
            String value = (String) xPath.evaluate("value/text()", propNode, XPathConstants.STRING);
            ret.put(key, value);
        }
    }
    return Optional.of(ret);
}