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:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddDataFileController.java

/**
 * Processing of the valid form/*w w  w . ja  va2 s . com*/
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    log.debug("Processing form data.");
    AddDataFileCommand addDataCommand = (AddDataFileCommand) command;
    MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
    // the map containing file names mapped to files
    Map m = mpRequest.getFileMap();
    Set set = m.keySet();
    for (Object key : set) {
        MultipartFile file = (MultipartFile) m.get(key);

        if (file == null) {
            log.error("No file was uploaded!");
        } else {
            log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId());
            Experiment experiment = new Experiment();
            experiment.setExperimentId(addDataCommand.getMeasurationId());
            if (file.getOriginalFilename().endsWith(".zip")) {
                ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes()));
                ZipEntry en = zis.getNextEntry();
                while (en != null) {
                    if (en.isDirectory()) {
                        en = zis.getNextEntry();
                        continue;
                    }
                    DataFile data = new DataFile();
                    data.setExperiment(experiment);
                    String name[] = en.getName().split("/");
                    data.setFilename(name[name.length - 1]);
                    data.setDescription(addDataCommand.getDescription());
                    data.setFileContent(Hibernate.createBlob(zis));
                    String[] partOfName = en.getName().split("[.]");
                    data.setMimetype(partOfName[partOfName.length - 1]);
                    dataFileDao.create(data);
                    en = zis.getNextEntry();
                }
            } else {
                log.debug("Creating new Data object.");
                DataFile data = new DataFile();
                data.setExperiment(experiment);

                log.debug("Original name of uploaded file: " + file.getOriginalFilename());
                String filename = file.getOriginalFilename().replace(" ", "_");
                data.setFilename(filename);

                log.debug("MIME type of the uploaded file: " + file.getContentType());
                if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) {
                    int index = filename.lastIndexOf(".");
                    data.setMimetype(filename.substring(index));
                } else {
                    data.setMimetype(file.getContentType());
                }

                log.debug("Parsing the sapmling rate.");
                data.setDescription(addDataCommand.getDescription());

                log.debug("Setting the binary data to object.");
                data.setFileContent(Hibernate.createBlob(file.getBytes()));

                dataFileDao.create(data);
                log.debug("Data stored into database.");
            }
        }
    }

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(
            "redirect:/experiments/detail.html?experimentId=" + addDataCommand.getMeasurationId());
    return mav;
}

From source file:com.boundlessgeo.geoserver.bundle.BundleExporterTest.java

@Test
public void testZipBundle() throws Exception {
    new CatalogCreator(cat).workspace("foo");
    exporter = new BundleExporter(cat, new ExportOpts(cat.getWorkspaceByName("foo")).name("blah"));

    exporter.run();//from w ww. jav  a2  s  . c  o m
    Path zip = exporter.zip();
    ZipInputStream zin = new ZipInputStream(
            new ByteArrayInputStream(FileUtils.readFileToByteArray(zip.toFile())));
    ZipEntry entry = null;

    boolean foundBundle = false;
    boolean foundWorkspace = false;

    while (((entry = zin.getNextEntry()) != null)) {
        if (entry.getName().equals("bundle.json")) {
            foundBundle = true;
        }
        if (entry.getName().endsWith("workspace.xml")) {
            foundWorkspace = true;
        }
    }

    assertTrue(foundBundle);
    assertTrue(foundWorkspace);
}

From source file:net.grinder.util.LogCompressUtil.java

/**
 * Uncompress the given the {@link InputStream} into the given {@link OutputStream}.
 * //from w  ww . j  a  v a  2  s  .c  o  m
 * @param inputStream
 *            input stream of the compressed file
 * @param outputStream
 *            file to be written
 * @param limit
 *            the limit of the output
 */
