Example usage for java.util.zip ZipOutputStream closeEntry

List of usage examples for java.util.zip ZipOutputStream closeEntry

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream closeEntry.

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:com.xpn.xwiki.export.html.HtmlPackager.java

/**
 * Add rendered document to ZIP stream.//  ww w . j a  v a 2  s . c o  m
 * 
 * @param pageName the name (used with {@link com.xpn.xwiki.XWiki#getDocument(String, XWikiContext)}) of the page to
 *            render.
 * @param zos the ZIP output stream.
 * @param context the XWiki context.
 * @param vcontext the Velocity context.
 * @throws XWikiException error when rendering document.
 * @throws IOException error when rendering document.
 */
private void renderDocument(String pageName, ZipOutputStream zos, XWikiContext context,
        VelocityContext vcontext) throws XWikiException, IOException {
    @SuppressWarnings("unchecked")
    EntityReferenceResolver<String> resolver = Utils.getComponent(EntityReferenceResolver.class);
    DocumentReference docReference = new DocumentReference(resolver.resolve(pageName, EntityType.DOCUMENT));
    XWikiDocument doc = context.getWiki().getDocument(docReference, context);

    String zipname = doc.getDocumentReference().getWikiReference().getName();
    for (EntityReference space : doc.getDocumentReference().getSpaceReferences()) {
        zipname += POINT + space.getName();
    }
    zipname += POINT + doc.getDocumentReference().getName();
    String language = doc.getLanguage();
    if (language != null && language.length() != 0) {
        zipname += POINT + language;
    }

    zipname += ".html";

    ZipEntry zipentry = new ZipEntry(zipname);
    zos.putNextEntry(zipentry);

    String originalDatabase = context.getDatabase();
    try {
        context.setDatabase(doc.getDocumentReference().getWikiReference().getName());
        context.setDoc(doc);
        vcontext.put(VCONTEXT_DOC, doc.newDocument(context));
        vcontext.put(VCONTEXT_CDOC, vcontext.get(VCONTEXT_DOC));

        XWikiDocument tdoc = doc.getTranslatedDocument(context);
        context.put(CONTEXT_TDOC, tdoc);
        vcontext.put(VCONTEXT_TDOC, tdoc.newDocument(context));

        String content = context.getWiki().evaluateTemplate("view.vm", context);

        zos.write(content.getBytes(context.getWiki().getEncoding()));
        zos.closeEntry();
    } finally {
        context.setDatabase(originalDatabase);
    }
}

From source file:com.mcleodmoores.mvn.natives.PackageMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().debug("Skipping step");
        return;/*from  w  w  w.  ja  v a 2s .  c  o  m*/
    }
    applyDefaults();
    final MavenProject project = (MavenProject) getPluginContext().get("project");
    final File targetDir = new File(project.getBuild().getDirectory());
    targetDir.mkdirs();
    final File targetFile = new File(targetDir, project.getArtifactId() + ".zip");
    getLog().debug("Writing to " + targetFile);
    final OutputStream output;
    try {
        output = getOutputStreams().open(targetFile);
    } catch (final IOException e) {
        throw new MojoFailureException("Can't write to " + targetFile);
    }
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    if ((new IOCallback<OutputStream, Boolean>(output) {

        @Override
        protected Boolean apply(final OutputStream output) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(output));
            for (final Map.Entry<Source, String> sourceInfo : gatherSources().entrySet()) {
                final Source source = sourceInfo.getKey();
                getLog().info("Processing " + source.getPath() + " into " + sourceInfo.getValue() + " ("
                        + source.getPattern() + ")");
                final File folder = new File(source.getPath());
                final String[] files = folder.list(new PatternFilenameFilter(regex(source.getPattern())));
                if (files != null) {
                    for (final String file : files) {
                        getLog().debug("Adding " + file + " to archive");
                        final ZipEntry entry = new ZipEntry(sourceInfo.getValue() + file);
                        zip.putNextEntry(entry);
                        if ((new IOCallback<InputStream, Boolean>(
                                getInputStreams().open(new File(folder, file))) {

                            @Override
                            protected Boolean apply(final InputStream input) throws IOException {
                                int bytes;
                                while ((bytes = input.read(buffer, 0, buffer.length)) > 0) {
                                    zip.write(buffer, 0, bytes);
                                }
                                return Boolean.TRUE;
                            }

                        }).call(errorLog) != Boolean.TRUE) {
                            return Boolean.FALSE;
                        }
                        zip.closeEntry();
                    }
                } else {
                    getLog().debug("Source folder is empty or does not exist");
                }
            }
            zip.close();
            return Boolean.TRUE;
        }

    }).call(errorLog) != Boolean.TRUE) {
        throw new MojoFailureException("Error writing to " + targetFile);
    }
    project.getArtifact().setFile(targetFile);
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

