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:com.github.nethad.clustermeister.provisioning.local.JPPFLocalNode.java

private void unzipNode(InputStream fileToUnzip, File targetDir) {
    ZipInputStream zipFile;
    try {//from  w  w  w  .  j  ava  2s . c o m
        zipFile = new ZipInputStream(fileToUnzip);
        ZipEntry entry;
        while ((entry = zipFile.getNextEntry()) != null) {
            //                ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                // Assume directories are stored parents first then children.
                System.err.println("Extracting directory: " + entry.getName());
                // This is not robust, just for demonstration purposes.
                (new File(targetDir, entry.getName())).mkdir();
                continue;
            }
            System.err.println("Extracting file: " + entry.getName());
            File targetFile = new File(targetDir, entry.getName());
            copyInputStream_notClosing(zipFile, new BufferedOutputStream(new FileOutputStream(targetFile)));
            //                zipFile.closeEntry();
        }
        zipFile.close();
    } catch (IOException ioe) {
        logger.warn("Unhandled exception.", ioe);
    }
}

From source file:nl.nn.adapterframework.webcontrol.api.TestPipeline.java

private void processZipFile(Map<String, Object> returnResult, InputStream inputStream, String fileEncoding,
        IAdapter adapter, boolean writeSecLogMessage) throws IOException {
    String result = "";
    String lastState = null;//ww w.j  a v a2s .co  m
    ZipInputStream archive = new ZipInputStream(inputStream);
    for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
        String name = entry.getName();
        int size = (int) entry.getSize();
        if (size > 0) {
            byte[] b = new byte[size];
            int rb = 0;
            int chunk = 0;
            while (((int) size - rb) > 0) {
                chunk = archive.read(b, rb, (int) size - rb);
                if (chunk == -1) {
                    break;
                }
                rb += chunk;
            }
            String message = XmlUtils.readXml(b, 0, rb, fileEncoding, false);
            if (StringUtils.isNotEmpty(result)) {
                result += "\n";
            }
            lastState = processMessage(adapter, message, writeSecLogMessage).getState();
            result += name + ":" + lastState;
        }
        archive.closeEntry();
    }
    archive.close();
    returnResult.put("state", lastState);
    returnResult.put("result", result);
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Deserializes examplars stored in archives in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getArchiveDirectory()//from   ww  w . j a v  a2s .c o  m
 */
public void deserializeArchivedVersions() throws RuntimeException {
    System.out.println("Deserializing archived instances in " + getArchiveDirectory() + ".");

    File archive = new File(getArchiveDirectory());

    if (!archive.exists() || !archive.isDirectory()) {
        return;
    }

    String[] listing = archive.list();

    for (String archiveName : listing) {
        if (!(archiveName.endsWith(".zip"))) {
            continue;
        }

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            ZipFile zipFile = new ZipFile(file);
            ZipEntry entry = zipFile.getEntry("class_fields.ser");
            InputStream inputStream = zipFile.getInputStream(entry);
            ObjectInputStream objectIn = new ObjectInputStream(inputStream);
            Map<String, List<String>> classFields = (Map<String, List<String>>) objectIn.readObject();
            zipFile.close();

            for (String className : classFields.keySet()) {

                //                    if (classFields.equals("HypotheticalGraph")) continue;

                List<String> fieldNames = classFields.get(className);
                Class<?> clazz = Class.forName(className);
                ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz);

                if (streamClass == null) {
                    System.out.println();
                }

                for (String fieldName : fieldNames) {
                    assert streamClass != null;
                    ObjectStreamField field = streamClass.getField(fieldName);

                    if (field == null) {
                        throw new RuntimeException("Field '" + fieldName + "' was dropped from class '"
                                + className + "' as a serializable field! Please " + "put it back!!!"
                                + "\nIt used to be in " + className + " in this archive: " + archiveName + ".");
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not read class_fields.ser in archive + " + archiveName + " .", e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }

        System.out.println("...Deserializing instances in " + archiveName + "...");
        ZipEntry zipEntry = null;

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            FileInputStream in = new FileInputStream(file);
            ZipInputStream zipinputstream = new ZipInputStream(in);

            while ((zipEntry = zipinputstream.getNextEntry()) != null) {
                if (!zipEntry.getName().endsWith(".ser")) {
                    continue;
                }

                ObjectInputStream objectIn = new ObjectInputStream(zipinputstream);
                objectIn.readObject();
                zipinputstream.closeEntry();
            }

            zipinputstream.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(
                    "Could not read object zipped file " + zipEntry.getName() + " in archive " + archiveName
                            + ". " + "Perhaps the class was renamed, moved to another package, or "
                            + "removed. In any case, please put it back where it was.",
                    e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }
    }

    System.out.println("Finished deserializing archived instances.");
}

From source file:InstallJars.java

public void installZip(URLConnection conn, String target, boolean doExpand, boolean doRun) throws IOException {
    // doRun not used on htis type
    if (doExpand) {
        String ctype = conn.getContentType();
        if (!ctype.equals("application/zip")) {
            throw new IllegalArgumentException("Unkexpected content type - " + ctype);
        }//from   w w w  . j  a  va2 s.c o m
        println("Expanding ZIP file to " + target + " from " + conn.getURL().toExternalForm());
        ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT));
        int count = 0;
        prepDirs(target, true);
        try {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                copyEntry(target, zis, ze);
                // zis.closeEntry();
                count++;
            }
        } finally {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
        println("Installed " + count + " files/directories");
    } else {
        print("Installing ZIP file " + target + " from " + conn.getURL().toExternalForm());
        copyStream(conn, target);
        println();
    }
}

