Example usage for java.util.zip ZipInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.apache.tika.parser.odf.OpenDocumentParser.java

public void parse(InputStream stream, ContentHandler baseHandler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    // Open the Zip stream
    // Use a File if we can, and an already open zip is even better
    ZipFile zipFile = null;/*from ww w  . ja va 2  s. c o  m*/
    ZipInputStream zipStream = null;
    if (stream instanceof TikaInputStream) {
        TikaInputStream tis = (TikaInputStream) stream;
        Object container = ((TikaInputStream) stream).getOpenContainer();
        if (container instanceof ZipFile) {
            zipFile = (ZipFile) container;
        } else if (tis.hasFile()) {
            zipFile = new ZipFile(tis.getFile());
        } else {
            zipStream = new ZipInputStream(stream);
        }
    } else {
        zipStream = new ZipInputStream(stream);
    }

    // Prepare to handle the content
    XHTMLContentHandler xhtml = new XHTMLContentHandler(baseHandler, metadata);

    // As we don't know which of the metadata or the content
    //  we'll hit first, catch the endDocument call initially
    EndDocumentShieldingContentHandler handler = new EndDocumentShieldingContentHandler(xhtml);

    if (zipFile != null) {
        try {
            handleZipFile(zipFile, metadata, context, handler);
        } finally {
            //Do we want to close silently == catch an exception here?
            zipFile.close();
        }
    } else {
        try {
            handleZipStream(zipStream, metadata, context, handler);
        } finally {
            //Do we want to close silently == catch an exception here?
            zipStream.close();
        }
    }

    // Only now call the end document
    if (handler.getEndDocumentWasCalled()) {
        handler.reallyEndDocument();
    }
}

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//  w w w.  ja  v  a  2  s  .c o  m
 * @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.bimserver.ifc.step.deserializer.IfcStepDeserializer.java

public IfcModelInterface read(InputStream in, String filename, long fileSize) throws DeserializeException {
    mode = Mode.HEADER;//  w w w .  j  a  va 2 s  .c  om
    if (filename != null
            && (filename.toUpperCase().endsWith(".ZIP") || filename.toUpperCase().endsWith(".IFCZIP"))) {
        ZipInputStream zipInputStream = new ZipInputStream(in);
        ZipEntry nextEntry;
        try {
            nextEntry = zipInputStream.getNextEntry();
            if (nextEntry == null) {
                throw new DeserializeException(
                        "Zip files must contain exactly one IFC-file, this zip-file looks empty");
            }
            if (nextEntry.getName().toUpperCase().endsWith(".IFC")) {
                IfcModelInterface model = null;
                FakeClosingInputStream fakeClosingInputStream = new FakeClosingInputStream(zipInputStream);
                model = read(fakeClosingInputStream, fileSize);
                if (model.size() == 0) {
                    throw new DeserializeException("Uploaded file does not seem to be a correct IFC file");
                }
                if (zipInputStream.getNextEntry() != null) {
                    zipInputStream.close();
                    throw new DeserializeException(
                            "Zip files may only contain one IFC-file, this zip-file contains more files");
                } else {
                    zipInputStream.close();
                    return model;
                }
            } else {
                throw new DeserializeException(
                        "Zip files must contain exactly one IFC-file, this zip-file seems to have one or more non-IFC files");
            }
        } catch (IOException e) {
            throw new DeserializeException(e);
        }
    } else {
        return read(in, fileSize);
    }
}

From source file:org.gofleet.context.GoClassLoader.java

