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.dhatim.archive.Archive.java

/**
 * Add the entries from the supplied {@link ZipInputStream} to this archive instance.
 * @param zipStream The zip stream./*from   ww w.j a  v  a  2  s .c  om*/
 * @return This archive instance.
 * @throws IOException Error reading zip stream.
 */
public Archive addEntries(ZipInputStream zipStream) throws IOException {
    AssertArgument.isNotNull(zipStream, "zipStream");

    try {
        ZipEntry zipEntry = zipStream.getNextEntry();
        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        byte[] byteReadBuffer = new byte[512];
        int byteReadCount;

        while (zipEntry != null) {
            if (zipEntry.isDirectory()) {
                addEntry(zipEntry.getName(), (byte[]) null);
            } else {
                while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) {
                    outByteStream.write(byteReadBuffer, 0, byteReadCount);
                }
                addEntry(zipEntry.getName(), outByteStream.toByteArray());
                outByteStream.reset();
            }
            zipEntry = zipStream.getNextEntry();
        }
    } finally {
        try {
            zipStream.close();
        } catch (IOException e) {
            logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e);
        }
    }

    return this;
}

From source file:org.jevis.commons.drivermanagment.ClassImporter.java

public List<File> unZipIt(String outputFolder, File zipFile) {
    List<File> files = new ArrayList<>();

    byte[] buffer = new byte[1024];

    try {/*from w  w  w.  j av  a2  s .  c o  m*/

        //create output directory is not exists
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            newFile.deleteOnExit();
            files.add(newFile);

            //                System.out.println("file unzip : " + newFile.getAbsoluteFile());
            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

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

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return files;
}

From source file:nl.imvertor.common.file.ZipFile.java

/**
 * Unzip it//from w  w  w .  j a  v  a  2s.c  om
 * @param zipFile input zip file
 * @param outputFolder zip file output folder
 * @param requestedFilePattern Pattern to match the file name.
 * 
 * @throws Exception 
 */
private void unZipIt(String zipFile, String outputFolder, Pattern requestedFilePattern) throws Exception {

    byte[] buffer = new byte[1024];

    //create output folder is not exists
    AnyFolder folder = new AnyFolder(outputFolder);
    folder.mkdir();

    //get the zip file content
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    //get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        if (!ze.isDirectory()) {
            String fileName = ze.getName();
            // if the pattern specified, use a matcher. Otherwise accept any file.
            Matcher m = (requestedFilePattern != null) ? requestedFilePattern.matcher(fileName) : null;
            if (requestedFilePattern == null || m.find()) {
                File newFile = new File(outputFolder + File.separator + fileName);
                //create all non exists folders
                //else you will hit FileNotFoundException for compressed folder
                new File(newFile.getParent()).mkdirs();
                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();
}

From source file:org.cytobank.acs.core.ACS.java

/**
 * Sets up the inventory in this <code>ACS</code> instance from an ACS
 * container on disk./*from  ww  w .  java2  s . com*/
 * 
 * @throws FileNotFoundException
 *             If the ACS container was not found
 * @throws AcsException
 *             If a problem occurred with versions or tables of contents
 * @throws URISyntaxException
 *             If a problem occurred parsing URIs
 * @throws SAXException
 *             If there was a problem parsing the xml
 */
protected void setupInventory() throws FileNotFoundException, AcsException, URISyntaxException, SAXException {
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(acsFile));

    try {
        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory())
                continue;

            String name = zipEntry.getName();
            if (name.startsWith(Constants.TOC_PREFIX) && name.endsWith(Constants.TOC_SUFFIX)) {
                int tocVersion = parseTocVersion(name);
                TableOfContents tableOfContents = createTableOfContents(zipInputStream, tocVersion);
                tablesOfContentsByVersion.put(tocVersion, tableOfContents);

                if (highestTableOfContentsVersion < tocVersion)
                    highestTableOfContentsVersion = tocVersion;
            }

            inventory.add(name);
        }
        zipInputStream.close();
    } catch (IOException ioe) {
        try {
            zipInputStream.close();
        } catch (IOException ignore) {
        }
        throw new InvalidArchiveException(ioe.toString());
    }
}

From source file:de.innovationgate.wgpublisher.plugins.WGAPlugin.java