From source file:com.joliciel.talismane.GenericLanguageImplementation.java

public void setLanguagePack(File languagePackFile) {
    ZipInputStream zis = null;
    try {/*w w  w . j a va  2 s  . com*/
        zis = new ZipInputStream(new FileInputStream(languagePackFile));
        ZipEntry ze = null;

        Map<String, String> argMap = new HashMap<String, String>();
        while ((ze = zis.getNextEntry()) != null) {
            String name = ze.getName();
            if (name.indexOf('/') >= 0)
                name = name.substring(name.lastIndexOf('/') + 1);
            if (name.equals("languagePack.properties")) {
                Properties props = new Properties();
                props.load(zis);
                argMap = StringUtils.getArgMap(props);
                break;
            }
        } // next zip entry
        zis.close();

        Map<String, String> reverseMap = new HashMap<String, String>();
        for (String key : argMap.keySet()) {
            String value = argMap.get(key);
            if (value.startsWith("replace:")) {
                value = value.substring("replace:".length());
                if (key.equals("textFilters")) {
                    replaceTextFilters = true;
                } else if (key.equals("tokenFilters")) {
                    replaceTokenFilters = true;
                } else if (key.equals("tokenSequenceFilters")) {
                    replaceTokenSequenceFilters = true;
                }
            }
            if (key.equals("locale")) {
                locale = Locale.forLanguageTag(value);
            } else {
                reverseMap.put(value, key);
            }
        }

        zis = new ZipInputStream(new FileInputStream(languagePackFile));
        ze = null;

        while ((ze = zis.getNextEntry()) != null) {
            String name = ze.getName();
            if (name.indexOf('/') >= 0)
                name = name.substring(name.lastIndexOf('/') + 1);
            String key = reverseMap.get(name);
            if (key != null) {
                if (key.equals("transitionSystem")) {
                    transitionSystem = this.getParserService().getArcEagerTransitionSystem();
                    Scanner scanner = new Scanner(zis, "UTF-8");
                    List<String> dependencyLabels = new ArrayListNoNulls<String>();
                    while (scanner.hasNextLine()) {
                        String dependencyLabel = scanner.nextLine();
                        if (!dependencyLabel.startsWith("#")) {
                            if (dependencyLabel.indexOf('\t') > 0)
                                dependencyLabel = dependencyLabel.substring(0, dependencyLabel.indexOf('\t'));
                            dependencyLabels.add(dependencyLabel);
                        }
                    }
                    transitionSystem.setDependencyLabels(dependencyLabels);
                } else if (key.equals("posTagSet")) {
                    Scanner scanner = new Scanner(zis, "UTF-8");
                    posTagSet = this.getPosTaggerService().getPosTagSet(scanner);
                } else if (key.equals("textFilters")) {
                    Scanner scanner = new Scanner(zis, "UTF-8");
                    textFiltersStr = this.getStringFromScanner(scanner);
                } else if (key.equals("tokenFilters")) {
                    Scanner scanner = new Scanner(zis, "UTF-8");
                    tokenFiltersStr = this.getStringFromScanner(scanner);
                } else if (key.equals("tokenSequenceFilters")) {
                    Scanner scanner = new Scanner(zis, "UTF-8");
                    tokenSequenceFiltersStr = this.getStringFromScanner(scanner);
                } else if (key.equals("posTaggerRules")) {
                    Scanner scanner = new Scanner(zis, "UTF-8");
                    posTaggerRulesStr = this.getStringFromScanner(scanner);
                } else if (key.equals("parserRules")) {
                    Scanner scanner = new Scanner(zis, "UTF-8");
                    parserRulesStr = this.getStringFromScanner(scanner);
                } else if (key.equals("sentenceModel")) {
                    ZipInputStream innerZis = new ZipInputStream(new UnclosableInputStream(zis));
                    sentenceModel = this.getMachineLearningService().getClassificationModel(innerZis);
                } else if (key.equals("tokeniserModel")) {
                    ZipInputStream innerZis = new ZipInputStream(new UnclosableInputStream(zis));
                    tokeniserModel = this.getMachineLearningService().getClassificationModel(innerZis);
                } else if (key.equals("posTaggerModel")) {
                    ZipInputStream innerZis = new ZipInputStream(new UnclosableInputStream(zis));
                    posTaggerModel = this.getMachineLearningService().getClassificationModel(innerZis);
                } else if (key.equals("parserModel")) {
                    ZipInputStream innerZis = new ZipInputStream(new UnclosableInputStream(zis));
                    parserModel = this.getMachineLearningService().getClassificationModel(innerZis);
                } else if (key.equals("lexicon")) {
                    ZipInputStream innerZis = new ZipInputStream(new UnclosableInputStream(zis));
                    LexiconDeserializer deserializer = new LexiconDeserializer(this.getTalismaneSession());
                    lexicons = deserializer.deserializeLexicons(innerZis);
                } else if (key.equals("corpusLexiconEntryRegex")) {
                    Scanner corpusLexicalEntryRegexScanner = new Scanner(zis, "UTF-8");
                    corpusLexicalEntryReader = new RegexLexicalEntryReader(corpusLexicalEntryRegexScanner);
                } else {
                    throw new TalismaneException("Unknown key in languagePack.properties: " + key);
                }
            }
        }
    } catch (FileNotFoundException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                LogUtils.logError(LOG, e);
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.apache.axis2.deployment.resolver.AARBasedWSDLLocator.java

/**
 * @param parentLocation//from  w w  w .  j  a  v  a 2s.  com
 * @param importLocation
 */
public InputSource getImportInputSource(String parentLocation, String importLocation) {
    lastImportLocation = URI.create(parentLocation).resolve(importLocation);

    if (isAbsolute(lastImportLocation.toString())) {
        return super.resolveEntity(null, importLocation, parentLocation);
    } else {
        //we don't care about the parent location
        ZipInputStream zin = null;
        try {

            zin = new ZipInputStream(new FileInputStream(aarFile));
            ZipEntry entry;
            byte[] buf = new byte[1024];
            int read;
            ByteArrayOutputStream out;
            String searchingStr = lastImportLocation.toString();
            while ((entry = zin.getNextEntry()) != null) {
                String entryName = entry.getName().toLowerCase();
                if (entryName.equalsIgnoreCase(searchingStr)) {
                    out = new ByteArrayOutputStream();
                    while ((read = zin.read(buf)) > 0) {
                        out.write(buf, 0, read);
                    }
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                    return new InputSource(in);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (zin != null) {
                    zin.close();
                }
            } catch (IOException e) {
                log.debug(e);
            }
        }
    }

    log.info("AARBasedWSDLLocator: Unable to resolve " + lastImportLocation);
    return null;
}

From source file:org.exoplatform.services.document.impl.MSXPPTDocumentReader.java

public Properties getProperties(InputStream is) throws IOException, DocumentReadException {
    try {//  ww  w . j ava  2 s.co m

        ZipInputStream zis = new ZipInputStream(is);
        try {
            ZipEntry ze = zis.getNextEntry();

            while (ze != null && !ze.getName().equals(PPTX_CORE_NAME)) {
                ze = zis.getNextEntry();
            }

            if (ze == null)
                return new Properties();

            MSPPTXMetaHandler metaHandler = new MSPPTXMetaHandler();
            XMLReader xmlReader = SAXHelper.newXMLReader();

            xmlReader.setFeature("http://xml.org/sax/features/validation", false);
            xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
            xmlReader.setContentHandler(metaHandler);
            xmlReader.parse(new InputSource(zis));
            return metaHandler.getProperties();
        } finally {
            zis.close();
        }

    } catch (ParserConfigurationException e) {
        throw new DocumentReadException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new DocumentReadException(e.getMessage(), e);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("An exception occurred: " + e.getMessage());
                }
            }
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * jarclass//from   w w  w  .j  a  v a 2s. c  om
 * @param inJar
 * @param removeClasses
 */
public static void removeFilesFromJar(File inJar, List<String> removeClasses) throws IOException {
    if (null == removeClasses || removeClasses.isEmpty()) {
        return;
    }
    File outJar = new File(inJar.getParentFile(), inJar.getName() + ".tmp");
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
                continue;
            }
            String name = entry.getName();
            String className = getClassName(name);
            if (removeClasses.contains(className)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
    FileUtils.deleteQuietly(inJar);
    FileUtils.moveFile(outJar, inJar);
}

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public String getEnvironmentFile(String environmentName, ApplicationPackage appPackage) {
    ZipInputStream zipStream = getNewUtf8ZipInputStream(appPackage);
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try {/*from  w w  w.  j  ava  2  s .c om*/
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (getBaseName(zipEntry.getName()).equals(environmentName)) {

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                zipStream.closeEntry();

                // Stop here because the file has been already read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackage.getPackageFile().reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return output.toString();
}

From source file:de.static_interface.sinklibrary.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit
 *//*w ww .ja  v a 2  s.com*/
private void unzip(File zipFile) {
    byte[] buffer = new byte[1024];

    try {
        File outputFolder = zipFile.getParentFile();
        if (!outputFolder.exists()) {
            outputFolder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            if (!newFile.exists() && newFile.getName().toLowerCase().endsWith(".jar")) {
                ze = zis.getNextEntry();
                continue;
            }

            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();

        zipFile.delete();

    } catch (IOException ex) {
        SinkLibrary.getInstance().getLogger()
                .warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
        result = Updater.UpdateResult.FAIL_DOWNLOAD;
        ex.printStackTrace();
    }
}