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.syncope.core.rest.controller.ReportController.java

@PreAuthorize("hasRole('REPORT_READ')")
@RequestMapping(method = RequestMethod.GET, value = "/execution/export/{executionId}")
@Transactional(readOnly = true)//  w  w w  .  j a  va2 s  . c o  m
public void exportExecutionResult(final HttpServletResponse response,
        @PathVariable("executionId") final Long executionId,
        @RequestParam(value = "fmt", required = false) final ReportExecExportFormat fmt)
        throws NotFoundException {

    ReportExec reportExec = reportExecDAO.find(executionId);
    if (reportExec == null) {
        throw new NotFoundException("Report execution " + executionId);
    }
    if (!ReportExecStatus.SUCCESS.name().equals(reportExec.getStatus()) || reportExec.getExecResult() == null) {

        SyncopeClientCompositeErrorException sccee = new SyncopeClientCompositeErrorException(
                HttpStatus.BAD_REQUEST);
        SyncopeClientException sce = new SyncopeClientException(SyncopeClientExceptionType.InvalidReportExec);
        sce.addElement(reportExec.getExecResult() == null ? "No report data produced"
                : "Report did not run successfully");
        sccee.addException(sce);
        throw sccee;
    }

    ReportExecExportFormat format = fmt == null ? ReportExecExportFormat.XML : fmt;

    LOG.debug("Exporting result of {} as {}", reportExec, format);

    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.addHeader("Content-Disposition",
            "attachment; filename=" + reportExec.getReport().getName() + "." + format.name().toLowerCase());

    // streaming SAX handler from a compressed byte array stream
    ByteArrayInputStream bais = new ByteArrayInputStream(reportExec.getExecResult());
    ZipInputStream zis = new ZipInputStream(bais);
    try {
        // a single ZipEntry in the ZipInputStream (see ReportJob)
        zis.getNextEntry();

        Pipeline<SAXPipelineComponent> pipeline = new NonCachingPipeline<SAXPipelineComponent>();
        pipeline.addComponent(new XMLGenerator(zis));

        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("status", reportExec.getStatus());
        parameters.put("message", reportExec.getMessage());
        parameters.put("startDate", reportExec.getStartDate());
        parameters.put("endDate", reportExec.getEndDate());

        switch (format) {
        case HTML:
            XSLTTransformer xsl2html = new XSLTTransformer(getClass().getResource("/report/report2html.xsl"));
            xsl2html.setParameters(parameters);
            pipeline.addComponent(xsl2html);
            pipeline.addComponent(XMLSerializer.createXHTMLSerializer());
            break;

        case PDF:
            XSLTTransformer xsl2pdf = new XSLTTransformer(getClass().getResource("/report/report2fo.xsl"));
            xsl2pdf.setParameters(parameters);
            pipeline.addComponent(xsl2pdf);
            pipeline.addComponent(new FopSerializer(MimeConstants.MIME_PDF));
            break;

        case RTF:
            XSLTTransformer xsl2rtf = new XSLTTransformer(getClass().getResource("/report/report2fo.xsl"));
            xsl2rtf.setParameters(parameters);
            pipeline.addComponent(xsl2rtf);
            pipeline.addComponent(new FopSerializer(MimeConstants.MIME_RTF));
            break;

        case XML:
        default:
            pipeline.addComponent(XMLSerializer.createXMLSerializer());
        }

        pipeline.setup(response.getOutputStream());
        pipeline.execute();

        LOG.debug("Result of {} successfully exported as {}", reportExec, format);
    } catch (Throwable t) {
        LOG.error("While exporting content", t);
    } finally {
        try {
            zis.close();
            bais.close();
        } catch (IOException e) {
            LOG.error("While closing stream for execution result", e);
        }
    }
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .jzml file
 * /*from  w ww  .  ja v  a  2  s .  co  m*/
 * @param zipTouchoscFilePath a .jzml file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    IPath path = new Path(zipTouchoscFilePath);

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            FileOutputStream os = new FileOutputStream(path.removeLastSegments(1) + "/_" + path.lastSegment());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<touchosc>", "");
            content = content.replace("</touchosc>", "");
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:com.amazonaws.eclipse.sdk.ui.AbstractSdkManager.java

private void unzipSDK(File zipFile, File unzipDestination, IProgressMonitor monitor, int totalUnitsOfWork)
        throws IOException {

    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));

    monitor.subTask("Extracting SDK to workspace metadata directory");

    int worked = 0;
    long totalSize = zipFile.length();
    long totalUnzipped = 0;
    int unitWorkInBytes = (int) (totalSize / (double) totalUnitsOfWork);

    ZipEntry zipEntry = null;//from   w  w w  .  j  av  a2  s. c  o  m

    try {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            IPath path = new Path(zipEntry.getName());

            File destinationFile = new File(unzipDestination, path.toOSString());
            if (zipEntry.isDirectory()) {
                destinationFile.mkdirs();
            } else {
                long compressedSize = zipEntry.getCompressedSize();

                FileOutputStream outputStream = new FileOutputStream(destinationFile);
                try {
                    IOUtils.copy(zipInputStream, outputStream);
                } catch (EOFException eof) {
                    /*
                     * There is a bug in ZipInputStream, where it might
                     * incorrectly throw EOFException if the read exceeds
                     * the current zip-entry size.
                     *
                     * http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6519463
                     */
                    JavaSdkPlugin.getDefault().getLog().log(new Status(Status.WARNING, JavaSdkPlugin.PLUGIN_ID,
                            "Ignore EOFException when unpacking zip-entry " + zipEntry.getName(), eof));
                }
                outputStream.close();

                totalUnzipped += compressedSize;
                if (totalUnzipped / unitWorkInBytes > worked) {
                    int newWork = (int) (totalUnzipped / (double) unitWorkInBytes) - worked;
                    monitor.worked(newWork);
                    worked += newWork;
                }
            }
        }

    } finally {
        zipInputStream.close();
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private void unzipFile(File file) {
    String zipFileFullPath = file.getPath();// path contains file name
    String zipFilePath = zipFileFullPath.substring(0, zipFileFullPath.indexOf(file.getName()));// path without file
                                                                                               // name
    ZipInputStream zin = null;
    try {/*www .  ja  va  2s.c o m*/
        zin = new ZipInputStream(new FileInputStream(zipFileFullPath));
        ZipEntry zipEntry = null;
        byte[] buf = new byte[1024];

        while ((zipEntry = zin.getNextEntry()) != null) {
            String zipEntryName = zipEntry.getName();
            String newPath = zipFilePath + File.separator
                    + file.getName().substring(0, file.getName().lastIndexOf(".")) + File.separator
                    + zipEntryName;// original path +
                                                                                                                                                                 // zipfile Name + entry
                                                                                                                                                                 // name
            File outfile = new File(newPath);
            if (zipEntry.isDirectory()) {
                outfile.mkdirs();
                continue;
            } else {
                if (!outfile.getParentFile().exists()) {
                    outfile.getParentFile().mkdirs();
                }
            }

            OutputStream os = new BufferedOutputStream(new FileOutputStream(outfile));
            int readLen = 0;
            try {
                readLen = zin.read(buf, 0, 1024);
            } catch (IOException ioe) {
                readLen = -1;
            }
            while (readLen != -1) {
                os.write(buf, 0, readLen);
                try {
                    readLen = zin.read(buf, 0, 1024);
                } catch (IOException ioe) {
                    readLen = -1;
                }
            }
            os.close();
        }
    } catch (IOException e) {
        s_logger.error("unzip file error.", e);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException e) {
                s_logger.error("Error occurs.", e);
            }
        }
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

/**
 * Estrae il contenuto di un archivio in formato ZIP.
 *
 * @param archiveInputStream L'input stream da cui leggere il contenuto dell'archivio.
 * @param path Il path della directory in cui estrarre il contenuto dell'archivio.
 *
 * @throws Exception/*from  w w  w. j a va2s .  c o m*/
 */
// TODO: verificare come mai se il file non e' ZIP non va in errore
private void extractZip(InputStream archiveInputStream, String path) throws Exception {
    logger.debug("[ArchiveImporterJob::extractZip] BEGIN");
    ZipInputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
        inputStream = new ZipInputStream(archiveInputStream);
        String entryName = null;
        byte[] buffer = new byte[1024];
        int n = 0;
        for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream.getNextEntry()) {
            entryName = entry.getName();
            File entryFile = new File(path + File.separator + entryName);
            if (entry.isDirectory()) {
                if (!entryFile.mkdirs()) {
                    throw new EcmEngineException("cannot create directory: " + entryFile.getAbsolutePath());
                }
            } else {
                File parentDir = entryFile.getParentFile();
                if (!parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        throw new EcmEngineException("cannot create directory: " + parentDir.getAbsolutePath());
                    }
                }
                fileOutputStream = new FileOutputStream(entryFile);
                while ((n = inputStream.read(buffer, 0, buffer.length)) > -1) {
                    fileOutputStream.write(buffer, 0, n);
                }
                fileOutputStream.close();
            }
            inputStream.closeEntry();
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
            }
            try {
                fileOutputStream.close();
            } catch (Exception e) {
            }
        }
        logger.debug("[ArchiveImporterJob::extractZip] END");
    }
}

