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.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationZip64Times() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = "data1".getBytes(Charsets.UTF_8);
    try (ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream)) {
        for (long i = 0; i < 2 * Short.MAX_VALUE + 1; i++) {
            ZipEntry entry = new ZipEntry("file" + i);
            entry.setSize(data.length);/* w  w  w . j a  v a 2 s  . co  m*/
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

    byte[] bytes = byteArrayOutputStream.toByteArray();
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // 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 ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:fll.web.setup.CreateDB.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    String redirect;//from  w w w .  j  a  v a 2s .  c  o m
    final StringBuilder message = new StringBuilder();
    InitFilter.initDataSource(application);
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {
        connection = datasource.getConnection();

        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        if (null != request.getAttribute("chooseDescription")) {
            final String description = (String) request.getAttribute("description");
            try {
                final URL descriptionURL = new URL(description);
                final Document document = ChallengeParser
                        .parse(new InputStreamReader(descriptionURL.openStream(), Utilities.DEFAULT_CHARSET));

                GenerateDB.generateDB(document, connection);

                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database</i></p>");
                redirect = "/admin/createUsername.jsp";

            } catch (final MalformedURLException e) {
                throw new FLLInternalException("Could not parse URL from choosen description: " + description,
                        e);
            }
        } else if (null != request.getAttribute("reinitializeDatabase")) {
            // create a new empty database from an XML descriptor
            final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldocument");

            if (null == xmlFileItem || xmlFileItem.getSize() < 1) {
                message.append("<p class='error'>XML description document not specified</p>");
                redirect = "/setup";
            } else {
                final Document document = ChallengeParser
                        .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET));

                GenerateDB.generateDB(document, connection);

                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database</i></p>");
                redirect = "/admin/createUsername.jsp";
            }
        } else if (null != request.getAttribute("createdb")) {
            // import a database from a dump
            final FileItem dumpFileItem = (FileItem) request.getAttribute("dbdump");

            if (null == dumpFileItem || dumpFileItem.getSize() < 1) {
                message.append("<p class='error'>Database dump not specified</p>");
                redirect = "/setup";
            } else {

                ImportDB.loadFromDumpIntoNewDB(new ZipInputStream(dumpFileItem.getInputStream()), connection);

                // remove application variables that depend on the database
                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database from dump</i></p>");
                redirect = "/admin/createUsername.jsp";
            }

        } else {
            message.append(
                    "<p class='error'>Unknown form state, expected form fields not seen: " + request + "</p>");
            redirect = "/setup";
        }

    } catch (final FileUploadException fue) {
        message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>");
        LOG.error(fue, fue);
        redirect = "/setup";
    } catch (final IOException ioe) {
        message.append("<p class='error'>Error reading challenge descriptor: " + ioe.getMessage() + "</p>");
        LOG.error(ioe, ioe);
        redirect = "/setup";
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error loading data into the database: " + sqle.getMessage() + "</p>");
        LOG.error(sqle, sqle);
        redirect = "/setup";
    } finally {
        SQLFunctions.close(connection);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + redirect));

}

From source file:com.metamx.druid.loading.S3ZippedSegmentPuller.java