protected void doUpload() {
    DbAdapter dba = new DbAdapter(this);
    dba.open();/*from   www  .j ava  2  s  . c  o m*/
    Cursor allLogs = dba.fetchAll();
    StringBuilder sb = new StringBuilder();
    allLogs.moveToFirst();
    sb.append("DateTime");
    sb.append(",");
    sb.append("Process");
    sb.append(",");
    sb.append("Type");
    sb.append(",");
    sb.append("Component");
    sb.append(",");
    sb.append("ActionString");
    sb.append(",");
    sb.append("Category");
    sb.append("\n");
    while (!allLogs.isAfterLast()) {
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_TIME)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_PROCESSTAG)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_1)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_2)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_3)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_4)));
        sb.append("\n");
        allLogs.moveToNext();
    }
    dba.close();
    File appDir = getDir("toUpload", MODE_PRIVATE);
    UUID uuid;
    uuid = MainScreen.getOrCreateUUID(this);
    long time = System.currentTimeMillis();
    String basename = uuid.toString() + "_AT_" + time;
    String filename = basename + ".zip.enc";
    File file = new File(appDir, filename);
    FileOutputStream out = null;
    ZipOutputStream outzip = null;
    CipherOutputStream outcipher = null;
    Cipher datac = null;

    File keyfile = new File(appDir, basename + ".key.enc");
    //Log.i("sb length", Integer.toString(sb.length()));
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String email = prefs.getString(MainScreen.EMAIL_KEY, "");
    String emailFilename = "email.txt";
    String csvFilename = "mouflon_log_" + time + ".csv";
    try {
        SecretKey aeskey = generateAESKey();
        //Log.i("secret key", bytearrToString(aeskey.getEncoded()));
        encryptAndWriteAESKey(aeskey, keyfile);
        datac = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        byte[] ivbytes = genIV();
        IvParameterSpec iv = new IvParameterSpec(ivbytes);
        datac.init(Cipher.ENCRYPT_MODE, aeskey, iv);
        out = new FileOutputStream(file);
        out.write(ivbytes);
        //Log.i("iv bytes", bytearrToString(ivbytes));
        outcipher = new CipherOutputStream(out, datac);
        outzip = new ZipOutputStream(outcipher);
        outzip.setMethod(ZipOutputStream.DEFLATED);
        //write the first file (e-mail address)
        String androidVersion = android.os.Build.VERSION.RELEASE;
        String deviceName = android.os.Build.MODEL;
        ZipEntry infoEntry = new ZipEntry("info.txt");
        outzip.putNextEntry(infoEntry);
        outzip.write((androidVersion + "\n" + deviceName).getBytes());
        outzip.closeEntry();
        ZipEntry emailEntry = new ZipEntry(emailFilename);
        outzip.putNextEntry(emailEntry);
        outzip.write(email.getBytes());
        outzip.closeEntry();
        ZipEntry csvEntry = new ZipEntry(csvFilename);
        outzip.putNextEntry(csvEntry);
        outzip.write(sb.toString().getBytes());
        outzip.closeEntry();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outzip.close();
            outcipher.close();
            out.close();
        } catch (IOException e) {
            //ignore
        } catch (NullPointerException ne) {
            //ignore
        }
    }
    //here we actually upload the files 
    String containerFilename = basename + "_container.zip";
    File containerFile = new File(appDir, containerFilename);
    zipUp(containerFile, new File[] { file, keyfile });
    boolean success = uploadFile(containerFile);
    containerFile.delete();
    file.delete();
    keyfile.delete();
    if (success && prefs.getBoolean(MainScreen.DELETE_KEY, true)) {
        DbAdapter dba2 = new DbAdapter(this);
        dba2.open();
        dba2.clearDB();
        dba2.close();
    }
    if (!success && prefs.getBoolean(MainScreen.UPLOAD_KEY, false)) {
        Editor e = prefs.edit();
        e.putInt(MainScreen.DAY_KEY, 6); //reset it to run tomorrow if it fails
        e.commit();
    }
    String s = success ? "Upload complete. Thanks!" : "Upload Failed";
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(UploadFile.this)
            .setSmallIcon(R.drawable.ic_launcher_bw).setContentTitle("Mouflon Recorder").setContentText(s)
            .setAutoCancel(true).setOngoing(false);

    if (mManual) { //only show a notification if we manually upload the file.
        Intent toLaunch = new Intent(UploadFile.this, MainScreen.class);
        //The notification has to go somewhere.
        PendingIntent pi = PendingIntent.getActivity(UploadFile.this, 0, toLaunch,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pi);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, mBuilder.build());
    }
    stopSelf();
}