From source file:de.xirp.plugin.PluginManager.java

/**
 * Extracts files from the plugins jar./*from  w ww .  jav a  2s. c o m*/
 * 
 * @param info
 *            the information about the plugin
 * @param destination
 *            destination for extraction
 * @param comparer
 *            comparer which returns <code>0</code> if an
 *            element from the jar should be extracted
 * @param replace
 *            string of the elements path which should be deleted
 * @param deleteOnExit
 *            <code>true</code> if the extracted files should be
 *            deleted on exit of the application.
 * @return <code>false</code> if an error occurred while
 *         extraction
 */
private static boolean extractFromJar(PluginInfo info, String destination, Comparable<String> comparer,
        String replace, boolean deleteOnExit) {
    if (logClass.isTraceEnabled()) {
        logClass.trace(Constants.LINE_SEPARATOR + "Extracting for Plugin: " + info.getDefaultName() //$NON-NLS-1$
                + " to path " + destination + Constants.LINE_SEPARATOR); //$NON-NLS-1$
    }
    ZipInputStream zip = null;
    FileInputStream in = null;
    try {
        in = new FileInputStream(info.getAbsoluteJarPath());
        zip = new ZipInputStream(in);

        ZipEntry entry = null;
        while ((entry = zip.getNextEntry()) != null) {
            // relative name with slashes to separate dirnames.
            String elementName = entry.getName();
            // Check if it's an entry within Plugin Dir.
            // Only need to extract these

            if (comparer.compareTo(elementName) == 0) {
                // Remove Help Dir Name, because we don't like
                // to extract this parent dir
                elementName = elementName.replaceFirst(replace + JAR_SEPARATOR, "").trim(); //$NON-NLS-1$ 

                if (!elementName.equalsIgnoreCase("")) { //$NON-NLS-1$
                    // if parent dir for File does not exist,
                    // create
                    // it
                    File elementFile = new File(destination, elementName);
                    if (!elementFile.exists()) {
                        elementFile.getParentFile().mkdirs();
                        if (deleteOnExit) {
                            DeleteManager.deleteOnShutdown(elementFile);
                        }
                    }

                    // Only extract files, directorys are created
                    // above with mkdirs
                    if (!entry.isDirectory()) {
                        FileOutputStream fos = new FileOutputStream(elementFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = zip.read(buf)) > 0) {
                            fos.write(buf, 0, len);
                        }
                        fos.close();
                        elementFile.setLastModified(entry.getTime());
                    }
                    logClass.trace("Extracted: " + elementName + Constants.LINE_SEPARATOR); //$NON-NLS-1$
                }
            }
            zip.closeEntry();
        }

    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        return false;
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
    }

    return true;
}

