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.baasbox.service.dbmanager.DbManagerService.java

public static void importDb(String appcode, ZipInputStream zis) throws FileFormatException, Exception {
    File newFile = null;//  w ww.j  a va 2 s. co m
    FileOutputStream fout = null;
    try {
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        if (ze == null)
            throw new FileFormatException("Looks like the uploaded file is not a valid export.");
        if (ze.isDirectory()) {
            ze = zis.getNextEntry();
        }
        if (ze != null) {
            newFile = File.createTempFile("export", ".json");
            fout = new FileOutputStream(newFile);
            IOUtils.copy(zis, fout, BBConfiguration.getImportExportBufferSize());
            fout.close();
        } else {
            throw new FileFormatException("Looks like the uploaded file is not a valid export.");
        }
        ZipEntry manifest = zis.getNextEntry();
        if (manifest != null) {
            File manifestFile = File.createTempFile("manifest", ".txt");
            fout = new FileOutputStream(manifestFile);
            for (int c = zis.read(); c != -1; c = zis.read()) {
                fout.write(c);
            }
            fout.close();
            String manifestContent = FileUtils.readFileToString(manifestFile);
            manifestFile.delete();
            Pattern p = Pattern.compile(BBInternalConstants.IMPORT_MANIFEST_VERSION_PATTERN);
            Matcher m = p.matcher(manifestContent);
            if (m.matches()) {
                String version = m.group(1);
                if (version.compareToIgnoreCase("0.6.0") < 0) { //we support imports from version 0.6.0
                    throw new FileFormatException(String.format(
                            "Current baasbox version(%s) is not compatible with import file version(%s)",
                            BBConfiguration.getApiVersion(), version));
                } else {
                    if (BaasBoxLogger.isDebugEnabled())
                        BaasBoxLogger.debug("Version : " + version + " is valid");
                }
            } else {
                throw new FileFormatException("The manifest file does not contain a version number");
            }
        } else {
            throw new FileFormatException("Looks like zip file does not contain a manifest file");
        }
        if (newFile != null) {
            DbHelper.importData(appcode, newFile);
            zis.closeEntry();
            zis.close();
        } else {
            throw new FileFormatException("The import file is empty");
        }
    } catch (FileFormatException e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
        throw e;
    } catch (Throwable e) {
        BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
        throw new Exception("There was an error handling your zip import file.", e);
    } finally {
        try {
            if (zis != null) {
                zis.close();
            }
            if (fout != null) {
                fout.close();
            }
        } catch (IOException e) {
            // Nothing to do here
        }
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.TestPipeLineExecute.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    // Initialize action
    initAction(request);/*from www. j a v  a  2s  .  c  o m*/
    if (null == config) {
        return (mapping.findForward("noconfig"));
    }

    if (isCancelled(request)) {
        return (mapping.findForward("success"));
    }

    DynaActionForm pipeLineTestForm = (DynaActionForm) form;
    String form_adapterName = (String) pipeLineTestForm.get("adapterName");
    String form_message = (String) pipeLineTestForm.get("message");
    String form_resultText = "";
    String form_resultState = "";
    FormFile form_file = (FormFile) pipeLineTestForm.get("file");

    // if no message and no formfile, send an error
    if (StringUtils.isEmpty(form_message) && (form_file == null || form_file.getFileSize() == 0)) {

        storeFormData(null, null, null, pipeLineTestForm);
        warn("Nothing to send or test");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, null, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }
    if ((form_adapterName == null) || (form_adapterName.length() == 0)) {
        warn("No adapter selected");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, form_message, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }
    // Execute the request
    IAdapter adapter = config.getRegisteredAdapter(form_adapterName);
    if (adapter == null) {
        warn("Adapter with specified name [" + form_adapterName + "] could not be retrieved");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, form_message, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }

    // if upload is choosen, it prevails over the message
    if ((form_file != null) && (form_file.getFileSize() > 0)) {
        log.debug("Upload of file [" + form_file.getFileName() + "] ContentType[" + form_file.getContentType()
                + "]");
        if (FileUtils.extensionEqualsIgnoreCase(form_file.getFileName(), "zip")) {
            ZipInputStream archive = new ZipInputStream(new ByteArrayInputStream(form_file.getFileData()));
            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 currentMessage = XmlUtils.readXml(b, 0, rb, request.getCharacterEncoding(), false);
                    //PipeLineResult pipeLineResult = adapter.processMessage(name+"_" + Misc.createSimpleUUID(), currentMessage);
                    PipeLineResult pipeLineResult = processMessage(adapter,
                            name + "_" + Misc.createSimpleUUID(), currentMessage);
                    form_resultText += name + ":" + pipeLineResult.getState() + "\n";
                    form_resultState = pipeLineResult.getState();
                }
                archive.closeEntry();
            }
            archive.close();
            form_message = null;
        } else {
            form_message = XmlUtils.readXml(form_file.getFileData(), request.getCharacterEncoding(), false);
        }
    } else {
        form_message = new String(form_message.getBytes(), Misc.DEFAULT_INPUT_STREAM_ENCODING);
    }

    if (form_message != null && form_message.length() > 0) {
        // Execute the request
        //PipeLineResult pipeLineResult = adapter.processMessage("testmessage" + Misc.createSimpleUUID(), form_message);
        PipeLineResult pipeLineResult = processMessage(adapter, "testmessage" + Misc.createSimpleUUID(),
                form_message);
        form_resultText = pipeLineResult.getResult();
        form_resultState = pipeLineResult.getState();
    }
    storeFormData(form_resultText, form_resultState, form_message, pipeLineTestForm);

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return (new ActionForward(mapping.getInput()));
    }

    // Forward control to the specified success URI
    log.debug("forward to success");
    return (mapping.findForward("success"));

}