public static Configuration loadConfiguration(File file, boolean full)
        throws FileNotFoundException, IOException, InvalidCSConfigVersionException {

    if (!file.exists()) {
        return null;
    }//from w ww. ja  v a 2s .  co  m

    file = WGUtils.resolveDirLink(file);

    DesignDefinition syncInfo = null;
    CSConfig csConfig = null;
    OverlayData overlayData = null;
    String licenseText = null;

    // Normal plugin file
    if (file.isFile()) {
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {

                String entryName = entry.getName();
                if (entryName.equals(DesignDirectory.DESIGN_DEFINITION_FILE)
                        || entryName.equals(DesignDirectory.SYNCINFO_FILE)) {
                    TemporaryFile tempFile = new TemporaryFile("design", zipIn, WGFactory.getTempDir());
                    syncInfo = DesignDefinition.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.CSCONFIG_PATH)) {
                    TemporaryFile tempFile = new TemporaryFile("csconfig", zipIn, WGFactory.getTempDir());
                    csConfig = CSConfig.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.LICENSE_PATH)) {
                    licenseText = WGUtils.readString(new InputStreamReader(zipIn, "UTF-8")).trim();
                } else if (entryName.equals(SystemContainerManager.OVERLAY_DATA_PATH)) {
                    try {
                        overlayData = OverlayData.read(zipIn);
                    } catch (Exception e) {
                        Logger.getLogger("wga.plugins").error(
                                "Exception reading overlay data from plugin file " + file.getAbsolutePath(), e);
                    }
                }

                if (syncInfo != null && csConfig != null) {
                    if (!full || overlayData != null) {
                        break;
                    }
                }
            }
        } finally {
            zipIn.close();
        }
    }

    // Developer plugin folder
    else {
        File syncInfoFile = DesignDirectory.getDesignDefinitionFile(file);
        if (syncInfoFile.exists()) {
            syncInfo = DesignDefinition.load(syncInfoFile);
        }
        File csConfigFile = new File(file, SystemContainerManager.CSCONFIG_PATH);
        if (csConfigFile.exists()) {
            csConfig = CSConfig.load(csConfigFile);
        }
        File licenseTextFile = new File(file, SystemContainerManager.LICENSE_PATH);
        if (licenseTextFile.exists()) {
            Reader reader = new InputStreamReader(new FileInputStream(licenseTextFile), "UTF-8");
            licenseText = WGUtils.readString(reader).trim();
            reader.close();
        }
        File overlayDataFile = new File(file, SystemContainerManager.OVERLAY_DATA_PATH);
        if (overlayDataFile.exists()) {
            try {
                InputStream stream = new FileInputStream(overlayDataFile);
                overlayData = OverlayData.read(stream);
                stream.close();
            } catch (Exception e) {
                Logger.getLogger("wga.plugins").error(
                        "Exception reading overlay data from plugin directory " + file.getAbsolutePath(), e);
            }
        }

    }

    if (syncInfo != null && csConfig != null && csConfig.getPluginConfig() != null) {
        return new Configuration(syncInfo, csConfig, licenseText, overlayData);
    } else {
        return null;
    }

}

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

