Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:org.geoserver.kml.KMLReflectorTest.java

@Test
public void testForceRasterKmz() throws Exception {
    final String requestUrl = "wms/kml?layers=" + getLayerId(MockData.BASIC_POLYGONS)
            + "&styles=&mode=download&KMSCORE=0&format=" + KMZMapOutputFormat.MIME_TYPE;
    MockHttpServletResponse response = getAsServletResponse(requestUrl);
    assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType());
    assertEquals("attachment; filename=cite-BasicPolygons.kmz", response.getHeader("Content-Disposition"));

    ZipInputStream zis = new ZipInputStream(getBinaryInputStream(response));
    try {/*from   ww w  .  j a  v  a  2  s.co  m*/
        // first entry, the kml document itself
        ZipEntry entry = zis.getNextEntry();
        assertEquals("wms.kml", entry.getName());
        // we need to clone the input stream, as dom(is) closes the stream
        byte[] data = IOUtils.toByteArray(zis);
        Document dom = dom(new ByteArrayInputStream(data));
        assertXpathEvaluatesTo("1", "count(//kml:Folder/kml:GroundOverlay)", dom);
        String href = XMLUnit.newXpathEngine().evaluate("//kml:Folder/kml:GroundOverlay/kml:Icon/kml:href",
                dom);
        assertEquals("images/layers_0.png", href);
        zis.closeEntry();

        // the images folder
        entry = zis.getNextEntry();
        assertEquals("images/", entry.getName());
        zis.closeEntry();

        // the ground overlay for the raster layer
        entry = zis.getNextEntry();
        assertEquals("images/layers_0.png", entry.getName());
        zis.closeEntry();
        assertNull(zis.getNextEntry());
    } finally {
        zis.close();
    }
}

From source file:org.kootox.episodesmanager.services.databases.TheTvDbService.java

protected void extractZip(File source, File destinationDirectory) {
    ZipInputStream zipIS = null;
    FileOutputStream out = null;//from   w  ww.  j a  va2 s  . c o m
    try {
        byte[] buf = new byte[1024];
        ZipEntry zipEntry;
        zipIS = new ZipInputStream(new FileInputStream(source));

        zipEntry = zipIS.getNextEntry();
        while (zipEntry != null) {
            //for each entry to be extracted
            String entryName = zipEntry.getName();
            if (log.isDebugEnabled()) {
                log.debug("Extracting : " + entryName);
            }
            int n;
            File newFile = new File(destinationDirectory, entryName);

            out = new FileOutputStream(newFile);

            while ((n = zipIS.read(buf, 0, 1024)) > -1)
                out.write(buf, 0, n);

            out.close();
            zipIS.closeEntry();
            zipEntry = zipIS.getNextEntry();

        } //while

    } catch (Exception eee) {
        log.error("Could not extract zip file", eee);
    } finally {
        try {
            if (zipIS != null) {
                zipIS.close();
            }
        } catch (IOException eee) {
            log.debug("Could not close zip file", eee);
        }

        try {
            if (null != out) {
                out.close();
            }
        } catch (IOException eee) {
            log.debug("Could not close extracted file", eee);
        }
    }
}

From source file:org.wso2.carbon.integration.framework.utils.ArchiveManipulatorUtil.java

public void extractFile(String sourceFilePath, String extractedDir) throws IOException {
    FileOutputStream fileoutputstream = null;

    String fileDestination = extractedDir + File.separator;
    byte[] buf = new byte[1024];
    ZipInputStream zipinputstream = null;
    ZipEntry zipentry;// w w  w . j a v a2s .  co  m
    try {
        zipinputstream = new ZipInputStream(new FileInputStream(sourceFilePath));

        zipentry = zipinputstream.getNextEntry();

        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = fileDestination + zipentry.getName();
            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);
            int n;

            File newFile = new File(entryName);

            if (zipentry.isDirectory()) {
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            } else {
                File resourceFile = new File(entryName.substring(0, entryName.lastIndexOf(File.separator)));
                if (!resourceFile.exists()) {
                    if (!resourceFile.mkdirs()) {
                        break;
                    }

                }
            }

            fileoutputstream = new FileOutputStream(entryName);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }

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

        }
        zipinputstream.close();
    } catch (IOException e) {
        log.error("Error on archive extraction ", e);
        throw new IOException("Error on archive extraction ", e);

    } finally {
        if (fileoutputstream != null) {
            fileoutputstream.close();
        }
        if (zipinputstream != null) {
            zipinputstream.close();
        }
    }
}