public static void unCompress(InputStream inputStream, OutputStream outputStream, long limit) {
    ZipInputStream zipInputStream = null;
    try {
        zipInputStream = new ZipInputStream(inputStream);
        byte[] buffer = new byte[COMPRESS_BUFFER_SIZE];
        int count = 0;
        long total = 0;
        checkNotNull(zipInputStream.getNextEntry(), "In zip, it should have at least one entry");
        while ((count = zipInputStream.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
            total += count;
            if (total >= limit) {
                break;
            }
            outputStream.write(buffer, 0, count);
        }
        outputStream.flush();
    } catch (IOException e) {
        LOGGER.error("Error occurs while uncompress");
        LOGGER.error("Details", e);
        return;
    } finally {
        IOUtils.closeQuietly(zipInputStream);
    }
}

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

/**
 * Adds a zipfile from an inputStream to the aggregate zipfile.
 *
 * @param dirName name of the top-level directory that will be
 * @param inputStream the inputStream to the zipfile created in the aggregate zip file
 * @throws IOException/*from   w  ww.j  av  a  2s .  c o  m*/
 * @throws BadInputZipFileException
 */
private void addZipFileFromInputStream(String dirName, long time, InputStream inputStream)
        throws IOException, BadInputZipFileException {
    // First pass: just scan through the contents of the
    // input file to make sure it's really valid.
    ZipInputStream zipInput = null;
    try {
        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            zipInput.closeEntry();
        }
    } catch (IOException e) {
        throw new BadInputZipFileException("Input zip file seems to be invalid", e);
    } finally {
        if (zipInput != null)
            zipInput.close();
    }

    // FIXME: It is probably wrong to call reset() on any input stream; for my application the inputStream will only ByteArrayInputStream or FileInputStream
    inputStream.reset();

    // Second pass: read each entry from the input zip file,
    // writing it to the output file.
    zipInput = null;
    try {
        // add the root directory with the correct timestamp
        if (time > 0L) {
            // Create output entry
            ZipEntry outputEntry = new ZipEntry(dirName + "/");
            outputEntry.setTime(time);
            zipOutput.closeEntry();
        }

        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            try {
                String name = entry.getName();
                // Convert absolute paths to relative
                if (name.startsWith("/")) {
                    name = name.substring(1);
                }

                // Prepend directory name
                name = dirName + "/" + name;

                // Create output entry
                ZipEntry outputEntry = new ZipEntry(name);
                if (time > 0L)
                    outputEntry.setTime(time);
                zipOutput.putNextEntry(outputEntry);

                // Copy zip input to output
                CopyUtils.copy(zipInput, zipOutput);
            } catch (Exception zex) {
                // ignore it
            } finally {
                zipInput.closeEntry();
                zipOutput.closeEntry();
            }
        }
    } finally {
        if (zipInput != null) {
            try {
                zipInput.close();
            } catch (IOException ignore) {
                // Ignore
            }
        }
    }
}

From source file:eionet.gdem.conversion.odf.ODFSpreadsheetAnalyzer.java

/**
 * Analyze the content file in a <code>File</code> which is a .zip file.
 *
 * @param inputStream//from www . jav  a  2s. c om
 *            a <code>File</code> that contains OpenDocument content-information information.
 */