private void findFileInPath(ArrayList<String> res, String cadena, final java.lang.String path) {
    try {//from   w w w  .  j a  va  2 s. com
        LOG.trace("findFileInPath(" + path + ")");
        final java.io.File object = new java.io.File(path);

        if (object.isDirectory()) {
            LOG.trace("Directory found: " + object.getAbsolutePath());
            for (java.lang.String entry : object.list()) {
                final java.io.File thing = new java.io.File(
                        object.getCanonicalPath() + System.getProperty("file.separator") + entry);
                if (thing.isFile() && thing.getName().contains(cadena))
                    res.add(object.getCanonicalPath());
                else
                    findFileInPath(res, cadena, thing.getCanonicalPath());
            }
        } else if (object.isFile() && object.getName().contains(cadena)) {
            LOG.debug("File found: " + object.getAbsolutePath());
            res.add(object.getCanonicalPath());
        } else if (object.isFile() && object.getName().endsWith(".jar")) {
            LOG.debug("Jar found: " + object.getAbsolutePath());
            FileInputStream fis = new FileInputStream(object);
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
            ZipEntry zipEntry;
            while ((zipEntry = zis.getNextEntry()) != null) {
                if (zipEntry.getName().contains(cadena)) {

                    JarFile jarFile = new JarFile(object);

                    JarEntry entry = jarFile.getJarEntry(zipEntry.getName());

                    InputStream inputStream = jarFile.getInputStream(entry);

                    System.out.println(object.getAbsolutePath() + "/" + zipEntry.getName());

                    File f = File.createTempFile(zipEntry.getName(), "");
                    f.deleteOnExit();
                    OutputStream out = new FileOutputStream(f);
                    byte buf[] = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0)
                        out.write(buf, 0, len);
                    out.close();
                    inputStream.close();

                    LOG.debug("File found: " + zipEntry.getName());
                    res.add(f.getCanonicalPath());
                }
            }
            zis.close();
            fis.close();
        }
    } catch (Throwable t) {
        LOG.error(t, t);
    }
}

From source file:com.joliciel.csvLearner.CSVLearner.java

private void doCommandNormalise() throws IOException {
    if (featureDir == null)
        throw new RuntimeException("Missing argument: featureDir");
    if (outDirPath == null)
        throw new RuntimeException("Missing argument: outDir");
    LOG.info("Generating event list from CSV files...");
    new File(outDirPath).mkdirs();

    CSVEventListReader reader = this.getReader(TrainingSetType.TEST_SEGMENT, true);

    Map<String, Float> normalisationLimits = null;
    boolean havePreviousLimits = false;
    if (this.maxentModelFilePath != null) {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(maxentModelFilePath));
        ZipEntry ze;/*from  w w w.ja  va 2 s.com*/
        boolean foundNormLimits = false;
        while ((ze = zis.getNextEntry()) != null) {
            if (ze.getName().endsWith(".nrm_limits.csv")) {
                foundNormLimits = true;
                break;
            }
        }
        if (foundNormLimits) {
            NormalisationLimitReader normalisationLimitReader = new NormalisationLimitReader(zis);
            normalisationLimits = normalisationLimitReader.read();
            havePreviousLimits = true;
        }
        zis.close();
    }

    Map<String, GenericEvents> eventToFileMap = reader.getEventsPerFile();

    // normalising & write to directory
    for (Entry<String, GenericEvents> fileEvents : eventToFileMap.entrySet()) {
        String filename = fileEvents.getKey();
        LOG.debug("Normalizing file: " + filename);
        GenericEvents events = fileEvents.getValue();

        RealValueFeatureNormaliser normaliser = null;
        if (havePreviousLimits)
            normaliser = new RealValueFeatureNormaliser(normalisationLimits, events);
        else
            normaliser = new RealValueFeatureNormaliser(reader, events);
        normaliser.setNormaliseMethod(normaliseMethod);
        normaliser.normalise();
        if (!havePreviousLimits)
            normalisationLimits = normaliser.getFeatureToMaxMap();

        String prefix = null;
        if (reader.getGroupedFiles().contains(filename))
            prefix = "ng_";
        else
            prefix = "n_";

        if (normaliseMethod.equals(NormaliseMethod.NORMALISE_BY_MEAN))
            prefix += "mean_";

        File file = new File(outDirPath + "/" + prefix + filename);
        CSVEventListWriter eventListWriter = new CSVEventListWriter(file);
        if (filename.endsWith(".zip"))
            eventListWriter.setFilePerEvent(zipEntryPerEvent);
        if (missingValueString != null)
            eventListWriter.setMissingValueString(missingValueString);
        if (identifierPrefix != null)
            eventListWriter.setIdentifierPrefix(identifierPrefix);
        eventListWriter.setIncludeOutcomes(includeOutcomes);
        eventListWriter.setDenominalise(denominalise);
        eventListWriter.writeFile(events);

        if (!havePreviousLimits) {
            File normalisationLimitFile = new File(outDirPath + "/" + prefix + filename + ".nrm_limits.csv");
            NormalisationLimitWriter limitWriter = new NormalisationLimitWriter(normalisationLimitFile);
            limitWriter.writeFile(normalisationLimits);
        }

    }
}