@Override
public File getSegmentFiles(DataSegment segment) throws StorageAdapterLoadingException {
    Map<String, Object> loadSpec = segment.getLoadSpec();
    String s3Bucket = MapUtils.getString(loadSpec, "bucket");
    String s3Path = MapUtils.getString(loadSpec, "key");

    if (s3Path.startsWith("/")) {
        s3Path = s3Path.substring(1);
    }/*w  w  w.j  a  v a 2 s . c  o m*/

    log.info("Loading index at path[s3://%s/%s]", s3Bucket, s3Path);

    S3Object s3Obj = null;
    File tmpFile = null;
    try {
        if (!s3Client.isObjectInBucket(s3Bucket, s3Path)) {
            throw new StorageAdapterLoadingException("IndexFile[s3://%s/%s] does not exist.", s3Bucket, s3Path);
        }

        File cacheFile = new File(config.getCacheDirectory(), computeCacheFilePath(s3Bucket, s3Path));

        if (cacheFile.exists()) {
            S3Object objDetails = s3Client.getObjectDetails(new S3Bucket(s3Bucket), s3Path);
            DateTime cacheFileLastModified = new DateTime(cacheFile.lastModified());
            DateTime s3ObjLastModified = new DateTime(objDetails.getLastModifiedDate().getTime());
            if (cacheFileLastModified.isAfter(s3ObjLastModified)) {
                log.info("Found cacheFile[%s] with modified[%s], which is after s3Obj[%s].  Using.", cacheFile,
                        cacheFileLastModified, s3ObjLastModified);
                return cacheFile;
            }
            FileUtils.deleteDirectory(cacheFile);
        }

        long currTime = System.currentTimeMillis();

        tmpFile = File.createTempFile(s3Bucket, new DateTime().toString());
        log.info("Downloading file[s3://%s/%s] to local tmpFile[%s] for cacheFile[%s]", s3Bucket, s3Path,
                tmpFile, cacheFile);

        s3Obj = s3Client.getObject(new S3Bucket(s3Bucket), s3Path);
        StreamUtils.copyToFileAndClose(s3Obj.getDataInputStream(), tmpFile);
        final long downloadEndTime = System.currentTimeMillis();
        log.info("Download of file[%s] completed in %,d millis", cacheFile, downloadEndTime - currTime);

        if (cacheFile.exists()) {
            FileUtils.deleteDirectory(cacheFile);
        }
        cacheFile.mkdirs();

        ZipInputStream zipIn = null;
        OutputStream out = null;
        ZipEntry entry = null;
        try {
            zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(tmpFile)));
            while ((entry = zipIn.getNextEntry()) != null) {
                out = new FileOutputStream(new File(cacheFile, entry.getName()));
                IOUtils.copy(zipIn, out);
                zipIn.closeEntry();
                Closeables.closeQuietly(out);
                out = null;
            }
        } finally {
            Closeables.closeQuietly(out);
            Closeables.closeQuietly(zipIn);
        }

        long endTime = System.currentTimeMillis();
        log.info("Local processing of file[%s] done in %,d millis", cacheFile, endTime - downloadEndTime);

        log.info("Deleting tmpFile[%s]", tmpFile);
        tmpFile.delete();

        return cacheFile;
    } catch (Exception e) {
        throw new StorageAdapterLoadingException(e, e.getMessage());
    } finally {
        S3Utils.closeStreamsQuietly(s3Obj);
        if (tmpFile != null && tmpFile.exists()) {
            log.warn("Deleting tmpFile[%s] in finally block.  Why?", tmpFile);
            tmpFile.delete();
        }
    }
}

From source file:gabi.FileUploadServlet.java