From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java

private File removeDuplicatesFromJar(File in, List<String> duplicates, Set<String> duplicatesAdded,
        ZipOutputStream duplicateZos, int num) {
    String target = targetDirectory.getAbsolutePath();
    File tmp = new File(target, "unpacked-embedded-jars");
    tmp.mkdirs();/*from  w  w w.  j a  v  a  2 s.  c  o  m*/
    String jarName = String.format("%s-%d.%s", Files.getNameWithoutExtension(in.getName()), num,
            Files.getFileExtension(in.getName()));
    File out = new File(tmp, jarName);

    if (out.exists()) {
        return out;
    } else {
        try {
            out.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a new Jar file
    final FileOutputStream fos;
    final ZipOutputStream jos;
    try {
        fos = new FileOutputStream(out);
        jos = new ZipOutputStream(fos);
    } catch (FileNotFoundException e1) {
        getLog().error(
                "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found");
        return null;
    }

    final ZipFile inZip;
    try {
        inZip = new ZipFile(in);
        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            // If the entry is not a duplicate, copy.
            if (!duplicates.contains(entry.getName())) {
                // copy the entry header to jos
                jos.putNextEntry(entry);
                InputStream currIn = inZip.getInputStream(entry);
                copyStreamWithoutClosing(currIn, jos);
                currIn.close();
                jos.closeEntry();
            }
            //if it is duplicate, check the resource transformers
            else {
                boolean resourceTransformed = false;
                if (transformers != null) {
                    for (ResourceTransformer transformer : transformers) {
                        if (transformer.canTransformResource(entry.getName())) {
                            getLog().info("Transforming " + entry.getName() + " using "
                                    + transformer.getClass().getName());
                            InputStream currIn = inZip.getInputStream(entry);
                            transformer.processResource(entry.getName(), currIn, null);
                            currIn.close();
                            resourceTransformed = true;
                            break;
                        }
                    }
                }
                //if not handled by transformer, add (once) to duplicates jar
                if (!resourceTransformed) {
                    if (!duplicatesAdded.contains(entry.getName())) {
                        duplicatesAdded.add(entry.getName());
                        duplicateZos.putNextEntry(entry);
                        InputStream currIn = inZip.getInputStream(entry);
                        copyStreamWithoutClosing(currIn, duplicateZos);
                        currIn.close();
                        duplicateZos.closeEntry();
                    }
                }
            }
        }
    } catch (IOException e) {
        getLog().error("Cannot removing duplicates : " + e.getMessage());
        return null;
    }

    try {
        inZip.close();
        jos.close();
        fos.close();
    } catch (IOException e) {
        // ignore it.
    }
    getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath());
    return out;
}

From source file:org.betaconceptframework.astroboa.console.export.XmlExportBean.java