From source file:edu.wustl.xipHost.caGrid.RetrieveNBIASecuredTest.java

@Test
public void test() throws Exception {
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    Login login = new GridLogin();
    String userName = "<JIRAusername>";
    String password = "<JIRApassword>";
    DcmFileFilter dcmFilter = new DcmFileFilter();
    login.login(userName, password);/*from   ww w . ja  v  a 2  s . c o m*/
    GlobusCredential globusCred = login.getGlobusCredential();
    boolean isConnectionSecured = login.isConnectionSecured();
    logger.debug("Acquired NBIA GlobusCredential. Connection secured = " + isConnectionSecured);
    if (!isConnectionSecured) {
        fail("Unable to acquire NBIA GlobusCredential. Check username and password.");
        return;
    }
    NCIACoreServiceClient client = new NCIACoreServiceClient(gridServiceUrl, globusCred);
    client.setAnonymousPrefered(false);
    TransferServiceContextReference tscr = client.retrieveDicomDataBySeriesUID("1.3.6.1.4.1.9328.50.1.4718");
    TransferServiceContextClient tclient = new TransferServiceContextClient(tscr.getEndpointReference(),
            globusCred);
    InputStream istream = TransferClientHelper.getData(tclient.getDataTransferDescriptor(), globusCred);
    ZipInputStream zis = new ZipInputStream(istream);
    ZipEntryInputStream zeis = null;
    BufferedInputStream bis = null;
    File importDir = new File("./test-content/NBIA5");
    if (!importDir.exists()) {
        importDir.mkdirs();
    } else {
        File[] files = importDir.listFiles(dcmFilter);
        for (int j = 0; j < files.length; j++) {
            File file = files[j];
            file.delete();
        }
    }
    while (true) {
        try {
            zeis = new ZipEntryInputStream(zis);
        } catch (EOFException e) {
            break;
        } catch (IOException e) {
            logger.error(e, e);
        }
        String unzzipedFile = null;
        try {
            unzzipedFile = importDir.getCanonicalPath();
        } catch (IOException e) {
            logger.error(e, e);
        }
        logger.debug(" filename: " + zeis.getName());
        bis = new BufferedInputStream(zeis);
        byte[] data = new byte[8192];
        int bytesRead = 0;
        String retrievedFilePath = unzzipedFile + File.separator + zeis.getName();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(retrievedFilePath));
            while ((bytesRead = (bis.read(data, 0, data.length))) != -1) {
                bos.write(data, 0, bytesRead);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            logger.error(e, e);
        }
    }
    try {
        zis.close();
        tclient.destroy();
    } catch (IOException e) {
        logger.error(e, e);
    }
    File[] retrievedFiles = importDir.listFiles(dcmFilter);
    int numbOfRetreivedFiles = retrievedFiles.length;
    assertEquals("Number of retrieved files should be 2 but is. " + numbOfRetreivedFiles, numbOfRetreivedFiles,
            2);
    //Assert file names. They should be equal to items' SeriesInstanceUIDs
    Map<String, File> mapRetrievedFiles = new HashMap<String, File>();
    for (int i = 0; i < numbOfRetreivedFiles; i++) {
        File file = retrievedFiles[i];
        mapRetrievedFiles.put(file.getName(), file);
    }
    boolean retrievedFilesCorrect = false;
    if (mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4716.dcm")
            && mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4720.dcm")) {
        retrievedFilesCorrect = true;
    }
    assertTrue("Retrieved files are not as expected.", retrievedFilesCorrect);
}

From source file:edu.monash.merc.system.remote.HttpHpaFileGetter.java

