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.alfresco.rest.api.tests.TestDownloads.java

/**
 * Tests downloading the content of a download node(a zip) using the /nodes API:
 *
 * <p>GET:</p>/*from  w  w  w .  ja va  2 s .co m*/
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/content}
 * 
 */
@Test
public void test004GetDownloadContent() throws Exception {

    //test downloading the content of a 1 file zip
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertDoneDownload(download, 1, 13);

    HttpResponse response = downloadContent(download);

    ZipInputStream zipStream = getZipStreamFromResponse(response);

    ZipEntry zipEntry = zipStream.getNextEntry();

    assertEquals("Zip entry name is not correct", ZIPPABLE_DOC1_NAME, zipEntry.getName());

    assertTrue("Zip entry size is not correct", zipEntry.getCompressedSize() <= 13);

    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
    zipStream.close();

    Map<String, String> responseHeaders = response.getHeaders();

    assertNotNull(responseHeaders);

    assertEquals(format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
            ZIPPABLE_DOC1_NAME + DEFAULT_ARCHIVE_EXTENSION, ZIPPABLE_DOC1_NAME + DEFAULT_ARCHIVE_EXTENSION),
            responseHeaders.get("Content-Disposition"));

    //test downloading the content of a multiple file zip
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableFolderId1, zippableDocId3_InFolder1);

    assertDoneDownload(download, 3, 39);

    response = downloadContent(download);

    zipStream = getZipStreamFromResponse(response);

    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/", zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + DOC3_NAME,
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + SUB_FOLDER1_NAME + "/",
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + SUB_FOLDER1_NAME + "/" + DOC4_NAME,
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", DOC3_NAME, zipStream.getNextEntry().getName());

    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
    zipStream.close();

    responseHeaders = response.getHeaders();

    assertNotNull(responseHeaders);

    assertEquals(format("attachment; filename=\"%s\"; filename*=UTF-8''%s", DEFAULT_ARCHIVE_NAME,
            DEFAULT_ARCHIVE_NAME), responseHeaders.get("Content-Disposition"));

    //test download the content of a zip which has a secondary child
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1, zippableFolderId3);
    assertDoneDownload(download, 2, 26);

    response = downloadContent(download);

    zipStream = getZipStreamFromResponse(response);

    assertEquals("Zip entry name is not correct", ZIPPABLE_DOC1_NAME, zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER3_NAME + "/", zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER3_NAME + "/" + ZIPPABLE_DOC1_NAME,
            zipStream.getNextEntry().getName());
    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
}

From source file:org.jahia.test.TestHelper.java