public void exportContentObjectList(ContentObjectCriteria contentObjectCriteria, String zipFilename) {

    // run the query
    CmsOutcome<ContentObject> cmsOutcome = astroboaClient.getContentService()
            .searchContentObjects(contentObjectCriteria, ResourceRepresentationType.CONTENT_OBJECT_LIST);

    if (cmsOutcome == null || cmsOutcome.getCount() == 0) {
        JSFUtilities.addMessage(null, "object.action.export.message.nullList", null,
                FacesMessage.SEVERITY_WARN);
        return;//from  w w w.  j  a  va 2  s.c  o m
    }

    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setContentType("application/zip");
        response.setCharacterEncoding("UTF-8");

        zipFilename = generateValidZipFilename(zipFilename);

        response.setHeader("Content-Disposition", "attachment;filename=" + zipFilename + ".zip");

        File tempZip = null;

        FileOutputStream fos = null;

        ZipOutputStream zipOutputStream = null;

        FileInputStream zipFileInputStream = null;

        try {
            tempZip = File.createTempFile(zipFilename, "zip");

            fos = new FileOutputStream(tempZip);
            zipOutputStream = new ZipOutputStream(fos);

            List<ContentObject> results = cmsOutcome.getResults();

            //Keep all filenames created to catch duplicate
            List<String> filenameList = new ArrayList<String>();

            //Allow only the first 500
            int numbreOfContentObjects = 500;

            long now = System.currentTimeMillis();

            for (ContentObject contentObject : results) {

                if (numbreOfContentObjects == 0) {
                    break;
                }

                Calendar created = ((CalendarProperty) contentObject.getCmsProperty("profile.created"))
                        .getSimpleTypeValue();

                String folderPath = DateUtils.format(created, "yyyy/MM/dd");

                long nowXml = System.currentTimeMillis();
                String xml = contentObject.xml(true);

                //Build filename
                String finalName = buildFilename(folderPath, created, contentObject, filenameList);

                filenameList.add(finalName);

                long nowZip = System.currentTimeMillis();
                zipOutputStream.putNextEntry(new ZipEntry(finalName));

                IOUtils.write(xml, zipOutputStream);

                zipOutputStream.closeEntry();

                numbreOfContentObjects--;
            }

            zipOutputStream.close();
            fos.close();

            long nowFileZip = System.currentTimeMillis();
            zipFileInputStream = new FileInputStream(tempZip);
            IOUtils.copy(zipFileInputStream, response.getOutputStream());
            zipFileInputStream.close();

            facesContext.responseComplete();

        } catch (IOException e) {
            logger.error("An error occurred while writing xmlto servlet output stream", e);
            JSFUtilities.addMessage(null, "object.action.export.message.error", null,
                    FacesMessage.SEVERITY_WARN);
        } finally {
            if (fos != null) {
                IOUtils.closeQuietly(fos);
            }
            if (zipOutputStream != null) {
                IOUtils.closeQuietly(zipOutputStream);
            }

            if (zipFileInputStream != null) {
                IOUtils.closeQuietly(zipFileInputStream);
            }

            if (tempZip != null) {
                FileUtils.deleteQuietly(tempZip);
            }
        }

    } else {
        JSFUtilities.addMessage(null, "object.action.export.message.error", null, FacesMessage.SEVERITY_WARN);
    }

}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

