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.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

private void unZipDHIS2APIBackupToTemp(String zipFile) {
    byte[] buffer = new byte[1024];
    String outputFolder = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER;

    try {//from  w ww .j  ava  2 s.  c o m
        File destDir = new File(outputFolder);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zipIn.getNextEntry();

        while (entry != null) {
            String filePath = outputFolder + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                if (!(new File(filePath)).getParentFile().exists()) {
                    (new File(filePath)).getParentFile().mkdirs();
                }
                (new File(filePath)).createNewFile();
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                byte[] bytesIn = buffer;
                int read = 0;
                while ((read = zipIn.read(bytesIn)) != -1) {
                    bos.write(bytesIn, 0, read);
                }
                bos.close();
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.jahia.utils.zip.JahiaArchiveFileHandler.java

/**
 * Extract an entry in a gived folder. If this entry is a directory,
 * all its contents are extracted too.//from  w  ww  .j av  a  2s . co  m
 *
 * @param entryName, the name of an entry in the jar
 * @param destPath,  the path to the destination folder
 */
public void extractEntry(String entryName, String destPath) throws JahiaException {

    try {

        ZipEntry entry = m_JarFile.getEntry(entryName);

        if (entry == null) {
            StringBuilder strBuf = new StringBuilder(1024);
            strBuf.append(" extractEntry(), cannot find entry ");
            strBuf.append(entryName);
            strBuf.append(" in the jar file ");

            throw new JahiaException(CLASS_NAME, strBuf.toString(), JahiaException.SERVICE_ERROR,
                    JahiaException.ERROR_SEVERITY);

        }

        File destDir = new File(destPath);
        if (destDir == null || !destDir.isDirectory() || !destDir.canWrite()) {

            logger.error(" cannot access to the destination dir " + destPath);

            throw new JahiaException(CLASS_NAME, " cannot access to the destination dir ",
                    JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
        }

        String path = null;

        FileInputStream fis = new FileInputStream(m_FilePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipInputStream zis = new ZipInputStream(bis);
        ZipFile zf = new ZipFile(m_FilePath);
        ZipEntry ze = null;
        String zeName = null;

        while ((ze = zis.getNextEntry()) != null && !ze.getName().equalsIgnoreCase(entryName)) {
            // loop until the requested entry
            zis.closeEntry();
        }

        try {
            if (ze != null) {
                if (ze.isDirectory()) {

                    while (ze != null) {
                        zeName = ze.getName();
                        path = destPath + File.separator + genPathFile(zeName);
                        File fo = new File(path);
                        if (ze.isDirectory()) {
                            fo.mkdirs();
                        } else {

                            FileOutputStream outs = new FileOutputStream(fo);
                            copyStream(zis, outs);
                            //outs.flush();
                            //outs.close();
                        }
                        zis.closeEntry();
                        ze = zis.getNextEntry();

                    }
                } else {

                    zeName = ze.getName();
                    path = destPath + File.separator + genPathFile(zeName);

                    File fo = new File(path);
                    FileOutputStream outs = new FileOutputStream(fo);
                    copyStream(zis, outs);
                    //outs.flush();
                    //outs.close();
                }
            }
        } finally {
            // Important !!!
            zf.close();
            fis.close();
            zis.close();
            bis.close();
        }

    } catch (IOException ioe) {

        logger.error(" fail unzipping " + ioe.getMessage(), ioe);

        throw new JahiaException(CLASS_NAME, "faile processing unzip", JahiaException.SERVICE_ERROR,
                JahiaException.ERROR_SEVERITY, ioe);

    }

}

From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java

private void createNewZipfileWithReplacedPlaceholders(InputStream packageStream, Path configurationPackagePath,
        Properties envProps) throws IOException {

    // For reading the original configuration package
    ZipInputStream configPackageZipStream = new ZipInputStream(new BufferedInputStream(packageStream),
            Charset.forName("UTF-8"));

    // For outputting the configured (placeholders replaced) version of the package as zip file
    File outZipFile = configurationPackagePath.toFile();
    ZipOutputStream outConfiguredZipStream = new ZipOutputStream(new FileOutputStream(outZipFile));

    ZipEntry zipEntry;// w  w w  . ja  v a 2s.c  o m
    while ((zipEntry = configPackageZipStream.getNextEntry()) != null) {

        if (zipEntry.isDirectory()) {
            configPackageZipStream.closeEntry();
            continue;
        } else {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            int length;
            byte[] buffer = new byte[2048];
            while ((length = configPackageZipStream.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, length);
            }

            InputStream zipEntryInputStream = new BufferedInputStream(
                    new ByteArrayInputStream(output.toByteArray()));

            if (zipEntry.getName().endsWith("instance.properties")) {
                ByteArrayOutputStream envPropsOut = new ByteArrayOutputStream();
                envProps.store(envPropsOut, "Environment configurations");
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(envPropsOut.toByteArray()));

            } else if (isTextFile(zipEntry.getName(), zipEntryInputStream)) {
                String configuredContent = StrSubstitutor.replace(output, envProps);
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(configuredContent.getBytes()));
            }

            // Add to output zip file
            addToZipFile(zipEntry.getName(), zipEntryInputStream, outConfiguredZipStream);

            zipEntryInputStream.close();
            configPackageZipStream.closeEntry();
        }
    }

    outConfiguredZipStream.close();
    configPackageZipStream.close();
}

From source file:org.etudes.mneme.tool.UploadXml.java

/**
 * unzip the file and write to disk/* w ww  . ja  v  a  2  s .  c o m*/
 * 
 * @param zipfile
 * @param dirpath
 * @throws FileNotFoundException
 * @throws IOException
 */
private void unZipFile(File zipfile, String dirpath) throws Exception {
    FileInputStream fis = new FileInputStream(zipfile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.isDirectory()) {

        } else if (entry.getName().lastIndexOf('\\') != -1) {
            String filenameincpath = entry.getName();

            String actFileNameIncPath = dirpath;

            while (filenameincpath.indexOf('\\') != -1) {
                String subFolName = filenameincpath.substring(0, filenameincpath.indexOf('\\'));

                File subfol = new File(actFileNameIncPath + File.separator + subFolName);
                if (!subfol.exists())
                    subfol.mkdirs();

                actFileNameIncPath = actFileNameIncPath + File.separator + subFolName;

                filenameincpath = filenameincpath.substring(filenameincpath.indexOf('\\') + 1);
            }

            String filename = entry.getName().substring(entry.getName().lastIndexOf('\\') + 1);
            unzip(zis, actFileNameIncPath + File.separator + filename);
        } else if (entry.getName().lastIndexOf('/') != -1) {
            String filenameincpath = entry.getName();

            String actFileNameIncPath = dirpath;

            while (filenameincpath.indexOf('/') != -1) {
                String subFolName = filenameincpath.substring(0, filenameincpath.indexOf('/'));
                File subfol = new File(actFileNameIncPath + File.separator + subFolName);
                if (!subfol.exists())
                    subfol.mkdirs();

                actFileNameIncPath = actFileNameIncPath + File.separator + subFolName;

                filenameincpath = filenameincpath.substring(filenameincpath.indexOf('/') + 1);
            }

            String filename = entry.getName().substring(entry.getName().lastIndexOf('/') + 1);
            unzip(zis, actFileNameIncPath + File.separator + filename);
        } else
            unzip(zis, dirpath + File.separator + entry.getName());
    }
    fis.close();
    zis.close();
}

From source file:com.kdmanalytics.toif.assimilator.Assimilator.java

/**
 * @param kdmFiles2//www  . j a v a2  s.c om
 * @throws IOException
 * @throws ToifException
 */
private void processKdmZip(List<File> kdmFiles2) throws IOException, ToifException {
    ZipInputStream zip = null;
    File file = null;
    try {
        file = kdmFiles2.get(0);
        zip = new ZipInputStream(new FileInputStream(file));
        zip.getNextEntry();

        // Read from the ZipInputStream as you would normally from any other
        // input stream
        LOG.info(file.getAbsolutePath());
        streamStatementsToRepo(zip);
    }

    finally {
        try {
            if (zip != null) {
                zip.close();
            }
        } catch (IOException e) {
            // just leave it alone
            if (file == null)
                file = new File(""); // just to be sure
            LOG.error("unable to close zip stream" + file.getAbsolutePath());
        }
    }
}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

/**
 * Returns The String representation of the code coverage results in XML format.
 *
 * TODO Perhaps this should return the CodeCoverageResults object?
 *
 * @return Returns The String representation of the code coverage results in XML format.
 * @throws IOException If the coverage results (currently zipped into a byte
 *    array and stored in the 'details' blob column) cannot be unzipped.
 *//*from ww  w .  j av a 2  s  .  c  om*/
public String getCodeCoverageXMLResultsAsString() throws IOException {
    // In very early versions that supported code coverage, I stuck the entire XML
    // file into the longTestResult field
    //      if (isCoverageType() && !"".equals(longTestResult))
    //           return longTestResult;

    // Unzip the code coverage results from the "details" field.
    // We assume there will only be one entry in the zip archive.
    ZipInputStream zip = null;
    BufferedReader reader = null;
    try {
        zip = new ZipInputStream(new ByteArrayInputStream((byte[]) details));

        ZipEntry entry = zip.getNextEntry();
        if (entry == null)
            throw new IOException(
                    "This test outcome doesn't contain " + "any zipped entries in the 'details' field.");

        reader = new BufferedReader(new InputStreamReader(zip));

        StringBuffer result = new StringBuffer();
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            result.append(line + "\n");
        }
        return result.toString();
    } finally {
        try {
            if (reader != null)
                reader.close();
        } finally {
            if (zip != null)
                zip.close();
        }
    }
}

From source file:com.griddynamics.deming.ecommerce.api.endpoint.catalog.CatalogManagerEndpoint.java

@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importCatalog(@FormDataParam("file") InputStream uploadInputStream)
        throws ServiceException, IOException {
    removeCatalog();/*  w ww. java 2  s.  co  m*/

    try {
        ZipInputStream inputStream = new ZipInputStream(uploadInputStream);

        try {
            byte[] buf = new byte[1024];

            for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
                    .getNextEntry()) {
                try {
                    String entryName = entry.getName();
                    entryName = entryName.replace('/', File.separatorChar);
                    entryName = entryName.replace('\\', File.separatorChar);

                    LOGGER.debug("Entry name: {}", entryName);

                    if (entry.isDirectory()) {
                        LOGGER.debug("Entry ({}) is directory", entryName);
                    } else if (PRODUCT_CATALOG_FILE.equals(entryName)) {
                        ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream(1024);

                        for (int n = inputStream.read(buf, 0, 1024); n > -1; n = inputStream.read(buf, 0,
                                1024)) {
                            jsonBytes.write(buf, 0, n);
                        }

                        byte[] bytes = jsonBytes.toByteArray();

                        ObjectMapper mapper = new ObjectMapper();

                        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
                        mapper.registerModule(jaxbAnnotationModule);

                        ImportCategoryWrapper catalog = mapper.readValue(bytes, ImportCategoryWrapper.class);
                        escape(catalog);
                        saveCategoryTree(catalog);
                    } else {
                        MultipartFile file = new MultipartFileAdapter(inputStream, entryName);
                        dmgStaticAssetStorageService.createStaticAssetStorageFromFile(file);
                    }

                } finally {
                    inputStream.closeEntry();
                }
            }
        } finally {
            inputStream.close();
        }

    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Unable load catalog.\n").build();
    }

    Thread rebuildSearchIndex = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
                searchService.rebuildIndex();
            } catch (Exception e) {
                /* nothing */}
        }
    });
    rebuildSearchIndex.start();

    return Response.status(Response.Status.OK).entity("Catalog was imported successfully!\n").build();
}