private static void unzip(String zipFilePath, String destDir) {
    File dir = new File(destDir);
    // create output directory if it doesn't exist
    if (!dir.exists())
        dir.mkdirs();//www  .j a va  2  s.c o  m
    FileInputStream fis;
    //buffer for read and write data to file
    byte[] buffer = new byte[1024];
    try {
        fis = new FileInputStream(zipFilePath);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(destDir + File.separator + fileName);
            System.out.println("Unzipping to " + newFile.getAbsolutePath());
            //create directories for sub directories in zip
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            //close this ZipEntry
            zis.closeEntry();
            ze = zis.getNextEntry();
        }
        //close last ZipEntry
        zis.closeEntry();
        zis.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

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

private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
    LOG.debug("output signed open document");
    OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
    if (null == signedOdfOutputStream) {
        throw new NullPointerException("signedOpenDocumentOutputStream is null");
    }/*from  www.  j a  v  a2 s  .  c  om*/
    /*
     * Copy the original ODF content to the signed ODF package.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();
    /*
     * Add the ODF XML signature file to the signed ODF package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.openkm.module.direct.DirectWorkflowModule.java

@Override
public void registerProcessDefinition(String token, InputStream is)
        throws ParseException, RepositoryException, WorkflowException, DatabaseException, IOException {
    log.debug("registerProcessDefinition({}, {})", token, is);
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    InputStream isForms = null;//  w w w . jav a2  s . c o  m
    ZipInputStream zis = null;
    Session session = null;

    try {
        if (token == null) {
            session = JCRUtils.getSession();
        } else {
            session = JcrSessionManager.getInstance().get(token);
        }

        zis = new ZipInputStream(is);
        org.jbpm.graph.def.ProcessDefinition processDefinition = org.jbpm.graph.def.ProcessDefinition
                .parseParZipInputStream(zis);

        // Check xml form definition  
        FileDefinition fileDef = processDefinition.getFileDefinition();
        isForms = fileDef.getInputStream("forms.xml");
        FormUtils.parseWorkflowForms(isForms);

        // If it is ok, deploy it
        jbpmContext.deployProcessDefinition(processDefinition);

        // Activity log
        UserActivity.log(session.getUserID(), "REGISTER_PROCESS_DEFINITION", null, null);
    } catch (javax.jcr.RepositoryException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        if (token == null)
            JCRUtils.logout(session);
        IOUtils.closeQuietly(isForms);
        IOUtils.closeQuietly(zis);
        jbpmContext.close();
    }

    log.debug("registerProcessDefinition: void");
}

From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java

public void unpackBundleZipToFS(String bundle_path, File fs_path) {
    URL zip_url = fBundle.getEntry(bundle_path);
    TestCase.assertNotNull(zip_url);/*  ww w  . j  av a 2s . com*/

    if (!fs_path.isDirectory()) {
        TestCase.assertTrue(fs_path.mkdirs());
    }

    try {
        InputStream in = zip_url.openStream();
        TestCase.assertNotNull(in);
        byte tmp[] = new byte[4 * 1024];
        int cnt;

        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry ze;

        while ((ze = zin.getNextEntry()) != null) {
            // System.out.println("Entry: \"" + ze.getName() + "\"");
            File entry_f = new File(fs_path, ze.getName());
            if (ze.getName().endsWith("/")) {
                // Directory
                continue;
            }
            if (!entry_f.getParentFile().exists()) {
                TestCase.assertTrue(entry_f.getParentFile().mkdirs());
            }
            FileOutputStream fos = new FileOutputStream(entry_f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length);

            while ((cnt = zin.read(tmp, 0, tmp.length)) > 0) {
                bos.write(tmp, 0, cnt);
            }
            bos.flush();
            bos.close();
            fos.close();

            zin.closeEntry();
        }
        zin.close();
    } catch (IOException e) {
        e.printStackTrace();
        TestCase.fail("Failed to unpack zip file: " + e.getMessage());
    }
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Extract the given ZIP file into the given destination folder.
 * //from  w  ww.  j av a 2 s  . co m
 * @param zipFile
 *            file to extract
 *            
 * @param baseFolder
 *            destination folder to extract in
 */
public static void extractZipToFolder(File zipFile, File baseFolder) {
    try {
        byte[] buf = new byte[1024];

        ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry zipentry = zipinputstream.getNextEntry();

        while (zipentry != null) {
            // for each entry to be extracted
            String entryName = zipentry.getName();

            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);

            int numBytes;
            FileOutputStream fileoutputstream;
            File newFile = new File(baseFolder, entryName);
            if (zipentry.isDirectory()) {
                if (!newFile.mkdirs()) {
                    break;
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            fileoutputstream = new FileOutputStream(newFile);
            while ((numBytes = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, numBytes);
            }

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        }

        zipinputstream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

ZipInputStream getPackagedRepositoryZipStream() {
    InputStream resourceAsStream = this.getClass()
            .getResourceAsStream(systemEnvironment.get(DEFAULT_COMMAND_SNIPPETS_ZIP));
    if (resourceAsStream == null) {
        throw new RuntimeException("Could not find default command snippets zip on classpath.");
    }// w  w  w. j a  va 2s . c  o m
    return new ZipInputStream(resourceAsStream);
}

From source file:be.i8c.sag.util.FileUtils.java

/**
 * Extract files from a zipped (and jar) file
 *
 * @param internalDir The directory you want to copy
 * @param zipFile The file that contains the content you want to copy
 * @param to The directory you want to copy to
 * @param deleteOnExit If true, delete the files once the application has closed.
 * @throws IOException When failed to write to a file
 * @throws FileNotFoundException If a file could not be found
 *///from  w  w  w.  j ava2s. c om
public static void extractDirectory(String internalDir, File zipFile, File to, boolean deleteOnExit)
        throws IOException {
    try (ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile))) {
        while (true) {
            ZipEntry zipEntry = zip.getNextEntry();
            if (zipEntry == null)
                break;

            if (zipEntry.getName().startsWith(internalDir) && !zipEntry.isDirectory()) {
                File f = createFile(new File(to, zipEntry.getName()
                        .replace((internalDir.endsWith("/") ? internalDir : internalDir + "/"), "")));
                if (deleteOnExit)
                    f.deleteOnExit();
                OutputStream bos = new FileOutputStream(f);
                try {
                    IOUtils.copy(zip, bos);
                } finally {
                    bos.flush();
                    bos.close();
                }
            }

            zip.closeEntry();
        }
    }
}