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:io.gromit.geolite2.geonames.CityFinder.java

/**
 * Read cities./* w w  w .ja va2 s  .c  o m*/
 *
 * @param citiesLocationUrl the cities location url
 * @return the city finder
 */
private CityFinder readCities(String citiesLocationUrl) {
    ZipInputStream zipis = null;
    CsvParserSettings settings = new CsvParserSettings();
    settings.setSkipEmptyLines(true);
    settings.trimValues(true);
    CsvFormat format = new CsvFormat();
    format.setDelimiter('\t');
    format.setLineSeparator("\n");
    format.setComment('\0');
    format.setCharToEscapeQuoteEscaping('\0');
    format.setQuote('\0');
    settings.setFormat(format);
    CsvParser parser = new CsvParser(settings);
    try {
        zipis = new ZipInputStream(new URL(citiesLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }
        RTree<City, Geometry> rtreeRead = RTree.create();
        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));
        for (String[] entry : lines) {
            City city = new City();
            city.setGeonameId(Integer.decode(entry[0]));
            city.setName(entry[1]);
            try {
                try {
                    city.setLatitude(Double.valueOf(entry[2]));
                    city.setLongitude(Double.valueOf(entry[3]));
                    rtreeRead = rtreeRead.add(city,
                            Geometries.pointGeographic(city.getLongitude(), city.getLatitude()));
                } catch (NumberFormatException | NullPointerException e) {
                }
                city.setCountryIsoCode(entry[4]);
                city.setSubdivisionOne(entry[5]);
                city.setSubdivisionTwo(entry[6]);
                city.setTimeZone(entry[7]);
            } catch (ArrayIndexOutOfBoundsException e) {
            }
            geonameMap.put(city.getGeonameId(), city);
        }
        this.rtree = rtreeRead;
        logger.info("loaded " + geonameMap.size() + " cities");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .touchosc file
 * /* w ww  . ja  v  a2s.co m*/
 * @param zipTouchoscFilePath a .touchosc file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML2(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        URL url = TouchOSCUtils.class.getClassLoader().getResource(".");

        FileInputStream touchoscFile = new FileInputStream(url.getPath() + "../samples/" + zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            }
            FileOutputStream os = new FileOutputStream(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:nl.knaw.dans.common.lang.file.UnzipUtil.java

private static List<File> extract(final ZipInputStream zipInputStream, String destPath,
        final int initialCapacityForFiles, final UnzipListener unzipListener, final long totSize)
        throws FileNotFoundException, IOException {
    if (unzipListener != null)
        unzipListener.onUnzipStarted(totSize);

    final File destPathFile = new File(destPath);
    if (!destPathFile.exists())
        throw new FileNotFoundException(destPath);
    if (!destPathFile.isDirectory())
        throw new IOException("Expected directory, got file.");
    if (!destPath.endsWith(File.separator))
        destPath += File.separator;

    // now unzip//w  ww  .ja v a  2s  . co m
    BufferedOutputStream out = null;
    ZipEntry entry;
    int count;
    final byte data[] = new byte[BUFFER_SIZE];
    final ArrayList<File> files = new ArrayList<File>(initialCapacityForFiles);
    String entryname;
    String filename;
    String path;
    boolean cancel = false;
    final DefaultUnzipFilenameFilter filter = new DefaultUnzipFilenameFilter();

    try {
        long bytesWritten = 0;
        while (((entry = zipInputStream.getNextEntry()) != null) && !cancel) {
            entryname = entry.getName();
            final int fpos = entryname.lastIndexOf(File.separator);
            if (fpos >= 0) {
                path = entryname.substring(0, fpos);
                filename = entryname.substring(fpos + 1);
            } else {
                path = "";
                filename = new String(entryname);
            }

            if (!filter.accept(destPathFile, filename)) {
                // file filtered out
                continue;
            }

            if (entry.isDirectory()) {
                if (!createPath(destPath, entryname, files, filter))
                    // directory filtered out
                    continue;
            } else {
                if (!StringUtils.isBlank(path)) {
                    if (!createPath(destPath, path, files, filter))
                        // path filtered out
                        continue;
                }

                final String absFilename = destPath + entryname;
                final FileOutputStream fos = new FileOutputStream(absFilename);
                out = new BufferedOutputStream(fos, BUFFER_SIZE);
                try {
                    // inner loop
                    while ((count = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                        out.write(data, 0, count);
                        bytesWritten += count;

                        if (unzipListener != null)
                            cancel = !unzipListener.onUnzipUpdate(bytesWritten, totSize);
                        if (cancel)
                            break;
                    }
                    out.flush();
                } finally {
                    out.close();
                    files.add(new File(absFilename));
                }
            }
        }
    } finally {
        zipInputStream.close();

        // rollback?
        if (cancel) {
            // first remove files
            for (final File file : files) {
                if (!file.isDirectory())
                    file.delete();
            }
            // then folders
            for (final File file : files) {
                if (file.isDirectory())
                    file.delete();
            }
            files.clear();
        }
    }

    if (unzipListener != null)
        unzipListener.onUnzipComplete(files, cancel);

    return files;
}

From source file:eu.optimis.ics.ImageCreationServiceREST.java

/**
 * Uncompresses the given zip file. Unfortunately, the files' permission is not
 * preserved, especially with regards to an executable file.
 * @param zipFile       the zip file//from   www . j  av a2s. co m
 * @param destination   the directory location
 * @throws IOException  IO Exception
 */
private void unzipFile(File zipFile, String destination) throws IOException {
    LOGGER.debug("ics.REST.unzipFile(): Unzipping " + zipFile + " to directory " + destination);
    //LOGGER.debug("ics.REST.unzipFile(): Opening input streams");
    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    File destinationDirectory = new File(destination);

    while ((entry = zin.getNextEntry()) != null) {
        //LOGGER.debug("ics.REST.unzipFile(): Extracting: " + entry);

        if (entry.isDirectory()) {
            //LOGGER.debug("ics.REST.unzipFile(): Directory found, will be created");
            File targetDirectory = new File(destinationDirectory, entry.getName());
            targetDirectory.mkdir();
        } else {
            // extract data
            // open output streams
            int BUFFER = 2048;

            File destinationFile = new File(destinationDirectory, entry.getName());
            destinationFile.getParentFile().mkdirs();

            //LOGGER.debug("ics.REST.unzipFile(): Creating parent file of destination: "
            //        + destinationFile.getParent());
            //boolean parentDirectoriesCreated = destinationFile.getParentFile().mkdirs();                
            //LOGGER.debug("ics.REST.unzipFile(): Result of creating parents: "
            //        + parentDirectoriesCreated);

            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];

            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zin.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
    }

    LOGGER.debug("ics.REST.unzipFile(): Unzipping file is done");
    zin.close();
    fis.close();
}

From source file:de.ingrid.importer.udk.util.Zipper.java

/**
 * Extracts the given ZIP-File and return a vector containing String
 * representation of the extracted files.
 * /*w w  w  .j a  va2  s.c o  m*/
 * @param zipFileName
 *            the name of the ZIP-file
 * @param targetDir
 *            the target directory
 * @param keepSubfolders
 *            boolean parameter, whether to keep the folder structure
 * 
 * @return a Vector<String> containing String representation of the allowed
 *         files from the ZipperFilter.
 * @return null if the input data was invalid or an Exception occurs
 */
public static final List<String> extractZipFile(InputStream myInputStream, final String targetDir,
        final boolean keepSubfolders, ZipperFilter zipperFilter) {
    if (log.isDebugEnabled()) {
        log.debug("extractZipFile: inputStream=" + myInputStream + ", targetDir='" + targetDir
                + "', keepSubfolders=" + keepSubfolders);
    }

    ArrayList<String> extractedFiles = new ArrayList<String>();

    FileOutputStream fos = null;

    File outdir = new File(targetDir);

    // make some checks
    if (outdir.isFile()) {
        String msg = "The Target Directory \"" + outdir + "\" must not be a file .";
        log.error(msg);
        System.err.println(msg);
        return null;
    }

    // create necessary directories for the output directory
    outdir.mkdirs();

    // Start Unzipping ...
    try {
        if (log.isDebugEnabled()) {
            log.debug("Start unzipping");
        }

        ZipInputStream zis = new ZipInputStream(myInputStream);
        if (log.isDebugEnabled()) {
            log.debug("ZipInputStream from InputStream=" + zis);
        }

        // for every zip-entry
        ZipEntry zEntry;
        String name;
        while ((zEntry = zis.getNextEntry()) != null) {
            name = zEntry.toString();
            if (log.isDebugEnabled()) {
                log.debug("Zip Entry name: " + name + ", size:" + zEntry.getSize());
            }

            boolean isDir = name.endsWith(separator);
            // System.out.println("------------------------------");
            // System.out.println((isDir? "<d>":"< >")+name);

            String[] nameSplitted = name.split(separator);

            // If it's a File, take all Splitted Names except the last one
            int len = (isDir ? nameSplitted.length : nameSplitted.length - 1);

            String currStr = targetDir;

            if (keepSubfolders) {

                // create all directories from the entry
                for (int j = 0; j < len; j++) {
                    // System.out.println("Dirs: " + nameSplitted[j]);
                    currStr += nameSplitted[j] + File.separator;
                    // System.out.println("currStr: "+currStr);

                    File currDir = new File(currStr);
                    currDir.mkdirs();

                }
            }

            // if the entry is a file, then create it.
            if (!isDir) {

                // set the file name of the output file.
                String outputFileName = null;
                if (keepSubfolders) {
                    outputFileName = currStr + nameSplitted[nameSplitted.length - 1];
                } else {
                    outputFileName = targetDir + nameSplitted[nameSplitted.length - 1];
                }

                File outputFile = new File(outputFileName);
                fos = new FileOutputStream(outputFile);

                // write the File
                if (log.isDebugEnabled()) {
                    log.debug("Write Zip Entry '" + name + "' to file '" + outputFile + "'");
                }
                writeFile(zis, fos, buffersize);
                if (log.isDebugEnabled()) {
                    log.debug("FILE WRITTEN: " + outputFile.getAbsolutePath());
                }

                // add the file to the vector to be returned

                if (zipperFilter != null) {
                    String[] accFiles = zipperFilter.getAcceptedFiles();
                    String currFileName = outputFile.getAbsolutePath();

                    for (int i = 0; i < accFiles.length; i++) {
                        if (currFileName.endsWith(accFiles[i])) {
                            extractedFiles.add(currFileName);
                        }
                    }

                } else {
                    extractedFiles.add(outputFile.getAbsolutePath());
                }

            }

        } // end while

        zis.close();

    } catch (Exception e) {
        log.error("Problems unzipping file", e);
        e.printStackTrace();
        return null;
    }

    return extractedFiles;
}

From source file:com.joliciel.talismane.machineLearning.ModelFactory.java

public MachineLearningModel getMachineLearningModel(ZipInputStream zis) {
    try {/*from  ww  w  .ja  va 2 s  .com*/
        MachineLearningModel machineLearningModel = null;
        ZipEntry ze = zis.getNextEntry();
        if (!ze.getName().equals("algorithm.txt")) {
            throw new JolicielException("Expected algorithm.txt as first entry in zip. Was: " + ze.getName());
        }

        // note: assuming the model type will always be the first entry
        Scanner typeScanner = new Scanner(zis, "UTF-8");
        MachineLearningAlgorithm algorithm = MachineLearningAlgorithm.MaxEnt;
        if (typeScanner.hasNextLine()) {
            String algorithmString = typeScanner.nextLine();
            try {
                algorithm = MachineLearningAlgorithm.valueOf(algorithmString);
            } catch (IllegalArgumentException iae) {
                LogUtils.logError(LOG, iae);
                throw new JolicielException("Unknown algorithm: " + algorithmString);
            }
        } else {
            throw new JolicielException("Cannot find algorithm in zip file");
        }
        switch (algorithm) {
        case MaxEnt:
            machineLearningModel = maxentService.getMaxentModel();
            break;
        case LinearSVM:
            machineLearningModel = linearSVMService.getLinearSVMModel();
            break;
        case Perceptron:
            machineLearningModel = perceptronService.getPerceptronModel();
            break;
        case PerceptronRanking:
            machineLearningModel = perceptronService.getPerceptronRankingModel();
            break;
        case OpenNLPPerceptron:
            machineLearningModel = maxentService.getPerceptronModel();
            break;
        default:
            throw new JolicielException("Machine learning algorithm not yet supported: " + algorithm);
        }

        while ((ze = zis.getNextEntry()) != null) {
            LOG.debug(ze.getName());
            machineLearningModel.loadZipEntry(zis, ze);
        } // next zip entry

        machineLearningModel.onLoadComplete();

        return machineLearningModel;
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    } finally {
        try {
            zis.close();
        } catch (IOException ioe) {
            LogUtils.logError(LOG, ioe);
        }
    }
}

From source file:fr.vdl.android.holocolors.HoloColorsDialog.java

private void unzipFile(File zipFile) throws Exception {
    File outputFolder = new File(resPathTextField.getText());

    boolean overwriteAll = false;
    boolean overwriteNone = false;
    Object[] overwriteOptions = { "Overwrite this file", "Overwrite all", "Do not overwrite this file",
            "Do not overwrite any file" };

    ZipInputStream zis = null;
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    try {/*from  w w  w  .j  ava  2s.  co  m*/
        zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName().replaceFirst("res/", "");
            File newFile = new File(outputFolder + File.separator + fileName);

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

            boolean overwrite = overwriteAll || (!newFile.exists());
            if (newFile.exists() && newFile.isFile() && !overwriteAll && !overwriteNone) {
                int option = JOptionPane.showOptionDialog(ahcPanel,
                        newFile.getName() + " already exists, overwrite ?", "File exists",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                        new ImageIcon(getClass().getResource("/icons/H64.png")), overwriteOptions,
                        overwriteOptions[0]);

                switch (option) {
                case 0:
                    overwrite = true;
                    break;
                case 1:
                    overwrite = true;
                    overwriteAll = true;
                    break;
                case 2:
                    overwrite = false;
                    break;
                case 3:
                    overwrite = false;
                    overwriteNone = true;
                    break;
                default:
                    overwrite = false;
                }
            }

            if (overwrite && !fileName.endsWith(File.separator)) {
                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();
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.fao.geonet.kernel.SchemaManager.java

/**
  * unpack the schema supplied as a zip archive into the appropriate dir.
 *
 * @param dir the directory into which the zip archive will be unpacked
 * @param in the schema zip archive/*  ww  w .ja  v  a2  s. com*/
  * @throws Exception
 */
private void unpackSchemaZipArchive(File dir, InputStream in) throws Exception {

    // -- unpack the schema zip archive into it
    ZipInputStream zipStream = new ZipInputStream(in);

    ZipEntry entry = zipStream.getNextEntry();
    while (entry != null) {

        if (entry.isDirectory()) {
            if (Log.isDebugEnabled(Geonet.SCHEMA_MANAGER))
                Log.debug(Geonet.SCHEMA_MANAGER, "Creating directory " + entry.getName());
            (new File(dir, entry.getName())).mkdir();
        } else {
            if (Log.isDebugEnabled(Geonet.SCHEMA_MANAGER))
                Log.debug(Geonet.SCHEMA_MANAGER, "Creating file " + entry.getName());
            copyInputStream(zipStream,
                    new BufferedOutputStream(new FileOutputStream(new File(dir, entry.getName()))));
        }
        entry = zipStream.getNextEntry();
    }
    zipStream.close();
}

From source file:org.eclipse.kura.web.server.servlet.FileServlet.java

private void doPostCommand(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    UploadRequest upload = new UploadRequest(this.m_diskFileItemFactory);

    try {/*  w ww.j  av  a  2  s  . c  om*/
        upload.parse(req);
    } catch (FileUploadException e) {
        s_logger.error("Error parsing the file upload request");
        throw new ServletException("Error parsing the file upload request", e);
    }

    // BEGIN XSRF - Servlet dependent code
    Map<String, String> formFields = upload.getFormFields();

    try {
        GwtXSRFToken token = new GwtXSRFToken(formFields.get("xsrfToken"));
        KuraRemoteServiceServlet.checkXSRFToken(req, token);
    } catch (Exception e) {
        throw new ServletException("Security error: please retry this operation correctly.", e);
    }
    // END XSRF security check

    List<FileItem> fileItems = null;
    InputStream is = null;
    File localFolder = new File(System.getProperty("java.io.tmpdir"));
    OutputStream os = null;

    try {
        fileItems = upload.getFileItems();

        if (fileItems.size() > 0) {
            FileItem item = fileItems.get(0);
            is = item.getInputStream();

            byte[] bytes = IOUtils.toByteArray(is);
            ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));

            int entries = 0;
            long total = 0;
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                byte[] buffer = new byte[BUFFER];

                String expectedFilePath = new StringBuilder(localFolder.getPath()).append(File.separator)
                        .append(ze.getName()).toString();
                String fileName = validateFileName(expectedFilePath, localFolder.getPath());
                File newFile = new File(fileName);
                if (newFile.isDirectory()) {
                    newFile.mkdirs();
                    ze = zis.getNextEntry();
                    continue;
                }
                if (newFile.getParent() != null) {
                    File parent = new File(newFile.getParent());
                    parent.mkdirs();
                }

                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while (total + BUFFER <= tooBig && (len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                    total += len;
                }
                fos.flush();
                fos.close();

                entries++;
                if (entries > tooMany) {
                    throw new IllegalStateException("Too many files to unzip.");
                }
                if (total > tooBig) {
                    throw new IllegalStateException("File being unzipped is too big.");
                }

                ze = zis.getNextEntry();
            }

            zis.closeEntry();
            zis.close();
        }
    } catch (IOException e) {
        throw e;
    } catch (GwtKuraException e) {
        throw new ServletException("File is outside extraction target directory.");
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                s_logger.warn("Cannot close output stream", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                s_logger.warn("Cannot close input stream", e);
            }
        }
        if (fileItems != null) {
            for (FileItem fileItem : fileItems) {
                fileItem.delete();
            }
        }
    }
}