From source file:nl.nn.adapterframework.webcontrol.pipes.UploadConfig.java

private String processZipFile(IPipeLineSession session, String fileName) throws PipeRunException, IOException {
    String result = "";
    Object form_file = session.get("file");
    if (form_file != null) {
        if (form_file instanceof InputStream) {
            InputStream inputStream = (InputStream) form_file;
            String form_fileEncoding = (String) session.get("fileEncoding");
            if (inputStream.available() > 0) {
                /*/*from   w w  w  . ja va 2 s .co m*/
                 * String fileEncoding; if
                 * (StringUtils.isNotEmpty(form_fileEncoding)) {
                 * fileEncoding = form_fileEncoding; } else { fileEncoding =
                 * Misc.DEFAULT_INPUT_STREAM_ENCODING; }
                 */ZipInputStream archive = new ZipInputStream(inputStream);
                int counter = 1;
                for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
                    String entryName = 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;
                        }
                        ByteArrayInputStream bais = new ByteArrayInputStream(b, 0, rb);
                        String fileNameSessionKey = "file_zipentry" + counter;
                        session.put(fileNameSessionKey, bais);
                        if (StringUtils.isNotEmpty(result)) {
                            result += "\n";
                        }
                        String name = "";
                        String version = "";
                        String[] fnArray = splitFilename(entryName);
                        if (fnArray[0] != null) {
                            name = fnArray[0];
                        }
                        if (fnArray[1] != null) {
                            version = fnArray[1];
                        }
                        result += entryName + ":"
                                + processJarFile(session, name, version, entryName, fileNameSessionKey);
                        session.remove(fileNameSessionKey);
                    }
                    archive.closeEntry();
                    counter++;
                }
                archive.close();
            }
        }
    }
    return result;
}

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