public OpenDocumentSpreadsheet analyzeZip(InputStream inputStream) {
    OpenDocumentSpreadsheet spreadsheet = null;
    ZipInputStream zipStream = null;
    try {
        zipStream = new ZipInputStream(inputStream);
        while (zipStream.available() == 1) {
            // read possible contentEntry
            ZipEntry cententEntry = zipStream.getNextEntry();
            if (cententEntry != null) {
                if ("content.xml".equals(cententEntry.getName())) {
                    // if real contentEntry we use content to do real
                    // analysis
                    spreadsheet = analyzeSpreadsheet(zipStream);
                    // analyze is made and we can break the loop
                    break;
                }
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        IOUtils.closeQuietly(zipStream);
    }
    return spreadsheet;
}

From source file:es.eucm.mokap.backend.controller.insert.MokapInsertController.java

/**
 * Processes a temp file stored in Cloud Storage: -It analyzes its contents
 * -Processes the descriptor.json file and stores the entity in Datastore
 * -Finally it stores the thumbnails and contents.zip in Cloud Storage
 * //w w  w. java  2  s.com
 * @param tempFileName
 *            name of the temp file we are going to process
 * @return The Datastore Key id for the entity we just created (entityRef in
 *         RepoElement)
 * @throws IOException
 *             If the file is not accessible or Cloud Storage is not
 *             available ServerError If a problem is found with the internal
 *             structure of the file
 */
private long processUploadedTempFile(String tempFileName) throws IOException, ServerError {
    long assignedKeyId;
    // Read the cloud storage file
    byte[] content = null;
    String descriptor = "";
    Map<String, byte[]> tns = new HashMap<String, byte[]>();
    InputStream is = st.readFile(tempFileName);
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        String filename = entry.getName();
        if (UploadZipStructure.isContentsFile(filename)) {
            content = IOUtils.toByteArray(zis);
        } else if (UploadZipStructure.isDescriptorFile(filename)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(zis, "UTF-8"));
            String str;
            while ((str = br.readLine()) != null) {
                descriptor += str;
            }
        } else if (entry.isDirectory()) {
            continue;
        }
        // Should be a thumbnail
        else if (UploadZipStructure.checkThumbnailImage(filename)) {
            byte[] img = IOUtils.toByteArray(zis);
            tns.put(filename, img);
        }
        zis.closeEntry();
    }

    try {
        if (descriptor != null && !descriptor.equals("") && content != null) {
            // Analizar json
            Map<String, Object> entMap = Utils.jsonToMap(descriptor);
            // Parse the map into an entity
            Entity ent = new Entity("Resource");
            for (String key : entMap.keySet()) {
                ent.setProperty(key, entMap.get(key));
            }
            // Store the entity (GDS) and get the Id
            Key k = db.storeEntity(ent);
            assignedKeyId = k.getId();

            // Store the contents file with the Id in the name
            ByteArrayInputStream bis = new ByteArrayInputStream(content);
            st.storeFile(bis, assignedKeyId + UploadZipStructure.ZIP_EXTENSION);

            // Store the thumbnails in a folder with the id as the name
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.storeFile(imgs, assignedKeyId + "/" + key);
            }
            // Create the Search Index Document
            db.addToSearchIndex(ent, k);

            // Everything went ok, so we delete the temp file
            st.deleteFile(tempFileName);
        } else {
            assignedKeyId = 0;
            if (descriptor == null || descriptor.equals("")) {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_DESCRIPTOR);
            } else {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_CONTENT);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        assignedKeyId = 0;
        // Force rollback if anything failed
        try {
            st.deleteFile(tempFileName);
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.deleteFile(assignedKeyId + "/" + key);
            }
            db.deleteEntity(assignedKeyId);
        } catch (Exception ex) {
        }
    }
    return assignedKeyId;
}

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

/**
 * Get a list of all the files / zip entries in an ODF package
 * /*w ww  .  j  a  va2 s .  c  o  m*/
 * @param odfInputStream
 * @return
 * @throws IOException
 */
public static List getZipEntriesAsList(InputStream odfInputStream) throws IOException {
    ArrayList list = new ArrayList();

    ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
    ZipEntry zipEntry;

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        list.add(zipEntry.getName());
    }
    return list;
}

From source file:de.pksoftware.springstrap.sapi.util.WebappZipper.java

/**
 * Unzip it//from w w w.  j av  a 2 s .c  o  m
 * @param zipFile input zip file
 * @param output zip file output folder
 */
public static void unzip(String zipFile, String outputFolder) {
    logger.info("Unzipping {} into {}.", zipFile, outputFolder);

    byte[] buffer = new byte[1024];

    try {

        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);

            logger.debug("Unzipping: {}", newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            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();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

        logger.debug("Unzipping {} completed.", zipFile);

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.tm.management.FileUploadHelper.java

private File saveTmpFile(List<FileItem> fileItems) throws Exception {
    File file = null;//from w  w  w.  j a va2s  .c o m

    // Create a temporary file to store the contents in it for now. We might
    // not have additional information, such as TUV id for building the
    // complete file path. We will save the contents in this file for now
    // and finally rename it to correct file name.
    file = File.createTempFile("GSTMUpload", null);

    // Set overall request size constraint
    long uploadTotalSize = 0;
    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            uploadTotalSize += item.getSize();
        }
    }
    status.setTotalSize(uploadTotalSize);

    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            // If it's a ZIP archive, then expand it on the fly.
            // Disallow archives containing multiple files; let the
            // rest of the import/validation code figure out if the
            // contents is actually TMX or not.
            String fileName = getFileName(item.getName());
            if (fileName.toLowerCase().endsWith(".zip")) {
                CATEGORY.info("Encountered zipped upload " + fileName);
                ZipInputStream zis = new ZipInputStream(item.getInputStream());
                boolean foundFile = false;
                for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) {
                    if (e.isDirectory()) {
                        continue;
                    }

                    if (foundFile) {
                        throw new IllegalArgumentException(
                                "Uploaded zip archives should only " + "contain a single file.");
                    }
                    foundFile = true;

                    FileOutputStream os = new FileOutputStream(file);
                    int expandedSize = copyData(zis, os);
                    os.close();
                    // Update file name and size to reflect zip entry
                    setFilename(getFileName(e.getName()));
                    status.setTotalSize(expandedSize);
                    CATEGORY.info("Saved archive entry " + e.getName() + " to tempfile " + file);
                }
            } else {
                item.write(file);
                setFilename(fileName);
                CATEGORY.info("Saving upload " + fileName + " to tempfile " + file);
            }
        } else {
            m_fields.put(item.getFieldName(), item.getString());
        }
    }

    return file;
}