From source file:org.agnitas.cms.web.CMTemplateAction.java

public int readArchivedCMTemplate(CMTemplateForm aForm, InputStream stream, HttpServletRequest request) {
    ZipInputStream zipInputStream = new ZipInputStream(stream);
    ZipEntry entry;//from ww  w. jav  a 2 s .  co  m
    String templateBody = null;
    // binds image name in zip to image id in CCR (Central Content Repository)
    Map<String, Integer> imageBindMap = new HashMap<String, Integer>();
    int newTemplateId = createEmptyCMTemplate(request);
    if (newTemplateId == -1) {
        return -1;
    }
    try {
        while ((entry = zipInputStream.getNextEntry()) != null) {
            String entryName = entry.getName();
            // hack for ignoring MACOS archive system folders
            if (entryName.contains("__MACOSX")) {
                continue;
            }
            // skip if directory
            if (entryName.endsWith("/")) {
                continue;
            }
            // if file is in media-folder - store it in CCR
            if (entryName.startsWith(MEDIA_FOLDER)) {
                // thumbs.db is ignored by EMM
                if (!StringUtils.endsWithIgnoreCase(entryName, THUMBS_DB)) {
                    byte[] fileData = getEntryData(zipInputStream, entry);
                    int mediaFileId = storeMediaFile(fileData, entryName, newTemplateId, request);
                    if (mediaFileId != -1) {
                        imageBindMap.put(entryName, mediaFileId);
                    }
                }
            } else if (entryName.endsWith(".html") && templateBody == null) {
                // first html file that was found in root folder of
                // zip-archive is considered to be a template-file
                byte[] templateData = getEntryData(zipInputStream, entry);
                templateBody = new String(templateData, Charset.forName(aForm.getCharset()).name());
            }
        }
        zipInputStream.close();
    } catch (IOException e) {
        AgnUtils.logger().error("Error occured reading CM template from zip: ", e);
    }
    if (templateBody == null) {
        getTemplateManager().deleteCMTemplate(newTemplateId);
        getMediaManager().removeMediaFilesForCMTemplateId(newTemplateId);
        return -1;
    } else {
        templateBody = replacePictureLinks(templateBody, imageBindMap);
        try {
            getTemplateManager().updateContent(newTemplateId,
                    templateBody.getBytes(Charset.forName("UTF-8").name()));
        } catch (UnsupportedEncodingException e) {
            AgnUtils.logger().warn("Wrong charset name", e);
        }
        return newTemplateId;
    }
}