@Override
public DeploymentConfiguration getDeploymentConfiguration(InputStream appPackageInputStream) {
    DeploymentConfiguration deploymentConfig = null;
    ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(appPackageInputStream),
            Charset.forName("UTF-8"));

    try {/*from  ww  w. ja  v a 2 s .c  om*/
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

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

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

            if (zipEntry.getName().startsWith(SLEDGEFILE_XML)) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

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

                DeploymentConfigurationReader deploymentConfigReader = new DeploymentConfigurationReaderXml();
                deploymentConfig = deploymentConfigReader
                        .parseDeploymentConfiguration(new ByteArrayInputStream(output.toByteArray()));

                zipStream.closeEntry();

                // Stop here, the file is read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackageInputStream.reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return deploymentConfig;
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

private void copyZipFile(File file, String path) throws FileNotFoundException, IOException {
    ZipInputStream zipIs = null;
    ZipEntry zEntry = null;/*from ww w. ja  v  a2 s  .  c o m*/
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(file);
        zipIs = new ZipInputStream(new BufferedInputStream(fis));

        while ((zEntry = zipIs.getNextEntry()) != null) {
            byte[] tmp = new byte[4 * 1024];
            File newFile = new File(zEntry.getName());
            String directory = newFile.getParent();
            if (directory == null) {
                try (FileOutputStream fos = new FileOutputStream(path + File.separator + zEntry.getName())) {
                    int size = 0;
                    while ((size = zipIs.read(tmp)) != -1) {
                        fos.write(tmp, 0, size);
                        fos.flush();
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.error("Error occured while trying to copy zip file.", e);
        throw e;
    } finally {
        if (zipIs != null) {
            zipIs.close();
        }
        if (fis != null) {
            fis.close();
        }
        file.delete();
    }
}

From source file:com.fdt.sdl.admin.ui.action.UploadAction.java

public void extractZip(InputStream is) throws IOException {
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    int BUFFER = 4096;
    BufferedOutputStream dest = null;
    ZipEntry entry;//from   w  w  w .j a  v a2 s .com
    while ((entry = zis.getNextEntry()) != null) {
        // System.out.println("Extracting: " +entry);
        // out.println(entry.getName());
        String entryPath = entry.getName();
        if (entryPath.indexOf('\\') >= 0) {
            entryPath = entryPath.replace('\\', File.separatorChar);
        }
        String destFilePath = WebserverStatic.getRootDirectory() + entryPath;
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        File f = new File(destFilePath);

        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        if (!f.exists()) {
            FileUtil.createNewFile(f);
            logger.info("creating file: " + f);
        } else {
            logger.info("already existing file: " + f);
            if (f.isDirectory()) {
                continue;
            }
        }

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

From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java

/**
 * Obtiene una lista de objetos <tt>FacturaReader</tt> desde el mensaje de correo, si existe
 *
 * @param mime4jMessage/*from  w  w  w .  ja v  a2 s  . c o  m*/
 * @return lista de instancias instancia <tt>FacturaReader</tt> si existe la factura, null
 * en caso contrario
 */
private List<FacturaReader> handleMessage(org.apache.james.mime4j.dom.Message mime4jMessage)
        throws IOException, Exception {
    List<FacturaReader> result = new ArrayList<>();
    ByteArrayOutputStream os = null;
    String filename = null;
    Factura factura = null;
    EmailHelper emailHelper = new EmailHelper();
    if (mime4jMessage.isMultipart()) {
        org.apache.james.mime4j.dom.Multipart mime4jMultipart = (org.apache.james.mime4j.dom.Multipart) mime4jMessage
                .getBody();
        emailHelper.parseBodyParts(mime4jMultipart);
        //Obtener la factura en los adjuntos
        if (emailHelper.getAttachments().isEmpty()) {
            //If it's single part message, just get text body  
            String text = emailHelper.getHtmlBody().toString();
            emailHelper.getTxtBody().append(text);
            if (mime4jMessage.getSubject().contains("Ghost")) {

                String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"",
                        "\" target=\"_blank\">Descarga formato XML</a>");
                if (url != null) {
                    result.add(FacturaElectronicaURLReader.getFacturaElectronica(url));
                }
            }
        } else {
            for (Entity entity : emailHelper.getAttachments()) {
                filename = EmailHelper.getFilename(entity);

                //if (entity.getBody() instanceof BinaryBody) {
                if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType())
                        || "application/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/plain".equalsIgnoreCase(entity.getMimeType()))
                        && (filename != null && filename.endsWith(".xml"))) {
                    //attachFiles += part.getFileName() + ", ";
                    os = EmailHelper.writeBody(entity.getBody());
                    factura = FacturaUtil.read(os.toString());
                    if (factura != null) {
                        result.add(new FacturaReader(factura, os.toString(), entity.getFilename(),
                                mime4jMessage.getFrom().get(0).getAddress()));
                    }
                } else if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType())
                        || "aplication/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/xml".equalsIgnoreCase(entity.getMimeType()))
                        && (filename != null && filename.endsWith(".zip"))) {
                    //http://www.java2s.com/Tutorial/Java/0180__File/UnzipusingtheZipInputStream.htm    
                    os = EmailHelper.writeBody(entity.getBody());
                    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray()));
                    try {
                        ZipEntry entry = null;
                        String tmp = null;
                        ByteArrayOutputStream fout = null;
                        while ((entry = zis.getNextEntry()) != null) {
                            if (entry.getName().endsWith(".xml")) {
                                //logger.debug("Unzipping {}", entry.getFilename());
                                fout = new ByteArrayOutputStream();
                                for (int c = zis.read(); c != -1; c = zis.read()) {
                                    fout.write(c);
                                }

                                tmp = new String(fout.toByteArray(), Charset.defaultCharset());

                                factura = FacturaUtil.read(tmp);
                                if (factura != null) {
                                    result.add(new FacturaReader(factura, tmp, entity.getFilename()));
                                }
                                fout.close();
                            }
                            zis.closeEntry();
                        }
                        zis.close();

                    } finally {
                        IOUtils.closeQuietly(os);
                        IOUtils.closeQuietly(zis);
                    }
                } else if ("message/rfc822".equalsIgnoreCase(entity.getMimeType())) {
                    if (entity.getBody() instanceof org.apache.james.mime4j.message.MessageImpl) {
                        result.addAll(
                                handleMessage((org.apache.james.mime4j.message.MessageImpl) entity.getBody()));
                    }
                }
            }
        }
    } else {
        //If it's single part message, just get text body  
        String text = emailHelper.getTxtPart(mime4jMessage);
        emailHelper.getTxtBody().append(text);
        if (mime4jMessage.getSubject().contains("Ghost")) {

            String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"",
                    "\" target=\"_blank\">Descarga formato XML</a>");
            if (url != null) {
                result.add(FacturaElectronicaURLReader.getFacturaElectronica(url));
            }
        }
    }
    return result;
}

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

private void findModulesInPath(ArrayList<File> res, String module_suffix, final java.lang.String path) {
    try {/*  w w w. j  av a2s  .c o m*/
        LOG.trace("findModulesInPath(" + 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().endsWith(module_suffix))
                    res.add(object);
                else
                    findModulesInPath(res, module_suffix, thing.getCanonicalPath());
            }
        } else if (object.isFile() && object.getName().endsWith(module_suffix)) {
            LOG.info("Module found: " + object.getAbsolutePath());
            res.add(object);
        } 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().endsWith(module_suffix)) {

                    JarFile jarFile = new JarFile(object);

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

                    InputStream inputStream = jarFile.getInputStream(entry);

                    File f = File.createTempFile("gofleet-", ".module");
                    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.info("Module found: " + zipEntry.getName());
                    res.add(f);
                }
            }
            zis.close();
            fis.close();
        }
    } catch (Throwable t) {
        LOG.error(t, t);
    }
}