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.evolveum.midpoint.ninja.action.worker.ImportProducerWorker.java

@Override
public void run() {
    Log log = context.getLog();/*from  w  ww.j a  v a  2 s .c  om*/

    log.info("Starting import");
    operation.start();

    try (InputStream input = openInputStream()) {
        if (!options.isZip()) {
            processStream(input);
        } else {
            ZipInputStream zis = new ZipInputStream(input);
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }

                if (!StringUtils.endsWith(entry.getName().toLowerCase(), ".xml")) {
                    continue;
                }

                log.info("Processing file {}", entry.getName());
                processStream(zis);
            }
        }
    } catch (IOException ex) {
        log.error("Unexpected error occurred, reason: {}", ex, ex.getMessage());
    } catch (NinjaException ex) {
        log.error(ex.getMessage(), ex);
    } finally {
        markDone();

        if (isWorkersDone()) {
            if (!operation.isFinished()) {
                operation.producerFinish();
            }
        }
    }
}

From source file:com.thoughtworks.go.server.initializers.PluginsInitializerTest.java

@Before
public void setUp() throws Exception {
    systemEnvironment = mock(SystemEnvironment.class);
    goPluginsDir = temporaryFolder.newFolder("go-plugins");
    when(systemEnvironment.get(SystemEnvironment.PLUGIN_GO_PROVIDED_PATH))
            .thenReturn(goPluginsDir.getAbsolutePath());
    pluginManager = mock(PluginManager.class);
    pluginExtensionsAndVersionValidator = mock(PluginExtensionsAndVersionValidator.class);
    elasticAgentInformationMigrator = mock(ElasticAgentInformationMigrator.class);
    pluginsInitializer = new PluginsInitializer(pluginManager, systemEnvironment, new ZipUtil(),
            pluginExtensionsAndVersionValidator, elasticAgentInformationMigrator) {
        @Override//from   w w  w. ja v  a  2 s  .c  o m
        public void startDaemon() {

        }

        @Override
        ZipInputStream getPluginsZipStream() {
            return new ZipInputStream(getClass().getResourceAsStream("/dummy-plugins.zip"));
        }
    };
}

From source file:coral.reef.web.FileUploadController.java

/**
 * Extracts a zip file specified by the zipFilePath to a directory specified
 * by destDirectory (will be created if does not exists)
 * //from   ww w  . ja  v  a 2s.co  m
 * @param zipFilePath
 * @param destDirectory
 * @throws IOException
 */