From source file:net.zionsoft.obadiah.model.Bible.java

private void downloadTranslation(String url, String translationShortName, OnDownloadProgressListener onProgress)
        throws Exception {
    ZipInputStream zis = null;
    SQLiteDatabase db = null;/*from  w ww. j a v a  2s  .c o  m*/
    try {
        db = mDatabaseHelper.openDatabase();
        if (db == null) {
            Analytics.trackException("Failed to open database.");
            throw new Exception("Failed to open database for writing");
        }
        db.beginTransaction();

        TranslationHelper.createTranslationTable(db, translationShortName);

        zis = new ZipInputStream(NetworkHelper.getStream(url));

        final byte buffer[] = new byte[2048];
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        int downloaded = 0;
        int read;
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            os.reset();
            while ((read = zis.read(buffer, 0, 2048)) != -1)
                os.write(buffer, 0, read);
            final byte[] bytes = os.toByteArray();
            String fileName = entry.getName();
            fileName = fileName.substring(0, fileName.length() - 5); // removes the trailing ".json"
            if (fileName.equals("books")) {
                TranslationHelper.saveBookNames(db, new JSONObject(new String(bytes, "UTF8")));
            } else {
                final String[] parts = fileName.split("-");
                final int bookIndex = Integer.parseInt(parts[0]);
                final int chapterIndex = Integer.parseInt(parts[1]);
                TranslationHelper.saveVerses(db, translationShortName, bookIndex, chapterIndex,
                        new JSONObject(new String(bytes, "UTF8")));
            }

            onProgress.onProgress(++downloaded / 12);
        }

        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            if (db.inTransaction()) {
                db.endTransaction();
            }
            mDatabaseHelper.closeDatabase();
        }
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                // we can't do much here
            }
        }
    }
}