From source file:org.saiku.plugin.resources.PentahoRepositoryResource2.java

@POST
@Path("/zipupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadArchiveZip(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("directory") String directory) {
    String zipFile = fileDetail.getFileName();
    String output = "";
    try {// w  ww.  j a va 2 s.co m
        if (StringUtils.isBlank(zipFile))
            throw new Exception("You must specify a zip file to upload");

        output = "Uploding file: " + zipFile + " ...\r\n";
        ZipInputStream zis = new ZipInputStream(uploadedInputStream);
        ZipEntry ze = zis.getNextEntry();
        byte[] doc = null;
        boolean isFile = false;
        if (ze == null) {
            doc = IOUtils.toByteArray(uploadedInputStream);
            isFile = true;
        }
        while (ze != null || doc != null) {
            String fileName = null;
            if (!isFile) {
                fileName = ze.getName();
                doc = IOUtils.toByteArray(zis);
            } else {
                fileName = zipFile;
            }

            output += "Saving " + fileName + "... ";
            String fullPath = (StringUtils.isNotBlank(directory)) ? directory + "/" + fileName : fileName;

            String content = new String(doc);
            Response r = saveResource(fullPath, content);
            doc = null;

            if (Status.OK.getStatusCode() != r.getStatus()) {
                output += " ERROR: " + r.getEntity().toString() + "\r\n";
            } else {
                output += " OK\r\n";
            }
            if (!isFile)
                ze = zis.getNextEntry();
        }

        if (!isFile) {
            zis.closeEntry();
            zis.close();
        }
        uploadedInputStream.close();

        output += " SUCCESSFUL!\r\n";
        return Response.ok(output).build();

    } catch (Exception e) {
        log.error("Cannot unzip resources " + zipFile, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(output + "\r\n" + error).build();
    }
}

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   ww  w  .  jav  a  2  s .  c  o m*/
    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:com.pontecultural.flashcards.ReadSpreadsheet.java

public void run() {
    try {// ww w. j  a  v a 2  s.c  o  m
        // This class is used to upload a zip file via 
        // the web (ie,fileData). To test it, the file is 
        // give to it directly via odsFile. One of 
        // which must be defined. 
        assertFalse(odsFile == null && fileData == null);
        XMLReader reader = null;
        final String ZIP_CONTENT = "content.xml";
        // Open office files are zipped. 
        // Walk through it and find "content.xml"

        ZipInputStream zin = null;
        try {
            if (fileData != null) {
                zin = new ZipInputStream(new BufferedInputStream(fileData.getInputStream()));
            } else {
                zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(odsFile)));
            }

            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                if (entry.getName().equals(ZIP_CONTENT)) {
                    break;
                }
            }
            SAXParserFactory spf = SAXParserFactory.newInstance();
            //spf.setValidating(validate);

            SAXParser parser = spf.newSAXParser();
            reader = parser.getXMLReader();

            // reader.setErrorHandler(new MyErrorHandler());
            reader.setContentHandler(this);
            // reader.parse(new InputSource(zf.getInputStream(entry)));

            reader.parse(new InputSource(zin));

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (SAXParseException spe) {
            spe.printStackTrace();
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zin != null)
                zin.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:aurelienribon.gdxsetupui.ProjectSetup.java

/**
 * Selected libraries are inflated from their zip files, and put in the
 * libs folders of the projects./*from ww  w.java  2 s  . co m*/
 * @throws IOException
 */
public void inflateLibraries() throws IOException {
    File commonPrjLibsDir = new File(tmpDst, "/prj-common/libs");
    File desktopPrjLibsDir = new File(tmpDst, "/prj-desktop/libs");
    File androidPrjLibsDir = new File(tmpDst, "/prj-android/libs");
    File htmlPrjLibsDir = new File(tmpDst, "/prj-html/war/WEB-INF/lib");
    File iosPrjLibsDir = new File(tmpDst, "/prj-ios/libs");
    File dataDir = new File(tmpDst, "/prj-android/assets");

    for (String library : cfg.libraries) {
        InputStream is = new FileInputStream(cfg.librariesZipPaths.get(library));
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry;

        LibraryDef def = libs.getDef(library);

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

            for (String elemName : def.libsCommon)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, commonPrjLibsDir);
            for (String elemName : def.libsDesktop)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, desktopPrjLibsDir);
            for (String elemName : def.libsAndroid)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, androidPrjLibsDir);
            for (String elemName : def.libsHtml)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, htmlPrjLibsDir);
            for (String elemName : def.libsIos)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, iosPrjLibsDir);
            for (String elemName : def.data)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, dataDir);
        }

        zis.close();
    }
}