public void unzip(InputStream zipFilePath, File destDir) throws IOException {
    if (!destDir.exists()) {
        destDir.mkdir();
    }
    ZipInputStream zipIn = new ZipInputStream(zipFilePath);
    ZipEntry entry = zipIn.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        File filePath = new File(destDir, entry.getName());
        if (!entry.isDirectory()) {
            // if the entry is a file, extracts it
            extractFile(zipIn, filePath);
        } else {
            // if the entry is a directory, make the directory
            filePath.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:edu.ku.brc.helpers.ZipFileHelper.java

/**
 * @param zipFile// ww w .  j av a2 s. c  om
 * @return
 * @throws ZipException
 * @throws IOException
 */
public List<File> unzipToFiles(final File zipFile) throws ZipException, IOException {
    Vector<File> files = new Vector<File>();

    final int bufSize = 65535;

    File dir = UIRegistry.getAppDataSubDir(Long.toString(System.currentTimeMillis()) + "_zip", true);
    dirsToRemoveList.add(dir);

    File outFile = null;
    FileOutputStream fos = null;
    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            if (zin.available() > 0) {
                outFile = new File(dir.getCanonicalPath() + File.separator + entry.getName());
                fos = new FileOutputStream(outFile);

                byte[] bytes = new byte[bufSize]; // 64k
                int bytesRead = zin.read(bytes, 0, bufSize);
                while (bytesRead > 0) {
                    fos.write(bytes, 0, bytesRead);
                    bytesRead = zin.read(bytes, 0, bufSize);
                }

                files.insertElementAt(outFile.getCanonicalFile(), 0);
            }
            entry = zin.getNextEntry();
        }

    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return files;
}

From source file:com.aaasec.sigserv.cscommon.DocTypeIdentifier.java

/**
 * Guess the document format and return an appropriate document type string
 *
 * @param is An InputStream holding the document
 * @return "xml" if the document is an XML document or "pdf" if the document
 * is a PDF document, or else an error message.
 *///from w  w  w  .j a v a2 s .  co m
public static SigDocumentType getDocType(InputStream is) {
    InputStream input = null;

    try {
        input = new BufferedInputStream(is);
        input.mark(5);
        byte[] preamble = new byte[5];
        int read = 0;
        try {
            read = input.read(preamble);
            input.reset();
        } catch (IOException ex) {
            return SigDocumentType.Unknown;
        }
        if (read < 5) {
            return SigDocumentType.Unknown;
        }
        String preambleString = new String(preamble);
        byte[] xmlPreable = new byte[] { '<', '?', 'x', 'm', 'l' };
        byte[] xmlUtf8 = new byte[] { -17, -69, -65, '<', '?' };
        if (Arrays.equals(preamble, xmlPreable) || Arrays.equals(preamble, xmlUtf8)) {
            return SigDocumentType.XML;
        } else if (preambleString.equals("%PDF-")) {
            return SigDocumentType.PDF;
        } else if (preamble[0] == 'P' && preamble[1] == 'K') {
            ZipInputStream asics = new ZipInputStream(new BufferedInputStream(is));
            ByteArrayOutputStream datafile = null;
            ByteArrayOutputStream signatures = null;
            ZipEntry entry;
            try {
                while ((entry = asics.getNextEntry()) != null) {
                    if (entry.getName().equals("META-INF/signatures.p7s")) {
                        signatures = new ByteArrayOutputStream();
                        IOUtils.copy(asics, signatures);
                        signatures.close();
                    } else if (entry.getName().equalsIgnoreCase("META-INF/signatures.p7s")) {
                        /* Wrong case */
                        // asics;Non ETSI compliant
                        return SigDocumentType.Unknown;
                    } else if (entry.getName().indexOf("/") == -1) {
                        if (datafile == null) {
                            datafile = new ByteArrayOutputStream();
                            IOUtils.copy(asics, datafile);
                            datafile.close();
                        } else {
                            //                              // asics;ASiC-S profile support only one data file
                            return SigDocumentType.Unknown;
                        }
                    }
                }
            } catch (Exception ex) {
                // null;Invalid ASiC-S
                return SigDocumentType.Unknown;
            }
            if (datafile == null || signatures == null) {
                // asics;ASiC-S profile support only one data file with CAdES signature
                return SigDocumentType.Unknown;
            }
            // asics/cades
            return SigDocumentType.Unknown;

        } else if (preambleString.getBytes()[0] == 0x30) {
            // cades;
            return SigDocumentType.Unknown;
        } else {
            // null;Document format not recognized/handled
            return SigDocumentType.Unknown;
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:net.myrrix.web.servlets.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    MyrrixRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;//from w ww  .j  ava  2 s  .  c  om
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        } else if ("application/x-bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else if ("bzip2".equals(contentEncoding)) {
            reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()),
                    charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

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

/**
 * Read the zipped data in the ODF package and return the inputstream for a
 * given file / zip entry//from ww w .  j a v  a  2  s  .c  o m
 * 
 * @param inputStream
 * @param uri
 * @return inputstream for the file / zip entry
 * @throws IOException
 */
public static InputStream findDataInputStream(InputStream inputStream, String uri) throws IOException {
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (zipEntry.getName().equals(uri)) {
            return zipInputStream;
        }
    }
    return null;
}

From source file:se.crisp.codekvast.warehouse.file_import.ZipFileImporterImpl.java

@Override
@Transactional(rollbackFor = Exception.class)
public void importZipFile(File file) {
    log.debug("Importing {}", file);
    Instant startedAt = now();/*from  ww  w. ja  v  a  2s  .  co  m*/

    ExportFileMetaInfo metaInfo = null;
    ImportDAO.ImportContext context = new ImportDAO.ImportContext();

    try (ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
            InputStreamReader reader = new InputStreamReader(zipInputStream, charset)) {

        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            ExportFileEntry exportFileEntry = ExportFileEntry.fromString(zipEntry.getName());
            log.debug("Reading {} ...", zipEntry.getName());

            switch (exportFileEntry) {
            case META_INFO:
                metaInfo = ExportFileMetaInfo.fromInputStream(zipInputStream);
                if (importDAO.isFileImported(metaInfo)) {
                    log.debug("{} with uuid {} has already been imported", file, metaInfo.getUuid());
                    return;
                }
                break;
            case APPLICATIONS:
                readApplications(reader, context);
                break;
            case METHODS:
                readMethods(reader, context);
                break;
            case JVMS:
                readJvms(reader, context);
                break;
            case INVOCATIONS:
                readInvocations(reader, context);
                break;
            }
        }
        if (metaInfo != null) {
            importDAO.recordFileAsImported(metaInfo,
                    ImportDAO.ImportStatistics.builder().importFile(file)
                            .fileSize(humanReadableByteCount(file.length()))
                            .processingTime(Duration.between(startedAt, now())).build());
        }
    } catch (IllegalArgumentException | IOException e) {
        log.error("Cannot import " + file, e);
    }
}

From source file:com.yahoo.storm.yarn.TestConfig.java

private void unzipFile(String filePath) {
    FileInputStream fis = null;/*w  w w . j  a v a2  s.c o m*/
    ZipInputStream zipIs = null;
    ZipEntry zEntry = null;
    try {
        fis = new FileInputStream(filePath);
        zipIs = new ZipInputStream(new BufferedInputStream(fis));
        while ((zEntry = zipIs.getNextEntry()) != null) {
            try {
                byte[] tmp = new byte[4 * 1024];
                FileOutputStream fos = null;
                String opFilePath = "lib/" + zEntry.getName();
                if (zEntry.isDirectory()) {
                    LOG.debug("Create a folder " + opFilePath);
                    if (zEntry.getName().indexOf(Path.SEPARATOR) == (zEntry.getName().length() - 1))
                        storm_home = opFilePath.substring(0, opFilePath.length() - 1);
                    new File(opFilePath).mkdir();
                } else {
                    LOG.debug("Extracting file to " + opFilePath);
                    fos = new FileOutputStream(opFilePath);
                    int size = 0;
                    while ((size = zipIs.read(tmp)) != -1) {
                        fos.write(tmp, 0, size);
                    }
                    fos.flush();
                    fos.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        zipIs.close();
    } catch (FileNotFoundException e) {
        LOG.warn(e.toString());
    } catch (IOException e) {
        LOG.warn(e.toString());
    }
    LOG.info("storm_home: " + storm_home);
}

From source file:com.microsoft.azurebatch.jenkins.utils.ZipHelper.java

private static void unzipFile(File zipFile, String outputFolderPath) throws FileNotFoundException, IOException {
    ZipInputStream zip = null;/*www  .j av  a2 s  . c o m*/
    try {
        zip = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry;

        while ((entry = zip.getNextEntry()) != null) {
            File entryFile = new File(outputFolderPath, entry.getName());
            if (entry.isDirectory()) {
                if (!entryFile.exists()) {
                    if (!entryFile.mkdirs()) {
                        throw new IOException(String.format("Failed to create folder %s %s", outputFolderPath,
                                entry.getName()));
                    }
                }
            } else {
                // Create parent folder if it's not exist
                File folder = entryFile.getParentFile();
                if (!folder.exists()) {
                    if (!folder.mkdirs()) {
                        throw new IOException(
                                String.format("Failed to create folder %s", folder.getAbsolutePath()));
                    }
                }

                // Create the target file
                if (!entryFile.createNewFile()) {
                    throw new IOException(
                            String.format("Failed to create entry file %s", entryFile.getAbsolutePath()));
                }

                // And rewrite data from stream
                OutputStream os = null;
                try {
                    os = new FileOutputStream(entryFile);
                    IOUtils.copy(zip, os);
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(zip);
    }
}