From source file:com.adobe.communities.ugc.migration.importer.GenericUGCImporter.java

protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    UGCImportHelper.checkUserPrivileges(request.getResourceResolver(), rrf);

    ResourceResolver resolver;/*from   w  w  w. jav  a 2 s.com*/
    try {
        resolver = serviceUserWrapper.getServiceResourceResolver(rrf,
                Collections.<String, Object>singletonMap(ResourceResolverFactory.SUBSERVICE, UGC_WRITER));
    } catch (final LoginException e) {
        throw new ServletException("Not able to invoke service user");
    }

    // finally get the uploaded file
    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()) {

        if (fileRequestParameters[0].getFileName().endsWith(".json")) {
            // if upload is a single json file...

            // get the resource we'll be adding new content to
            final String path = request.getRequestParameter("path").getString();
            final Resource resource = resolver.getResource(path);
            if (resource == null) {
                resolver.close();
                throw new ServletException("Could not find a valid resource for import");
            }
            final InputStream inputStream = fileRequestParameters[0].getInputStream();
            final JsonParser jsonParser = new JsonFactory().createParser(inputStream);
            jsonParser.nextToken(); // get the first token

            importFile(jsonParser, resource, resolver);
        } else if (fileRequestParameters[0].getFileName().endsWith(".zip")) {
            ZipInputStream zipInputStream;
            try {
                zipInputStream = new ZipInputStream(fileRequestParameters[0].getInputStream());
            } catch (IOException e) {
                resolver.close();
                throw new ServletException("Could not open zip archive");
            }

            try {
                final RequestParameter[] paths = request.getRequestParameters("path");
                int counter = 0;
                ZipEntry zipEntry = zipInputStream.getNextEntry();
                while (zipEntry != null && paths.length > counter) {
                    final String path = paths[counter].getString();
                    final Resource resource = resolver.getResource(path);
                    if (resource == null) {
                        resolver.close();
                        throw new ServletException("Could not find a valid resource for import");
                    }

                    final JsonParser jsonParser = new JsonFactory().createParser(zipInputStream);
                    jsonParser.nextToken(); // get the first token
                    importFile(jsonParser, resource, resolver);
                    zipInputStream.closeEntry();
                    zipEntry = zipInputStream.getNextEntry();
                    counter++;
                }
            } finally {
                zipInputStream.close();
            }
        } else {
            resolver.close();
            throw new ServletException("Unrecognized file input type");
        }
    } else {
        resolver.close();
        throw new ServletException("No file provided for UGC data");
    }
    resolver.close();
}

From source file:org.wso2.carbon.automation.extensions.servers.utils.ArchiveExtractor.java

public void extractFile(String sourceFilePath, String extractedDir) throws IOException {
    FileOutputStream fileoutputstream = null;

    String fileDestination = extractedDir + File.separator;
    byte[] buf = new byte[1024];
    ZipInputStream zipinputstream = null;
    ZipEntry zipentry;//from   ww  w .j a v a  2  s  . c  o  m
    try {
        zipinputstream = new ZipInputStream(new FileInputStream(sourceFilePath));

        zipentry = zipinputstream.getNextEntry();

        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = fileDestination + zipentry.getName();
            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);
            int n;

            File newFile = new File(entryName);
            boolean fileCreated = false;
            if (zipentry.isDirectory()) {
                if (!newFile.exists()) {
                    fileCreated = newFile.mkdirs();
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            } else {
                File resourceFile = new File(entryName.substring(0, entryName.lastIndexOf(File.separator)));
                if (!resourceFile.exists()) {
                    if (!resourceFile.mkdirs()) {
                        break;
                    }
                }
            }

            fileoutputstream = new FileOutputStream(entryName);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }

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

        }
        zipinputstream.close();
    } catch (IOException e) {
        log.error("Error on archive extraction ", e);
        throw new IOException("Error on archive extraction ", e);

    } finally {
        if (fileoutputstream != null) {
            fileoutputstream.close();
        }
        if (zipinputstream != null) {
            zipinputstream.close();
        }
    }
}

From source file:isl.FIMS.utils.Utils.java

/**
 * Unzip it (This implementation works only when zip contains files-folders
 * with ASCII filenames Greek characters break the code!
 *
 * @param zipFile input zip file/*from   w w  w.  ja  v  a 2 s.  com*/
 * @param output zip file output folder
 */