From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java

/**
 * Main method which extracts given Maven Archetype in destination directory
 *
 * @return/*w w w.  jav a 2s .c o  m*/
 */
public int execute() throws IOException {
    outputDir.mkdirs();

    if (packageName == null || packageName.length() == 0) {
        packageName = groupId + "." + artifactId;
    }

    String packageDir = packageName.replace('.', '/');

    info("Creating archetype using Maven groupId: " + groupId + ", artifactId: " + artifactId + ", version: "
            + version + " in directory: " + outputDir);

    Map<String, String> replaceProperties = new HashMap<String, String>();

    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(archetypeIn);
        boolean ok = true;
        while (ok) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) {
                ok = false;
            } else {
                if (!entry.isDirectory()) {
                    String fullName = entry.getName();
                    if (fullName != null && fullName.startsWith(zipEntryPrefix)) {
                        String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()),
                                replaceProperties);
                        debug("Processing resource: " + name);

                        int idx = name.lastIndexOf('/');
                        Matcher matcher = sourcePathRegexPattern.matcher(name);
                        String dirName;
                        if (packageName.length() > 0 && idx > 0 && matcher.matches()) {
                            String prefix = matcher.group(1);
                            dirName = prefix + packageDir + "/" + name.substring(prefix.length());
                        } else if (packageName.length() > 0 && name.startsWith(webInfResources)) {
                            dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources"
                                    + name.substring(webInfResources.length());
                        } else {
                            dirName = name;
                        }

                        // lets replace properties...
                        File file = new File(outputDir, dirName);
                        file.getParentFile().mkdirs();
                        FileOutputStream out = null;
                        try {
                            out = new FileOutputStream(file);
                            boolean isBinary = false;
                            for (String suffix : binarySuffixes) {
                                if (name.endsWith(suffix)) {
                                    isBinary = true;
                                    break;
                                }
                            }
                            if (isBinary) {
                                // binary file?  don't transform.
                                copy(zip, out);
                            } else {
                                // text file...
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                copy(zip, bos);
                                String text = new String(bos.toByteArray(), "UTF-8");
                                out.write(transformContents(text, replaceProperties).getBytes());
                            }
                        } finally {
                            if (out != null) {
                                out.close();
                            }
                        }
                    } else if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) {
                        // we assume that this resource will be first in Archetype's ZIP
                        // this way we can find out what are the required properties before we will actually use them
                        parseReplaceProperties(zip, replaceProperties);
                        replaceProperties.putAll(overrideProperties);
                    }
                }
                zip.closeEntry();
            }
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (zip != null) {
            zip.close();
        }
    }

    info("Using replace properties: " + replaceProperties);

    // now lets replace all the properties in the pom.xml
    if (!replaceProperties.isEmpty()) {
        File pom = new File(outputDir, "pom.xml");
        FileReader reader = new FileReader(pom);
        String text = IOUtils.toString(reader);
        IOUtils.closeQuietly(reader);
        for (Map.Entry<String, String> e : replaceProperties.entrySet()) {
            text = replaceVariable(text, e.getKey(), e.getValue());
        }
        FileWriter writer = new FileWriter(pom);
        IOUtils.write(text, writer);
        IOUtils.closeQuietly(writer);
    }

    // now lets create the default directories
    if (createDefaultDirectories) {
        File srcDir = new File(outputDir, "src");
        File mainDir = new File(srcDir, "main");
        File testDir = new File(srcDir, "test");

        String srcDirName = "java";
        // Who needs Scala in 2014?
        //            if (new File(mainDir, "scala").exists() || new File(textDir, "scala").exists()) {
        //                srcDirName = "scala";
        //            }

        for (File dir : new File[] { mainDir, testDir }) {
            for (String name : new String[] { srcDirName + "/" + packageDir, "resources" }) {
                new File(dir, name).mkdirs();
            }
        }
    }

    return 0;
}