Example usage for java.util.zip ZipInputStream getNextEntry

List of usage examples for java.util.zip ZipInputStream getNextEntry

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream getNextEntry.

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:com.xpn.xwiki.plugin.zipexplorer.ZipExplorerPlugin.java

/**
 * For ZIP URLs of the format <code>http://[...]/zipfile.zip/SomeDirectory/SomeFile.txt</code> return a new
 * attachment containing the file pointed to inside the ZIP. If the original attachment does not point to a ZIP file
 * or if it doesn't specify a location inside the ZIP then do nothing and return the original attachment.
 * //from   w  w  w  .  j a v a  2 s .c  o  m
 * @param attachment the original attachment
 * @param context the XWiki context, used to get the request URL corresponding to the download request
 * @return a new attachment pointing to the file pointed to by the URL inside the ZIP or the original attachment if
 *         the requested URL doesn't specify a file inside a ZIP
 * @see com.xpn.xwiki.plugin.XWikiDefaultPlugin#downloadAttachment
 */
@Override
public XWikiAttachment downloadAttachment(XWikiAttachment attachment, XWikiContext context) {
    String url = context.getRequest().getRequestURI();

    // Verify if we should return the original attachment. This will happen if the requested
    // download URL doesn't point to a zip or if the URL doesn't point to a file inside the ZIP.
    if (!isValidZipURL(url, context.getAction().trim())) {
        return attachment;
    }

    String filename = getFileLocationFromZipURL(url, context.getAction().trim());

    // Create the new attachment pointing to the file inside the ZIP
    XWikiAttachment newAttachment = new XWikiAttachment();
    newAttachment.setDoc(attachment.getDoc());
    newAttachment.setAuthor(attachment.getAuthor());
    newAttachment.setDate(attachment.getDate());

    InputStream stream = null;
    try {
        stream = new BufferedInputStream(attachment.getContentInputStream(context));

        if (!isZipFile(stream)) {
            return attachment;
        }

        ZipInputStream zis = new ZipInputStream(stream);
        ZipEntry entry;

        while ((entry = zis.getNextEntry()) != null) {
            String entryName = entry.getName();

            if (entryName.equals(filename)) {
                newAttachment.setFilename(entryName);

                if (entry.getSize() == -1) {
                    // Note: We're copying the content of the file in the ZIP in memory. This is
                    // potentially going to cause an error if the file's size is greater than the
                    // maximum size of a byte[] array in Java or if there's not enough memomry.
                    byte[] data = IOUtils.toByteArray(zis);

                    newAttachment.setContent(data);
                } else {
                    newAttachment.setContent(zis, (int) entry.getSize());
                }
                break;
            }
        }
    } catch (XWikiException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return newAttachment;
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

private void initialize() {
    this.init = true;

    try {/* w ww .  j  a va2 s .  c  om*/
        InputStream in = new FileInputStream(getSourceFile());
        ArrayList<String> itemList = new ArrayList<String>();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        String item = null;
        final int bufLength = 1024;
        char[] buffer = new char[bufLength];
        int readReturn;
        int count = 0;

        ZipEntry zipentry;
        ZipInputStream zipinputstream = new ZipInputStream(in);

        while ((zipentry = zipinputstream.getNextEntry()) != null) {
            count++;
            StringWriter sw = new StringWriter();
            Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8"));

            while ((readReturn = reader.read(buffer)) != -1) {
                sw.write(buffer, 0, readReturn);
            }

            item = new String(sw.toString());
            itemList.add(item);
            this.fileNames.add(zipentry.getName());

            reader.close();
            zipinputstream.closeEntry();

        }

        this.logger.debug("Zip file contains " + count + "elements");
        zipinputstream.close();
        this.counter = 0;

        this.originalData = byteArrayOutputStream.toByteArray();
        this.items = itemList.toArray(new String[] {});
        this.length = this.items.length;
    } catch (Exception e) {
        this.logger.error("Could not read zip File: " + e.getMessage());
        throw new RuntimeException("Error reading input stream", e);
    }
}

From source file:ch.puzzle.itc.mobiliar.business.shakedown.control.ShakedownTestRunner.java

String bundleSTM(String strcsv, String stscsv, STS sts) throws ShakedownTestException {
    String tmpdir = System.getProperty("java.io.tmpdir");
    String stmpath = ConfigurationService.getProperty(ConfigKey.STM_PATH);
    if (tmpdir != null && !tmpdir.trim().isEmpty()) {
        if (stmpath != null && new File(stmpath).exists()) {
            try {
                File bundle = new File(tmpdir + File.separator + sts.getTestId() + "stm.jar");
                ZipOutputStream bundleZOS = new ZipOutputStream(new FileOutputStream(bundle));
                bundleZOS.putNextEntry(new ZipEntry("str.csv"));
                IOUtils.write(strcsv, bundleZOS);
                bundleZOS.putNextEntry(new ZipEntry("sts.csv"));
                IOUtils.write(stscsv, bundleZOS);
                ZipInputStream zin = new ZipInputStream(new FileInputStream(stmpath));
                ZipEntry ze;// w w w . j  a  v a  2s  .  c o m
                while ((ze = zin.getNextEntry()) != null) {
                    bundleZOS.putNextEntry(ze);
                    IOUtils.copy(zin, bundleZOS);
                }
                bundleZOS.close();
                log.info("Successfully bundled STM and stored to " + bundle.getAbsolutePath());
            } catch (IOException e) {
                throw new ShakedownTestException("Was not able to bundle STM", e);
            }
        } else {
            throw new ShakedownTestException(
                    "No STM found at location configured with system property " + ConfigKey.STM_PATH + ".");
        }
    } else {
        throw new ShakedownTestException("No temporary folder found - is java.io.tmpdir defined?");
    }
    return tmpdir + File.separator + sts.getTestId() + "stm.jar";
}

From source file:com.gatf.executor.report.ReportHandler.java

/**
  * @param zipFile//from  www  .ja  v a2  s  . c om
  * @param directoryToExtractTo Provides file unzip functionality
  */
public static void unzipZipFile(InputStream zipFile, String directoryToExtractTo) {
    ZipInputStream in = new ZipInputStream(zipFile);
    try {
        File directory = new File(directoryToExtractTo);
        if (!directory.exists()) {
            directory.mkdirs();
            logger.info("Creating directory for Extraction...");
        }
        ZipEntry entry = in.getNextEntry();
        while (entry != null) {
            try {
                File file = new File(directory, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    FileOutputStream out = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    out.close();
                }
                in.closeEntry();
                entry = in.getNextEntry();
            } catch (Exception e) {
                logger.severe(ExceptionUtils.getStackTrace(e));
            }
        }
    } catch (IOException ioe) {
        logger.severe(ExceptionUtils.getStackTrace(ioe));
        return;
    }
}

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

private File saveTmpFile(List<FileItem> fileItems) throws Exception {
    File file = null;/*from  ww  w.jav a2s . com*/

    // 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: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  w  w  .j  a  v a2s. com
 * @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:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Unzips all elements in the file represented by byte[] data.
 * Needed by retrieveRawJudgments which will retrieve a zip-file with a single JSON
 * @param data//from  w ww.ja v a 2  s .  co  m
 * @return unzipped data
 * @throws IOException
 */

byte[] unzip(final byte[] data) throws IOException {
    final InputStream input = new ByteArrayInputStream(data);
    final byte[] buffer = new byte[1024];

    final ZipInputStream zip = new ZipInputStream(input);
    final ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
    int count = 0;

    if (zip.getNextEntry() != null) {
        while ((count = zip.read(buffer)) != -1) {
            out.write(buffer, 0, count);
        }
    }

    out.flush();
    zip.close();
    out.close();

    return out.toByteArray();
}

From source file:com.dibsyhex.apkdissector.ZipReader.java

public void getZipContents(String name) {
    try {/*w  ww  .  j a va  2 s  . co m*/
        File file = new File(name);
        FileInputStream fileInputStream = new FileInputStream(file);
        ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
        //System.out.println(zipInputStream.available());
        //System.out.println("Reading each entries in details:");
        ZipFile zipFile = new ZipFile(file);
        ZipEntry zipEntry;

        response.displayLog("Begining to extract");

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String filename = "extracts" + File.separator + file.getName() + File.separator
                    + zipEntry.getName();
            System.out.println(filename);
            response.displayLog(filename);
            File extractDirectory = new File(filename);

            //Create the directories
            new File(extractDirectory.getParent()).mkdirs();

            //Now write the contents

            InputStream inputStream = zipFile.getInputStream(zipEntry);
            OutputStream outputStream = new FileOutputStream(extractDirectory);

            FileUtils.copyInputStreamToFile(inputStream, extractDirectory);

            //Decode the xml files

            if (filename.endsWith(".xml")) {
                //First create a temp file at a location temp/extract/...
                File temp = new File("temp" + File.separator + extractDirectory);
                new File(temp.getParent()).mkdirs();

                //Create an object of XML Decoder
                XmlDecoder xmlDecoder = new XmlDecoder();
                InputStream inputStreamTemp = new FileInputStream(extractDirectory);
                byte[] buf = new byte[80000];//increase
                int bytesRead = inputStreamTemp.read(buf);
                String xml = xmlDecoder.decompressXML(buf);
                //System.out.println(xml);
                FileUtils.writeStringToFile(temp, xml);

                //Now rewrite the files at the original locations

                FileUtils.copyFile(temp, extractDirectory);

            }

        }

        response.displayLog("Extraction Done !");
        System.out.println(" DONE ! ");
        zipInputStream.close();

    } catch (Exception e) {
        System.out.println(e.toString());
        response.displayError(e.toString());
    }
}

From source file:io.gromit.geolite2.geonames.SubdivisionFinder.java

/**
 * Read countries./*from w  w  w  . ja  va 2s.c o m*/
 *
 * @param subdivisionOneLocationUrl the subdivision one location url
 * @return the time zone finder
 */
public SubdivisionFinder readLevelOne(String subdivisionOneLocationUrl) {
    ZipInputStream zipis = null;
    try {
        zipis = new ZipInputStream(new URL(subdivisionOneLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc1 == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }
        CsvParserSettings settings = new CsvParserSettings();
        settings.setSkipEmptyLines(true);
        settings.trimValues(true);
        CsvFormat format = new CsvFormat();
        format.setDelimiter('\t');
        format.setLineSeparator("\n");
        format.setCharToEscapeQuoteEscaping('\0');
        format.setQuote('\0');
        settings.setFormat(format);
        CsvParser parser = new CsvParser(settings);

        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));

        for (String[] entry : lines) {
            Subdivision subdivision = new Subdivision();
            subdivision.setId(entry[0]);
            subdivision.setName(entry[1]);
            subdivision.setGeonameId(NumberUtils.toInt(entry[2]));
            idOneMap.put(subdivision.getId(), subdivision);
            geonameIdMap.put(subdivision.getGeonameId(), subdivision);
        }
        logger.info("loaded " + lines.size() + " subdivisions level 1");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}

From source file:io.gromit.geolite2.geonames.SubdivisionFinder.java

/**
 * Read level two.//from w ww. j a va  2 s. c  om
 *
 * @param subdivisionTwoLocationUrl the subdivision two location url
 * @return the subdivision finder
 */
public SubdivisionFinder readLevelTwo(String subdivisionTwoLocationUrl) {
    ZipInputStream zipis = null;
    try {
        zipis = new ZipInputStream(new URL(subdivisionTwoLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc2 == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }
        CsvParserSettings settings = new CsvParserSettings();
        settings.setSkipEmptyLines(true);
        settings.trimValues(true);
        CsvFormat format = new CsvFormat();
        format.setDelimiter('\t');
        format.setLineSeparator("\n");
        format.setCharToEscapeQuoteEscaping('\0');
        format.setQuote('\0');
        settings.setFormat(format);
        CsvParser parser = new CsvParser(settings);

        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));

        for (String[] entry : lines) {
            Subdivision subdivision = new Subdivision();
            subdivision.setId(entry[0]);
            subdivision.setName(entry[1]);
            subdivision.setGeonameId(NumberUtils.toInt(entry[2]));
            idTowMap.put(subdivision.getId(), subdivision);
            geonameIdMap.put(subdivision.getGeonameId(), subdivision);
        }
        logger.info("loaded " + lines.size() + " subdivisions level 2");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}