From source file:com.twinsoft.convertigo.engine.util.ZipUtils.java

public static void expandZip(String zipFileName, String rootDir, String prefixDir)
        throws FileNotFoundException, IOException {
    Engine.logEngine.debug("Expanding the zip file " + zipFileName);

    // Creating the root directory
    File ftmp = new File(rootDir);
    if (!ftmp.exists()) {
        ftmp.mkdirs();//from  ww w.  j a v a  2s.  com
        Engine.logEngine.debug("Root directory created");
    }

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFileName)));

    try {
        ZipEntry entry;
        int prefixSize = prefixDir != null ? prefixDir.length() : 0;

        while ((entry = zis.getNextEntry()) != null) {
            // Ignoring directories
            if (entry.isDirectory()) {

            } else {

                String entryName = entry.getName();
                Engine.logEngine.debug("+ Analyzing the entry: " + entryName);

                try {
                    // Ignore entry if does not belong to the project directory
                    if ((prefixDir == null) || entryName.startsWith(prefixDir)) {

                        // Ignore entry from _data or _private directory
                        if ((entryName.indexOf("/_data/") != prefixSize)
                                && (entryName.indexOf("/_private/") != prefixSize)) {
                            Engine.logEngine.debug("  The entry is accepted");
                            String s1 = rootDir + "/" + entryName;
                            String dir = s1.substring(0, s1.lastIndexOf('/'));

                            // Creating the directory if needed
                            ftmp = new File(dir);
                            if (!ftmp.exists()) {
                                ftmp.mkdirs();
                                Engine.logEngine.debug("  Directory created");
                            }

                            // Writing the files to the disk
                            File file = new File(rootDir + "/" + entryName);
                            FileOutputStream fos = new FileOutputStream(file);
                            try {
                                IOUtils.copy(zis, fos);
                            } finally {
                                fos.close();
                            }
                            file.setLastModified(entry.getTime());
                            Engine.logEngine.debug("  File written to: " + rootDir + "/" + entryName);
                        }
                    }
                } catch (IOException e) {
                    Engine.logEngine.error(
                            "Unable to expand the ZIP entry \"" + entryName + "\": " + e.getMessage(), e);
                }
            }
        }
    } finally {
        zis.close();
    }
}