/**
 * Extracts the text content of the n first slides 
 *//*from   w w w.  j ava 2s.  c o  m*/
public String getContentAsText(InputStream is, int maxSlides) throws IOException, DocumentReadException {
    if (is == null) {
        throw new IllegalArgumentException("InputStream is null.");
    }
    StringBuilder appendText = new StringBuilder();
    try {

        int slideCount = 0;
        ZipInputStream zis = new ZipInputStream(is);

        try {
            ZipEntry ze = zis.getNextEntry();

            if (ze == null)
                return "";

            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);
            Map<Integer, String> slides = new TreeMap<Integer, String>();
            // PPTX: ppt/slides/slide<slide_no>.xml
            while (ze != null && slideCount < maxSlides) {
                String zeName = ze.getName();
                if (zeName.startsWith(PPTX_SLIDE_PREFIX) && zeName.length() > PPTX_SLIDE_PREFIX.length()) {
                    String slideNumberStr = zeName.substring(PPTX_SLIDE_PREFIX.length(),
                            zeName.indexOf(".xml"));
                    int slideNumber = -1;
                    try {
                        slideNumber = Integer.parseInt(slideNumberStr);
                    } catch (NumberFormatException e) {
                        LOG.warn("Could not parse the slide number: " + e.getMessage());
                    }
                    if (slideNumber > -1 && slideNumber <= maxSlides) {
                        MSPPTXContentHandler contentHandler = new MSPPTXContentHandler();
                        xmlReader.setContentHandler(contentHandler);
                        xmlReader.parse(new InputSource((new ByteArrayInputStream(IOUtils.toByteArray(zis)))));
                        slides.put(slideNumber, contentHandler.getContent());
                        slideCount++;
                    }
                }
                ze = zis.getNextEntry();
            }
            for (String slide : slides.values()) {
                appendText.append(slide);
                appendText.append(' ');
            }
        } finally {
            try {
                zis.close();
            } catch (IOException e) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("An exception occurred: " + e.getMessage());
                }
            }
        }
        return appendText.toString();
    } catch (ParserConfigurationException e) {
        throw new DocumentReadException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new DocumentReadException(e.getMessage(), e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("An exception occurred: " + e.getMessage());
            }
        }
    }
}

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

private void closeInputStream(ZipInputStream zis) throws IOException {
    if (zis instanceof NoCloseZipInputStream) {
        ((NoCloseZipInputStream) zis).reallyClose();
    } else {/*from   w w w  .java  2  s .  c o  m*/
        zis.close();
    }
}