private void addDHIS2APIDirectories(File dirObj, ZipOutputStream out, String sourceDirectory) {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (matchingDHIS2APIBackUpStructure(files[i])) {
            if (files[i].isDirectory()) {
                addDHIS2APIDirectories(files[i], out, sourceDirectory);
                continue;
            }//from  w ww . j a va 2  s  . com
            try {
                FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
                String entryPath = (new File(sourceDirectory)).toURI().relativize(files[i].toURI()).getPath();

                System.out.println("Adding: " + entryPath);
                out.putNextEntry(new ZipEntry(entryPath));

                int len;
                while ((len = in.read(tmpBuf)) > 0) {
                    out.write(tmpBuf, 0, len);
                }
                out.closeEntry();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.sakaiproject.metaobj.shared.mgt.impl.StructuredArtifactDefinitionManagerImpl.java

public void writeSADtoZip(StructuredArtifactDefinitionBean bean, ZipOutputStream zos, String path)
        throws IOException {
    // if the path is a directory without an end slash, then add one
    if (!path.endsWith("/") && path.length() > 0) {
        path += "/";
    }//from  ww  w  .j  a va  2 s. c o  m
    ZipEntry definitionFile = new ZipEntry(path + "formDefinition.xml");

    zos.putNextEntry(definitionFile);
    writeSADasXMLtoStream(bean, zos);
    zos.closeEntry();

    ZipEntry schemeFile = new ZipEntry(path + "schema.xsd");

    zos.putNextEntry(schemeFile);
    zos.write(bean.getSchema());
    zos.closeEntry();

    List existingEntries = new ArrayList();
    storeFile(zos, bean.getAlternateCreateXslt(), existingEntries);
    storeFile(zos, bean.getAlternateViewXslt(), existingEntries);

}

From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java

/**
 * @param expFile// ww  w  . j a va2  s  .c o  m
 * @param data
 * @param appRes
 * @throws IOException
 * 
 * writes the contents of a report resource to a zip file. 
 * Currently creates 3 entries: 1) AppResource, 2) AppResource data,
 * and if present, 3)SpReport, SpQuery, SpQueryFields.
 * 
 */
//XXX implement support for subreports
protected void writeSpReportResToZipFile(final File expFile, final String data, final AppResourceIFace appRes)
        throws IOException {
    StringBuilder sb = new StringBuilder();

    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(expFile));

    //the appResource name and metadata
    sb.append("<reportresource name=\"" + appRes.getName() + "\">\r\n");
    sb.append("<metadata > <![CDATA[");
    sb.append(appRes.getMetaData());
    sb.append("]]>");
    sb.append("</metadata>\r\n");
    sb.append("<mimetype > <![CDATA[");
    sb.append(appRes.getMimeType());
    sb.append("]]>");
    sb.append("</mimetype>\r\n");
    sb.append("\r\n</reportresource>\r\n");

    zout.putNextEntry(new ZipEntry("app.xml"));
    byte[] bytes = sb.toString().getBytes();
    zout.write(bytes, 0, bytes.length);
    zout.closeEntry();

    //the data
    zout.putNextEntry(new ZipEntry("data.xml"));
    bytes = data.getBytes();
    zout.write(bytes, 0, bytes.length);
    zout.closeEntry();

    //the spReport
    sb.setLength(0);
    DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
    try {
        SpReport spRep = (SpReport) session
                .getData("from SpReport where appResourceId = " + ((SpAppResource) appRes).getId());
        if (spRep != null) {
            spRep.forceLoad();
            spRep.toXML(sb);
            bytes = sb.toString().getBytes();
            zout.putNextEntry(new ZipEntry("SpReport.xml"));
            zout.write(bytes, 0, bytes.length);
            zout.closeEntry();
        }
    } finally {
        session.close();
    }
    zout.close();
}

From source file:com.meltmedia.cadmium.core.util.WarUtils.java

/**
 * <p>This method updates a template war with the following settings.</p>
 * @param templateWar The name of the template war to pull from the classpath.
 * @param war The path of an external war to update (optional).
 * @param newWarNames The name to give the new war. (note: only the first element of this list is used.)
 * @param repoUri The uri to a github repo to pull content from.
 * @param branch The branch of the github repo to pull content from.
 * @param configRepoUri The uri to a github repo to pull config from.
 * @param configBranch The branch of the github repo to pull config from.
 * @param domain The domain to bind a vHost to.
 * @param context The context root that this war will deploy to.
 * @param secure A flag to set if this war needs to have its contents password protected.
 * @throws Exception/*from  ww w  .j  av  a 2  s .  co  m*/
 */
public static void updateWar(String templateWar, String war, List<String> newWarNames, String repoUri,
        String branch, String configRepoUri, String configBranch, String domain, String context, boolean secure,
        Logger log) throws Exception {
    ZipFile inZip = null;
    ZipOutputStream outZip = null;
    InputStream in = null;
    OutputStream out = null;
    try {
        if (war != null) {
            if (war.equals(newWarNames.get(0))) {
                File tmpZip = File.createTempFile(war, null);
                tmpZip.delete();
                tmpZip.deleteOnExit();
                new File(war).renameTo(tmpZip);
                war = tmpZip.getAbsolutePath();
            }
            inZip = new ZipFile(war);
        } else {
            File tmpZip = File.createTempFile("cadmium-war", "war");
            tmpZip.delete();
            tmpZip.deleteOnExit();
            in = WarUtils.class.getClassLoader().getResourceAsStream(templateWar);
            out = new FileOutputStream(tmpZip);
            FileSystemManager.streamCopy(in, out);
            inZip = new ZipFile(tmpZip);
        }
        outZip = new ZipOutputStream(new FileOutputStream(newWarNames.get(0)));

        ZipEntry cadmiumPropertiesEntry = null;
        cadmiumPropertiesEntry = inZip.getEntry("WEB-INF/cadmium.properties");

        Properties cadmiumProps = updateProperties(inZip, cadmiumPropertiesEntry, repoUri, branch,
                configRepoUri, configBranch);

        ZipEntry jbossWeb = null;
        jbossWeb = inZip.getEntry("WEB-INF/jboss-web.xml");

        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            if (e.getName().equals(cadmiumPropertiesEntry.getName())) {
                storeProperties(outZip, cadmiumPropertiesEntry, cadmiumProps, newWarNames);
            } else if (((domain != null && domain.length() > 0) || (context != null && context.length() > 0))
                    && e.getName().equals(jbossWeb.getName())) {
                updateDomain(inZip, outZip, jbossWeb, domain, context);
            } else if (secure && e.getName().equals("WEB-INF/web.xml")) {
                addSecurity(inZip, outZip, e);
            } else {
                outZip.putNextEntry(e);
                if (!e.isDirectory()) {
                    FileSystemManager.streamCopy(inZip.getInputStream(e), outZip, true);
                }
                outZip.closeEntry();
            }
        }
    } finally {
        if (FileSystemManager.exists("tmp_cadmium-war.war")) {
            new File("tmp_cadmium-war.war").delete();
        }
        try {
            if (inZip != null) {
                inZip.close();
            }
        } catch (Exception e) {
            if (log != null) {
                log.error("Failed to close " + war);
            }
        }
        try {
            if (outZip != null) {
                outZip.close();
            }
        } catch (Exception e) {
            if (log != null) {
                log.error("Failed to close " + newWarNames.get(0));
            }
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
        }
    }

}

From source file:org.betaconceptframework.astroboa.console.export.XmlExportBean.java

public void exportContentObjectSelection(ContentObjectSelectionBean contentObjectSelection,
        String zipFilename) {//from   www.java 2  s.c  o m

    if (contentObjectSelection == null
            || CollectionUtils.isEmpty(contentObjectSelection.getSelectedContentObjects())) {
        JSFUtilities.addMessage(null, "object.action.export.message.nullList", null,
                FacesMessage.SEVERITY_WARN);
        return;
    }

    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setContentType("application/zip");
        response.setCharacterEncoding("UTF-8");

        zipFilename = generateValidZipFilename(zipFilename);

        response.setHeader("Content-Disposition", "attachment;filename=" + zipFilename + ".zip");

        File tempZip = null;

        FileOutputStream fos = null;

        ZipOutputStream zipOutputStream = null;

        FileInputStream zipFileInputStream = null;

        try {
            tempZip = File.createTempFile(zipFilename, "zip");

            fos = new FileOutputStream(tempZip);
            zipOutputStream = new ZipOutputStream(fos);

            List<ContentObjectUIWrapper> results = contentObjectSelection.getSelectedContentObjects();

            //Keep all filenames created to catch duplicate
            List<String> filenameList = new ArrayList<String>();

            //Allow only the first 500
            int numbreOfContentObjects = 500;

            long now = System.currentTimeMillis();

            for (ContentObjectUIWrapper contentObjectUiWraper : results) {

                if (numbreOfContentObjects == 0) {
                    break;
                }
                ContentObject contentObject = contentObjectUiWraper.getContentObject();
                Calendar created = ((CalendarProperty) contentObject.getCmsProperty("profile.created"))
                        .getSimpleTypeValue();

                String folderPath = DateUtils.format(created, "yyyy/MM/dd");

                long nowXml = System.currentTimeMillis();
                String xml = contentObject.xml(false);

                //Build filename
                String finalName = buildFilename(folderPath, created, contentObject, filenameList);

                filenameList.add(finalName);

                long nowZip = System.currentTimeMillis();
                zipOutputStream.putNextEntry(new ZipEntry(finalName));

                IOUtils.write(xml, zipOutputStream);

                zipOutputStream.closeEntry();

                numbreOfContentObjects--;
            }

            zipOutputStream.close();
            fos.close();

            long nowFileZip = System.currentTimeMillis();
            zipFileInputStream = new FileInputStream(tempZip);
            IOUtils.copy(zipFileInputStream, response.getOutputStream());
            zipFileInputStream.close();

            facesContext.responseComplete();

        } catch (IOException e) {
            logger.error("An error occurred while writing xmlto servlet output stream", e);
            JSFUtilities.addMessage(null, "object.action.export.message.error", null,
                    FacesMessage.SEVERITY_WARN);
        } finally {
            if (fos != null) {
                IOUtils.closeQuietly(fos);
            }
            if (zipOutputStream != null) {
                IOUtils.closeQuietly(zipOutputStream);
            }

            if (zipFileInputStream != null) {
                IOUtils.closeQuietly(zipFileInputStream);
            }

            if (tempZip != null) {
                FileUtils.deleteQuietly(tempZip);
            }
        }

    } else {
        JSFUtilities.addMessage(null, "object.action.export.message.error", null, FacesMessage.SEVERITY_WARN);
    }
}