public static void unzip(String zipFile, String outputFolder) {

    String rootFolderName = "";
    String rootFlashFilename = "";
    byte[] buffer = new byte[1024];

    try {

        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(outputFolder + File.separator + zipFile));
        //get the zipped file list entry

        ZipEntry ze = zis.getNextEntry();

        boolean rootDirFound = false;
        boolean flashFileFound = false;
        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            if (!ze.getName().contains("__MACOSX")) {
                if (ze.isDirectory()) {
                    if (rootDirFound == false) {
                        rootFolderName = newFile.getName();
                        rootDirFound = true;
                    }
                    new File(newFile.getParent()).mkdirs();
                } else {
                    FileOutputStream fos = null;

                    new File(newFile.getParent()).mkdirs();

                    if (flashFileFound == false && newFile.getName().endsWith(".swf")
                            && !newFile.getName().startsWith(".")) {
                        rootFlashFilename = newFile.getName();
                        flashFileFound = true;
                    }

                    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();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.jahia.services.importexport.ExternalUsersImportUpdater.java

public File updateImport(File importFile, String fileName, String fileType) {
    Map<String, String> pathMapping = new HashMap<String, String>();
    File newImportFile = null;/*  w ww .  j  av a  2 s .c  om*/
    ZipInputStream zin = null;
    OutputStream out = null;
    ZipOutputStream zout = null;
    boolean updated = false;
    try {
        newImportFile = File.createTempFile("import", ".zip");
        zin = importFile.isDirectory() ? new DirectoryZipInputStream(importFile)
                : new NoCloseZipInputStream(new BufferedInputStream(new FileInputStream(importFile)));
        out = new FileOutputStream(newImportFile);
        zout = new ZipOutputStream(out);

        while (true) {
            ZipEntry zipentry = zin.getNextEntry();
            if (zipentry == null)
                break;
            String name = zipentry.getName();

            if (LIVE_REPOSITORY_XML.equals(name) || REPOSITORY_XML.equals(name)) {
                zout.putNextEntry(new ZipEntry(name));
                if ("users.zip".equalsIgnoreCase(fileName)) {
                    updated |= transform(zin, zout, pathMapping);
                } else {
                    updated |= clean(zin, zout, pathMapping);
                }
            }

        }
        if (!updated) {
            FileUtils.deleteQuietly(newImportFile);
            return importFile;
        }

        zin.closeEntry();
        if (zin instanceof NoCloseZipInputStream) {
            ((NoCloseZipInputStream) zin).reallyClose();
        }
        zin = importFile.isDirectory() ? new DirectoryZipInputStream(importFile)
                : new NoCloseZipInputStream(new BufferedInputStream(new FileInputStream(importFile)));
        while (true) {
            ZipEntry zipentry = zin.getNextEntry();
            if (zipentry == null)
                break;
            String name = zipentry.getName();

            if (!LIVE_REPOSITORY_XML.equals(name) && !REPOSITORY_XML.equals(name)) {
                if (name.startsWith(LIVE_CONTENT + "/")) {
                    for (String key : pathMapping.keySet()) {
                        if (StringUtils.startsWith(name, LIVE_CONTENT + key)) {
                            name = StringUtils.replace(name, LIVE_CONTENT + key,
                                    LIVE_CONTENT + pathMapping.get(key));
                            break;
                        }
                    }
                } else if (name.startsWith(CONTENT + "/")) {
                    for (String key : pathMapping.keySet()) {
                        if (StringUtils.startsWith(name, CONTENT + key)) {
                            name = StringUtils.replace(name, CONTENT + key, CONTENT + pathMapping.get(key));
                            break;
                        }
                    }
                }
                File content = File.createTempFile("content", null);
                IOUtils.copy(zin, new FileOutputStream(content));
                zout.putNextEntry(new ZipEntry(name));
                IOUtils.copy(new FileInputStream(content), zout);
            }

        }
        JCRSessionFactory.getInstance().getCurrentUserSession().getPathMapping().putAll(pathMapping);
        return newImportFile;
    } catch (IOException | RepositoryException | ParserConfigurationException | XPathExpressionException
            | SAXException | TransformerException e) {
        logger.error("An error occurred while updating import file", e);
    } finally {
        try {
            if (zout != null) {
                zout.closeEntry();
                zout.finish();
            }
            if (out != null) {
                out.close();
            }
            if (zin != null) {
                zin.closeEntry();
                if (zin instanceof NoCloseZipInputStream) {
                    ((NoCloseZipInputStream) zin).reallyClose();
                }
            }
        } catch (IOException e) {
            logger.debug("Stream already closed", e);
        }
    }

    FileUtils.deleteQuietly(newImportFile);
    return importFile;
}

From source file:org.candlepin.sync.ExporterTest.java

private void verifyContent(File export, String name, Verify v) {
    ZipInputStream zis = null;

    try {//from  w w  w .  j a  v  a2 s  .  com
        zis = new ZipInputStream(new FileInputStream(export));
        ZipEntry entry = null;
        while ((entry = zis.getNextEntry()) != null) {
            byte[] buf = new byte[1024];

            if (entry.getName().equals("consumer_export.zip")) {
                OutputStream os = new FileOutputStream("/tmp/consumer_export.zip");

                int n;
                while ((n = zis.read(buf, 0, 1024)) > -1) {
                    os.write(buf, 0, n);
                }
                os.flush();
                os.close();
                File exportdata = new File("/tmp/consumer_export.zip");
                // open up the zip and look for the metadata
                verifyContent(exportdata, name, v);
            } else if (entry.getName().equals(name)) {
                v.verify(zis, buf);
            }
            zis.closeEntry();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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

public void unzipFile(File zipFile, File destination, boolean unwrap) throws UnzipException {
    try {//from   w w  w  .  jav a2  s  . co m
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile));
        boolean done = false;
        while (!done) {
            ZipEntry nextEntry = in.getNextEntry();

            if (nextEntry == null)
                done = true;
            else {
                String name = nextEntry.getName();
                if (unwrap) {
                    name = name.substring(name.indexOf('/'));
                }
                File outputFile = new File(destination, name);
                log.info("   " + outputFile.getAbsolutePath());

                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs())
                    throw new UnzipException("Could not create directory " + outputFile.getParent());

                if (nextEntry.isDirectory()) {
                    if (!outputFile.exists() && !outputFile.mkdir())
                        throw new UnzipException("Ddirectory does not exist and could not be created:"
                                + outputFile.getAbsolutePath());
                } else {
                    if (!outputFile.createNewFile())
                        throw new UnzipException("Could not create file " + outputFile.getAbsolutePath());
                    FileOutputStream out = new FileOutputStream(outputFile);
                    copyStreams(in, out, 1024 * 100);
                    out.close();
                    in.closeEntry();
                }

            }
        }

    } catch (Exception e) {
        throw new UnzipException("There was an error executing the unzip of file " + zipFile.getAbsolutePath(),
                e);
    }

    //      String pathOfZipFile = zipFile.getAbsolutePath();
    //      
    //      String command = "unzip -o "  + pathOfZipFile + " -d " + destination.getAbsolutePath() ;
    //      
    //      try {
    //         log.info("Running " + command);
    //         
    //         int result = new CommandRunner().runCommand(command);
    //         if(result!=0) throw new UnzipException("Unzip command exited with status " + result);
    //         log.info("Unzip complete");
    //      } catch (CommandException e) {
    //         throw new UnzipException("There was an error executing the unzip command: \"" + command + "\"", e);
    //      }
}

From source file:org.geoserver.wps.gs.download.DownloadProcessTest.java

/**
 * This method is used for decoding an input file.
 * /*from   w w w  . j  a va2  s . c  om*/
 * @param input the input stream to decode
 * @param tempDirectory temporary directory on where the file is decoded.
 * @return the object the decoded file
 * @throws Exception the exception TODO review
 */
public static File decode(InputStream input, File tempDirectory) throws Exception {

    // unzip to the temporary directory
    ZipInputStream zis = null;
    try {
        zis = new ZipInputStream(input);
        ZipEntry entry = null;

        // Copy the whole file in the new position
        while ((entry = zis.getNextEntry()) != null) {
            File file = new File(tempDirectory, entry.getName());
            if (entry.isDirectory()) {
                file.mkdir();
            } else {
                int count;
                byte data[] = new byte[4096];
                // write the files to the disk
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                    while ((count = zis.read(data)) != -1) {
                        fos.write(data, 0, count);
                    }
                    fos.flush();
                } finally {
                    if (fos != null) {
                        org.apache.commons.io.IOUtils.closeQuietly(fos);
                    }
                }
            }
            zis.closeEntry();
        }
    } finally {
        if (zis != null) {
            org.apache.commons.io.IOUtils.closeQuietly(zis);
        }
    }

    return tempDirectory;
}