public static JahiaSite createSite(String name, String serverName, String templateSet, String prepackedZIPFile,
        String siteZIPName, String[] modulesToDeploy) throws Exception {
    modulesToDeploy = (modulesToDeploy == null) ? new String[0] : modulesToDeploy;

    JahiaUser admin = JahiaAdminUser.getAdminUser(null);

    JahiaSitesService service = ServicesRegistry.getInstance().getJahiaSitesService();
    try {//from   ww  w .j av a  2 s .co m
        JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentSystemSession(null, null, null);
        JahiaSite existingSite = service.getSiteByKey(name, session);

        if (existingSite != null) {
            service.removeSite(existingSite);
            session.refresh(false);
        }
    } catch (RepositoryException ex) {
        logger.debug("Error while trying to remove the site", ex);
    }
    JahiaSite site = null;
    File siteZIPFile = null;
    File sharedZIPFile = null;
    try {
        if (!StringUtils.isEmpty(prepackedZIPFile)) {
            ZipInputStream zis = null;
            OutputStream os = null;
            try {
                zis = new ZipInputStream(new FileInputStream(new File(prepackedZIPFile)));
                ZipEntry z = null;
                while ((z = zis.getNextEntry()) != null) {
                    if (siteZIPName.equalsIgnoreCase(z.getName()) || "users.zip".equals(z.getName())) {
                        File zipFile = File.createTempFile("import", ".zip");
                        os = new FileOutputStream(zipFile);
                        byte[] buf = new byte[4096];
                        int r;
                        while ((r = zis.read(buf)) > 0) {
                            os.write(buf, 0, r);
                        }
                        os.close();
                        if ("users.zip".equals(z.getName())) {
                            sharedZIPFile = zipFile;
                        } else {
                            siteZIPFile = zipFile;
                        }
                    }
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                if (zis != null) {
                    try {
                        zis.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        }
        if (sharedZIPFile != null) {
            try {
                ImportExportBaseService.getInstance().importSiteZip(
                        sharedZIPFile != null ? new FileSystemResource(sharedZIPFile) : null, null, null);
            } catch (RepositoryException e) {
                logger.warn("shared.zip could not be imported", e);
            }
        }
        site = service.addSite(admin, name, serverName, name, name,
                SettingsBean.getInstance().getDefaultLocale(), templateSet, modulesToDeploy,
                siteZIPFile == null ? "noImport" : "fileImport",
                siteZIPFile != null ? new FileSystemResource(siteZIPFile) : null, null, false, false, null);
        site = service.getSiteByKey(name);
    } finally {
        if (sharedZIPFile != null) {
            sharedZIPFile.delete();
        }
        if (siteZIPFile != null) {
            siteZIPFile.delete();
        }
    }

    return site;
}

From source file:com.baasbox.controllers.Admin.java

/**
 * /admin/db/import (POST)//from ww w. java 2s .  co m
 * 
 * the method allows to upload a json export file and apply it to the db.
 * WARNING: all data on the db will be wiped out before importing
 * 
 * @return a 200 Status code when the import is successfull,a 500 status code otherwise
 */
public static Result importDb() {
    String appcode = (String) ctx().args.get("appcode");
    if (appcode == null || StringUtils.isEmpty(appcode.trim())) {
        unauthorized("appcode can not be null");
    }
    MultipartFormData body = request().body().asMultipartFormData();
    if (body == null)
        return badRequest("missing data: is the body multipart/form-data?");
    FilePart fp = body.getFile("file");

    if (fp != null) {
        ZipInputStream zis = null;
        try {
            java.io.File multipartFile = fp.getFile();
            java.util.UUID uuid = java.util.UUID.randomUUID();
            File zipFile = File.createTempFile(uuid.toString(), ".zip");
            FileUtils.copyFile(multipartFile, zipFile);
            zis = new ZipInputStream(new FileInputStream(zipFile));
            DbManagerService.importDb(appcode, zis);
            zipFile.delete();
            return ok();
        } catch (org.apache.xmlbeans.impl.piccolo.io.FileFormatException e) {
            BaasBoxLogger.warn(ExceptionUtils.getMessage(e));
            return badRequest(ExceptionUtils.getMessage(e));
        } catch (Exception e) {
            BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
            return internalServerError(ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                if (zis != null) {
                    zis.close();
                }
            } catch (IOException e) {
                // Nothing to do here
            }
        }
    } else {
        return badRequest("The form was submitted without a multipart file field.");
    }
}

From source file:org.vietspider.server.handler.cms.metas.EditContentHandler.java

private byte[] loadZipEntry(File file, String fileName) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipInputStream zipInput = null;
    try {//from   ww w. j  a va2s  . co m
        zipInput = new ZipInputStream(new FileInputStream(file));
        int read = -1;
        byte[] bytes = new byte[4 * 1024];

        ZipEntry entry = null;
        while (true) {
            entry = zipInput.getNextEntry();
            if (entry == null)
                break;
            if (entry.getName().equalsIgnoreCase(fileName)) {
                while ((read = zipInput.read(bytes, 0, bytes.length)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                break;
            }
        }
        zipInput.close();
    } finally {
        try {
            if (zipInput != null)
                zipInput.close();
        } catch (Exception e) {
        }
    }
    return outputStream.toByteArray();
}

From source file:com.opengamma.util.db.script.ZipFileDbScript.java

@Override
public String getScript() throws IOException {
    ZipInputStream zippedIn = null;
    try {//w w w.  j  a va  2s.  c  o m
        zippedIn = new ZipInputStream(new FileInputStream(getZipFile()));
        ZipEntry entry;
        while ((entry = zippedIn.getNextEntry()) != null) {
            if (entry.getName().equals(getEntryName())) {
                break;
            }
        }
        if (entry == null) {
            throw new OpenGammaRuntimeException(
                    "No entry found in zip file " + getZipFile() + " with name " + getEntryName());
        }
        return IOUtils.toString(zippedIn);
    } catch (FileNotFoundException e) {
        throw new OpenGammaRuntimeException("Zip file not found: " + getZipFile());
    } catch (IOException e) {
        throw new OpenGammaRuntimeException("Error reading from zip file: " + getZipFile());
    } finally {
        if (zippedIn != null) {
            try {
                zippedIn.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.dspace.pack.bagit.Bag.java

public void inflate(InputStream in, String fmt) throws IOException {
    if (filled) {
        throw new IllegalStateException("Cannot inflate filled bag");
    }/*from   w  w w .j  av  a 2  s. co  m*/
    if ("zip".equals(fmt)) {
        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry entry = null;
        while ((entry = zin.getNextEntry()) != null) {
            File outFile = new File(baseDir.getParent(), entry.getName());
            outFile.getParentFile().mkdirs();
            FileOutputStream fout = new FileOutputStream(outFile);
            Utils.copy(zin, fout);
            fout.close();
        }
        zin.close();
    } else if ("tgz".equals(fmt)) {
        TarArchiveInputStream tin = new TarArchiveInputStream(new GzipCompressorInputStream(in));
        TarArchiveEntry entry = null;
        while ((entry = tin.getNextTarEntry()) != null) {
            File outFile = new File(baseDir.getParent(), entry.getName());
            outFile.getParentFile().mkdirs();
            FileOutputStream fout = new FileOutputStream(outFile);
            Utils.copy(tin, fout);
            fout.close();
        }
        tin.close();
    }
    filled = true;
}

From source file:com.joliciel.jochre.search.JochreIndexBuilderImpl.java

private void updateDocumentInternal(File documentDir) {
    try {//from   w w w  .  j av  a 2 s  .com
        LOG.info("Updating index for " + documentDir.getName());

        File zipFile = new File(documentDir, documentDir.getName() + ".zip");
        if (!zipFile.exists()) {
            LOG.info("Nothing to index in " + documentDir.getName());
            return;
        }
        long zipDate = zipFile.lastModified();

        this.deleteDocumentInternal(documentDir);

        File[] offsetFiles = documentDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".obj");
            }
        });

        for (File offsetFile : offsetFiles) {
            offsetFile.delete();
        }

        int i = 0;

        Map<String, String> fields = new TreeMap<String, String>();
        File metaDataFile = new File(documentDir, "metadata.txt");
        Scanner scanner = new Scanner(
                new BufferedReader(new InputStreamReader(new FileInputStream(metaDataFile), "UTF-8")));
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String key = line.substring(0, line.indexOf('\t'));
            String value = line.substring(line.indexOf('\t'));
            fields.put(key, value);
        }
        scanner.close();

        JochreXmlDocument xmlDoc = this.searchService.newDocument();
        JochreXmlReader reader = this.searchService.getJochreXmlReader(xmlDoc);

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null) {
            LOG.debug("Adding zipEntry " + i + ": " + ze.getName());
            String baseName = ze.getName().substring(0, ze.getName().lastIndexOf('.'));
            UnclosableInputStream uis = new UnclosableInputStream(zis);
            reader.parseFile(uis, baseName);
            i++;
        }
        zis.close();

        i = 0;
        StringBuilder sb = new StringBuilder();
        coordinateStorage = searchService.getCoordinateStorage();
        offsetLetterMap = new HashMap<Integer, JochreXmlLetter>();
        int startPage = -1;
        int endPage = -1;
        int docCount = 0;
        int wordCount = 0;
        int cumulWordCount = 0;
        for (JochreXmlImage image : xmlDoc.getImages()) {
            if (startPage < 0)
                startPage = image.getPageIndex();
            endPage = image.getPageIndex();
            int remainingWords = xmlDoc.wordCount() - (cumulWordCount + wordCount);
            LOG.debug("Word count: " + wordCount + ", cumul word count: " + cumulWordCount
                    + ", total xml words: " + xmlDoc.wordCount() + ", remaining words: " + remainingWords);
            if (wordsPerDoc > 0 && wordCount >= wordsPerDoc && remainingWords >= wordsPerDoc) {
                LOG.debug("Creating new index doc: " + docCount);
                JochreIndexDocument indexDoc = searchService.newJochreIndexDocument(documentDir, docCount, sb,
                        coordinateStorage, startPage, endPage, fields);
                indexDoc.save(indexWriter);
                docCount++;

                sb = new StringBuilder();
                coordinateStorage = searchService.getCoordinateStorage();
                startPage = image.getPageIndex();
                offsetLetterMap = new HashMap<Integer, JochreXmlLetter>();
                cumulWordCount += wordCount;
                wordCount = 0;
            }

            LOG.debug("Processing page: " + image.getFileNameBase());

            File imageFile = null;
            for (String imageExtension : imageExtensions) {
                imageFile = new File(documentDir, image.getFileNameBase() + "." + imageExtension);
                if (imageFile.exists())
                    break;
                imageFile = null;
            }
            if (imageFile == null)
                throw new RuntimeException("No image found in directory " + documentDir.getAbsolutePath()
                        + ", baseName " + image.getFileNameBase());

            coordinateStorage.addImage(sb.length(), imageFile.getName(), image.getPageIndex());

            for (JochreXmlParagraph par : image.getParagraphs()) {
                coordinateStorage.addParagraph(sb.length(),
                        new Rectangle(par.getLeft(), par.getTop(), par.getRight(), par.getBottom()));
                for (JochreXmlRow row : par.getRows()) {
                    coordinateStorage.addRow(sb.length(),
                            new Rectangle(row.getLeft(), row.getTop(), row.getRight(), row.getBottom()));
                    int k = 0;
                    for (JochreXmlWord word : row.getWords()) {
                        wordCount++;
                        for (JochreXmlLetter letter : word.getLetters()) {
                            offsetLetterMap.put(sb.length(), letter);
                            if (letter.getText().length() > 1) {
                                for (int j = 1; j < letter.getText().length(); j++) {
                                    offsetLetterMap.put(sb.length() + j, letter);
                                }
                            }
                            sb.append(letter.getText());
                        }
                        k++;
                        boolean finalDash = false;
                        if (k == row.getWords().size() && word.getText().endsWith("-")
                                && word.getText().length() > 1)
                            finalDash = true;
                        if (!finalDash)
                            sb.append(" ");
                    }
                }
                sb.append("\n");
            }
            i++;
        }
        JochreIndexDocument indexDoc = searchService.newJochreIndexDocument(documentDir, docCount, sb,
                coordinateStorage, startPage, endPage, fields);
        indexDoc.save(indexWriter);

        File lastIndexDateFile = new File(documentDir, "indexDate.txt");

        Writer writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(lastIndexDateFile, false), "UTF8"));
        writer.write("" + zipDate);
        writer.flush();

        writer.close();
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:org.apache.oodt.cas.workflow.misc.WingsTask.java

private void unZipIt(String zipFile, String outputFolder) {
    byte[] buffer = new byte[1024];
    try {/*from  w ww . jav a  2 s  . c o m*/
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.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);
            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();
    }
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java

protected File unzip3(File zf) throws FileNotFoundException {
    //File f = null;
    String rename = zf.getAbsolutePath().replaceFirst("\\.zip", identifier + ".xml");//.replaceFirst("\\.gz", ".xml");
    File f = new File(rename);
    try {//from ww  w .  ja  v  a  2 s . co  m
        FileInputStream fis = new FileInputStream(zf);

        ZipInputStream zin = new ZipInputStream(fis);
        ZipEntry ze;

        final byte[] content = new byte[BUFFER];

        while ((ze = zin.getNextEntry()) != null) {
            f = new File(getCalTempPath() + File.separator + ze.getName());
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, content.length);

            int n = 0;
            while (-1 != (n = zin.read(content))) {
                bos.write(content, 0, n);
            }
            bos.flush();
            bos.close();
        }

        fis.close();
        zin.close();
    } catch (IOException ioe) {
        jlog.error("Error processing Zip " + zf + " Excluding! :: " + ioe);
        return null;
    }
    //try again... what could go wrong
    /*
    if (checkMinFileSize(f) && retry_counter<MAX_UNGZIP_RETRIES){
       retry_counter++;
       f.delete();
       f = unzip2(zf);
    }
    */
    return f;
}

From source file:com.wakatime.eclipse.plugin.Dependencies.java

private void unzip(String zipFile, File outputDir) throws IOException {
    if (!outputDir.exists())
        outputDir.mkdirs();/*from   w w  w  . j ava2s .c o  m*/

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(outputDir, fileName);

        if (ze.isDirectory()) {
            // WakaTime.log("Creating directory: "+newFile.getParentFile().getAbsolutePath());
            newFile.mkdirs();
        } else {
            // WakaTime.log("Extracting File: "+newFile.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }

        ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
}