public boolean importHPAXML(String remoteFile, String localFile) {
    //use httpclient to get the remote file
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(remoteFile);

    ZipInputStream zis = null;
    FileOutputStream fos = null;/*from  w  w w  .  j a  v a  2 s  .com*/
    try {
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream in = entity.getContent();
                zis = new ZipInputStream(in);
                ZipEntry zipEntry = zis.getNextEntry();
                while (zipEntry != null) {
                    String fileName = zipEntry.getName();
                    if (StringUtils.contains(fileName, HPA_FILE_NAME)) {
                        System.out.println("======= found file.");
                        File aFile = new File(localFile);
                        fos = new FileOutputStream(aFile);
                        byte[] buffer = new byte[BUFFER_SIZE];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                        fos.flush();
                        break;
                    }
                }
            }
        } else {
            throw new DMRemoteException("can't get the file from " + remoteFile);
        }
    } catch (Exception ex) {
        throw new DMRemoteException(ex);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (zis != null) {
                zis.closeEntry();
                zis.close();
            }
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            //ignore whatever caught
        }
    }
    return true;
}

From source file:com.thinkbiganalytics.feedmgr.service.ExportImportTemplateService.java

private ImportTemplate openZip(String fileName, InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry entry;//w w  w.j a  v a2 s .c  o m
    // while there are entries I process them
    ImportTemplate importTemplate = new ImportTemplate(fileName);
    while ((entry = zis.getNextEntry()) != null) {
        log.info("zip file entry: " + entry.getName());
        // consume all the data from this entry
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len = 0;
        while ((len = zis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        String outString = new String(out.toByteArray(), "UTF-8");
        if (entry.getName().startsWith(NIFI_TEMPLATE_XML_FILE)) {
            importTemplate.setNifiTemplateXml(outString);
        } else if (entry.getName().startsWith(TEMPLATE_JSON_FILE)) {
            importTemplate.setTemplateJson(outString);
        } else if (entry.getName().startsWith(NIFI_CONNECTING_REUSABLE_TEMPLATE_XML_FILE)) {
            importTemplate.addNifiConnectingReusableTemplateXml(outString);
        }
    }
    zis.closeEntry();
    zis.close();
    if (!importTemplate.isValid()) {
        throw new UnsupportedOperationException(
                " The file you uploaded is not a valid archive.  Please ensure the Zip file has been exported from the system and has 2 valid files named: "
                        + NIFI_TEMPLATE_XML_FILE + ", and " + TEMPLATE_JSON_FILE);
    }
    importTemplate.setZipFile(true);
    return importTemplate;

}

From source file:org.candlepin.sync.ExporterTest.java

/**
 * return true if export has a given entry named name.
 * @param export zip file to inspect// w ww . j a v a 2  s  .com
 * @param name entry
 * @return
 */
private boolean verifyHasEntry(File export, String name) {
    ZipInputStream zis = null;
    boolean found = false;

    try {
        zis = new ZipInputStream(new FileInputStream(export));
        ZipEntry entry = null;

        while ((entry = zis.getNextEntry()) != null) {
            byte[] buf = new byte[1024];

            if (entry.getName().equals("consumer_export.zip")) {
                OutputStream os = new FileOutputStream("/tmp/consumer_export.zip");

                int n;
                while ((n = zis.read(buf, 0, 1024)) > -1) {
                    os.write(buf, 0, n);
                }
                os.flush();
                os.close();
                File exportdata = new File("/tmp/consumer_export.zip");
                // open up the zip and look for the metadata
                verifyHasEntry(exportdata, name);
            } else if (entry.getName().equals(name)) {
                found = true;
            }

            zis.closeEntry();
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return found;
}

From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java

private Document getDeploymentStructureFromArchive(File zipFile) throws Exception {
    getLog().debug("Read deployment-informations from archive <" + zipFile + ">");
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry entry;/*w  w  w . jav  a2s .  c  o  m*/
    Document doc = null;
    boolean done = false;
    while (!done && (entry = zis.getNextEntry()) != null) {
        String entryName = entry.getName().toLowerCase();
        if (entryName.endsWith("meta-inf/" + JBOSS_SUBDEPLOYMENT)
                || entryName.endsWith("web-inf/" + JBOSS_SUBDEPLOYMENT)) {
            byte[] buf = IOUtils.toByteArray(zis);
            if (verbose) {
                getLog().debug(new String(buf, encoding));
            }
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            // doc=factory.newDocumentBuilder().parse(new ByteArrayInputStream(buf),encoding);
            doc = factory.newDocumentBuilder().parse(
                    new org.xml.sax.InputSource(new java.io.StringReader(new String(buf, encoding).trim())));
            done = true;
        } else {
            if (entry.getCompressedSize() >= 0) {
                if (verbose) {
                    getLog().debug("Skipping entry <" + entryName + "> to next entry for bytes:"
                            + entry.getCompressedSize());
                }
                zis.skip(entry.getCompressedSize());
            }
        }
    }
    zis.close();
    return doc;
}

From source file:io.gromit.geolite2.geonames.SubdivisionFinder.java

/**
 * Read countries.// w  w  w.ja  v  a  2  s.c  o m
 *
 * @param subdivisionOneLocationUrl the subdivision one location url
 * @return the time zone finder
 */
public SubdivisionFinder readLevelOne(String subdivisionOneLocationUrl) {
    ZipInputStream zipis = null;
    try {
        zipis = new ZipInputStream(new URL(subdivisionOneLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc1 == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }
        CsvParserSettings settings = new CsvParserSettings();
        settings.setSkipEmptyLines(true);
        settings.trimValues(true);
        CsvFormat format = new CsvFormat();
        format.setDelimiter('\t');
        format.setLineSeparator("\n");
        format.setCharToEscapeQuoteEscaping('\0');
        format.setQuote('\0');
        settings.setFormat(format);
        CsvParser parser = new CsvParser(settings);

        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));

        for (String[] entry : lines) {
            Subdivision subdivision = new Subdivision();
            subdivision.setId(entry[0]);
            subdivision.setName(entry[1]);
            subdivision.setGeonameId(NumberUtils.toInt(entry[2]));
            idOneMap.put(subdivision.getId(), subdivision);
            geonameIdMap.put(subdivision.getGeonameId(), subdivision);
        }
        logger.info("loaded " + lines.size() + " subdivisions level 1");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}

From source file:io.gromit.geolite2.geonames.SubdivisionFinder.java

/**
 * Read level two.//from  w w  w .j a va 2s. c o  m
 *
 * @param subdivisionTwoLocationUrl the subdivision two location url
 * @return the subdivision finder
 */
public SubdivisionFinder readLevelTwo(String subdivisionTwoLocationUrl) {
    ZipInputStream zipis = null;
    try {
        zipis = new ZipInputStream(new URL(subdivisionTwoLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc2 == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }
        CsvParserSettings settings = new CsvParserSettings();
        settings.setSkipEmptyLines(true);
        settings.trimValues(true);
        CsvFormat format = new CsvFormat();
        format.setDelimiter('\t');
        format.setLineSeparator("\n");
        format.setCharToEscapeQuoteEscaping('\0');
        format.setQuote('\0');
        settings.setFormat(format);
        CsvParser parser = new CsvParser(settings);

        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));

        for (String[] entry : lines) {
            Subdivision subdivision = new Subdivision();
            subdivision.setId(entry[0]);
            subdivision.setName(entry[1]);
            subdivision.setGeonameId(NumberUtils.toInt(entry[2]));
            idTowMap.put(subdivision.getId(), subdivision);
            geonameIdMap.put(subdivision.getGeonameId(), subdivision);
        }
        logger.info("loaded " + lines.size() + " subdivisions level 2");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}

From source file:aurelienribon.gdxsetupui.ProjectUpdate.java

/**
 * Selected libraries are inflated from their zip files, and put in the
 * correct folders of the projects./*from   w  ww  . j a  v  a 2  s . c o m*/
 * @throws IOException
 */
public void inflateLibraries() throws IOException {
    File commonPrjLibsDir = new File(Helper.getCorePrjPath(cfg) + "libs");
    File desktopPrjLibsDir = new File(Helper.getDesktopPrjPath(cfg) + "libs");
    File androidPrjLibsDir = new File(Helper.getAndroidPrjPath(cfg) + "libs");
    File htmlPrjLibsDir = new File(Helper.getHtmlPrjPath(cfg) + "war/WEB-INF/lib");
    File iosPrjLibsDir = new File(Helper.getIosPrjPath(cfg) + "libs");
    File dataDir = new File(Helper.getAndroidPrjPath(cfg) + "assets");

    for (String library : cfg.libraries) {
        InputStream is = new FileInputStream(cfg.librariesZipPaths.get(library));
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry;

        LibraryDef def = libs.getDef(library);

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory())
                continue;
            String entryName = entry.getName();

            for (String elemName : def.libsCommon)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, commonPrjLibsDir);

            if (cfg.isDesktopIncluded) {
                for (String elemName : def.libsDesktop)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, desktopPrjLibsDir);
            }

            if (cfg.isAndroidIncluded) {
                for (String elemName : def.libsAndroid)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, androidPrjLibsDir);
                for (String elemName : def.data)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, dataDir);
            }

            if (cfg.isHtmlIncluded) {
                for (String elemName : def.libsHtml)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, htmlPrjLibsDir);
            }

            if (cfg.isIosIncluded) {
                for (String elemName : def.libsIos)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, iosPrjLibsDir);
            }
        }

        zis.close();
    }
}