Example usage for java.util.zip ZipOutputStream flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the compressed output stream.

Usage

From source file:org.apache.roller.weblogger.ui.struts2.editor.WeblogExport.java

/**
 * Returns an output stream to the client of all uploaded resource files as
 * a ZIP archive.//w w w. j ava2s.  c  om
 */
public void exportResources() {
    SimpleDateFormat dateFormat;
    dateFormat = new SimpleDateFormat("MMddyyyy'T'HHmmss");

    StringBuilder fileName;
    fileName = new StringBuilder();
    fileName.append(getActionWeblog().getHandle());
    fileName.append("-resources-");
    fileName.append(dateFormat.format(System.currentTimeMillis()));
    fileName.append(".zip");

    if (!response.isCommitted()) {
        response.reset();

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName.toString() + "\"");

        try {
            MediaFileManager fmgr = WebloggerFactory.getWeblogger().getMediaFileManager();

            List<MediaFile> resources = new ArrayList<MediaFile>();

            // Load the contents of any sub-directories
            for (MediaFileDirectory mdir : fmgr.getMediaFileDirectories(getActionWeblog())) {
                loadResources(resources, mdir);
            }

            // Load the files at the root of the specific upload directory
            loadResources(resources, null);

            // Create a buffer for reading the files
            byte[] buffer;
            buffer = new byte[1024];

            ServletOutputStream servletOutput;
            servletOutput = response.getOutputStream();

            ZipOutputStream zipOutput;
            zipOutput = new ZipOutputStream(servletOutput);

            for (MediaFile resource : resources) {
                InputStream input;
                input = resource.getInputStream();

                // Add a new ZIP entry to output stream
                zipOutput.putNextEntry(new ZipEntry(resource.getPath()));

                int length;
                while ((length = input.read(buffer)) > 0) {
                    zipOutput.write(buffer, 0, length);
                }

                // Cleanup the entry
                input.close();
                zipOutput.closeEntry();
            }

            // Cleanup the output stream
            zipOutput.flush();
            zipOutput.close();
        } catch (Exception e) {
            log.error("Error exporting resources: " + e.getMessage());
        }
    }
}

From source file:edu.harvard.iq.dvn.core.study.StudyFileServiceBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void addIngestedFiles(Long studyId, String versionNote, List fileBeans, Long userId) {
    // if no files, then just return
    if (fileBeans.isEmpty()) {
        return;//from  w w  w  .j  a v  a 2 s.  c  om
    }

    // first some initialization
    StudyVersion studyVersion = null;
    Study study = null;
    MD5Checksum md5Checksum = new MD5Checksum();

    study = em.find(Study.class, studyId);
    studyVersion = study.getEditVersion();
    if (studyVersion.getId() == null) {
        em.persist(studyVersion);
        em.flush();
    }

    studyVersion.setVersionNote(versionNote);

    VDCUser user = userService.find(userId);

    File newDir = new File(FileUtil.getStudyFileDir(),
            study.getAuthority() + File.separator + study.getStudyId());
    if (!newDir.exists()) {
        newDir.mkdirs();
    }

    // now iterate through fileBeans
    Iterator iter = fileBeans.iterator();
    while (iter.hasNext()) {
        StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();

        // for now the logic is if the DSB does not return a file, don't copy
        // over anything; this is to cover the situation with the Ingest servlet
        // that uses takes a control card file to add a dataTable to a prexisting
        // file; this will have to change if we do this two files method at the
        // time of the original upload
        // (TODO: figure out what this comment means - ? - L.A.)
        // (is this some legacy thing? - it's talking about "ingest servlet"...)
        // (did we ever have a mechanism for adding a data table to an existing
        //  tab file?? - that's actually kinda cool)

        StudyFile f = fileBean.getStudyFile();

        // So, if there is a file: let's move it to its final destination
        // in the study directory. 
        //
        // First, if it's a subsettable or network, or any other
        // kind potentially, that gets transformed on ingest: 

        File newIngestedLocationFile = null;

        if (fileBean.getIngestedSystemFileLocation() != null) {

            String originalFileType = f.getFileType();

            // 1. move ingest-created file:

            File tempIngestedFile = new File(fileBean.getIngestedSystemFileLocation());
            newIngestedLocationFile = new File(newDir, f.getFileSystemName());
            try {
                FileUtil.copyFile(tempIngestedFile, newIngestedLocationFile);
                tempIngestedFile.delete();
                if (f instanceof TabularDataFile) {
                    f.setFileType("text/tab-separated-values");
                }
                f.setFileSystemLocation(newIngestedLocationFile.getAbsolutePath());

            } catch (IOException ex) {
                throw new EJBException(ex);
            }
            // 1b. If this is a NetworkDataFile,  move the SQLite file from the temp Ingested location to the system location
            if (f instanceof NetworkDataFile) {
                File tempSQLDataFile = new File(tempIngestedFile.getParent(), FileUtil
                        .replaceExtension(tempIngestedFile.getName(), NetworkDataServiceBean.SQLITE_EXTENSION));
                File newSQLDataFile = new File(newDir,
                        f.getFileSystemName() + "." + NetworkDataServiceBean.SQLITE_EXTENSION);

                File tempNeo4jDir = new File(tempIngestedFile.getParent(), FileUtil
                        .replaceExtension(tempIngestedFile.getName(), NetworkDataServiceBean.NEO4J_EXTENSION));
                File newNeo4jDir = new File(newDir,
                        f.getFileSystemName() + "." + NetworkDataServiceBean.NEO4J_EXTENSION);

                try {
                    FileUtil.copyFile(tempSQLDataFile, newSQLDataFile);
                    FileUtils.copyDirectory(tempNeo4jDir, newNeo4jDir);
                    tempSQLDataFile.delete();
                    FileUtils.deleteDirectory(tempNeo4jDir);
                    f.setOriginalFileType(originalFileType);

                } catch (IOException ex) {
                    throw new EJBException(ex);
                }
            }

            // 2. also move original file for archiving
            File tempOriginalFile = new File(fileBean.getTempSystemFileLocation());
            File newOriginalLocationFile = new File(newDir, "_" + f.getFileSystemName());
            try {
                if (fileBean.getControlCardSystemFileLocation() != null
                        && fileBean.getControlCardType() != null) {
                    // 2a. For the control card-based ingests (SPSS and DDI), we save
                    // a zipped bundle of both the card and the raw data file
                    // (TAB-delimited or CSV):

                    FileInputStream instream = null;
                    byte[] dataBuffer = new byte[8192];

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

                    // First, the control card:

                    File controlCardFile = new File(fileBean.getControlCardSystemFileLocation());

                    ZipEntry ze = new ZipEntry(controlCardFile.getName());
                    instream = new FileInputStream(controlCardFile);
                    zout.putNextEntry(ze);

                    int k = 0;
                    while ((k = instream.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, k);
                        zout.flush();
                    }

                    instream.close();

                    // And then, the data file:

                    ze = new ZipEntry(tempOriginalFile.getName());
                    instream = new FileInputStream(tempOriginalFile);
                    zout.putNextEntry(ze);

                    while ((k = instream.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, k);
                        zout.flush();
                    }

                    instream.close();

                    zout.close();

                    // and control card file can be deleted now:
                    controlCardFile.delete();

                    // Mime types: 
                    // These are custom, made-up types, used to identify the 
                    // type of the source data:

                    if (fileBean.getControlCardType().equals("spss")) {
                        f.setOriginalFileType("application/x-dvn-csvspss-zip");
                    } else if (fileBean.getControlCardType().equals("ddi")) {
                        f.setOriginalFileType("application/x-dvn-tabddi-zip");
                    } else {
                        logger.info("WARNING: unknown control card-based Ingest type? -- "
                                + fileBean.getControlCardType());
                        f.setOriginalFileType(originalFileType);
                    }
                    f.setMd5(md5Checksum.CalculateMD5(tempOriginalFile.getAbsolutePath()));

                } else {
                    // 2b. Otherwise, simply store the data that was used for
                    // ingest as the original:

                    FileUtil.copyFile(tempOriginalFile, newOriginalLocationFile);
                    f.setOriginalFileType(originalFileType);
                    f.setMd5(md5Checksum.CalculateMD5(newOriginalLocationFile.getAbsolutePath()));
                }
                tempOriginalFile.delete();
            } catch (IOException ex) {
                throw new EJBException(ex);
            }
        } else if (f instanceof SpecialOtherFile) {
            // "Special" OtherFiles are still OtherFiles; we just add the file
            // uploaded by the user to the study as is:

            File tempIngestedFile = new File(fileBean.getTempSystemFileLocation());
            newIngestedLocationFile = new File(newDir, f.getFileSystemName());
            try {
                FileUtil.copyFile(tempIngestedFile, newIngestedLocationFile);
                tempIngestedFile.delete();
                f.setFileSystemLocation(newIngestedLocationFile.getAbsolutePath());
                f.setMd5(md5Checksum.CalculateMD5(newIngestedLocationFile.getAbsolutePath()));
            } catch (IOException ex) {
                throw new EJBException(ex);
            }
        }

        // Finally, if the file was copied sucessfully, 
        // attach file to study version and study

        if (newIngestedLocationFile != null && newIngestedLocationFile.exists()) {

            fileBean.getFileMetadata().setStudyVersion(studyVersion);
            studyVersion.getFileMetadatas().add(fileBean.getFileMetadata());
            fileBean.getStudyFile().setStudy(study);
            // don't need to set study side, since we're no longer using persistence cache
            //study.getStudyFiles().add(fileBean.getStudyFile());
            //fileBean.addFiletoStudy(study);

            em.persist(fileBean.getStudyFile());
            em.persist(fileBean.getFileMetadata());

        } else {
            //fileBean.getStudyFile().setSubsettable(true);
            em.merge(fileBean.getStudyFile());
        }
    }
    // calcualte UNF for study version
    try {
        studyVersion.getMetadata().setUNF(new DSBWrapper().calculateUNF(studyVersion));
    } catch (IOException e) {
        throw new EJBException("Could not calculate new study UNF");
    }

    studyService.saveStudyVersion(studyVersion, user.getId());
}

From source file:com.xpn.xwiki.plugin.packaging.Package.java

public String export(OutputStream os, XWikiContext context) throws IOException, XWikiException {
    if (this.files.size() == 0) {
        return "No Selected file";
    }//from  w w  w  .  j a  v a 2  s .c  o m

    ZipOutputStream zos = new ZipOutputStream(os);
    for (int i = 0; i < this.files.size(); i++) {
        DocumentInfo docinfo = this.files.get(i);
        XWikiDocument doc = docinfo.getDoc();
        addToZip(doc, zos, this.withVersions, context);
    }
    addInfosToZip(zos, context);
    zos.finish();
    zos.flush();

    return "";
}

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

/**
 * Apply export and create the ZIP package.
 * //from   w  w w.j a  va 2  s  . c  o m
 * @param context the XWiki context used to render pages.
 * @throws IOException error when creating the package.
 * @throws XWikiException error when render the pages.
 */
public void export(XWikiContext context) throws IOException, XWikiException {
    context.getResponse().setContentType("application/zip");
    context.getResponse().addHeader("Content-disposition",
            "attachment; filename=" + Util.encodeURI(this.name, context) + ".zip");
    context.setFinished(true);

    ZipOutputStream zos = new ZipOutputStream(context.getResponse().getOutputStream());

    File dir = context.getWiki().getTempDirectory(context);
    File tempdir = new File(dir, RandomStringUtils.randomAlphanumeric(8));
    tempdir.mkdirs();
    File attachmentDir = new File(tempdir, "attachment");
    attachmentDir.mkdirs();

    // Create custom URL factory
    ExportURLFactory urlf = new ExportURLFactory();

    // Render pages to export
    renderDocuments(zos, tempdir, urlf, context);

    // Add required skins to ZIP file
    for (String skinName : urlf.getNeededSkins()) {
        addSkinToZip(skinName, zos, urlf.getExportedSkinFiles(), context);
    }

    // add "resources" folder
    File file = new File(context.getWiki().getEngineContext().getRealPath("/resources/"));
    addDirToZip(file, zos, "resources" + ZIPPATH_SEPARATOR, urlf.getExportedSkinFiles());

    // Add attachments and generated skin files files to ZIP file
    addDirToZip(tempdir, zos, "", null);

    zos.setComment(this.description);

    // Finish ZIP file
    zos.finish();
    zos.flush();

    // Delete temporary directory
    deleteDirectory(tempdir);
}

From source file:cross.io.misc.WorkflowZipper.java

private void addZipEntry(final int bufsize, final ZipOutputStream zos, final byte[] input_buffer,
        final File file, final HashSet<String> zipEntries) throws IOException {
    log.debug("Adding zip entry for file {}", file);
    if (file.exists() && file.isFile()) {
        // Use the file name for the ZipEntry name.
        final ZipEntry zip_entry = new ZipEntry(file.getName());
        if (zipEntries.contains(file.getName())) {
            log.info("Skipping duplicate zip entry {}", file.getName());
            return;
        } else {/*from  w w w . j a v a 2  s.  co  m*/
            zipEntries.add(file.getName());
        }
        zos.putNextEntry(zip_entry);

        // Create a buffered input stream from the file stream.
        final FileInputStream in = new FileInputStream(file);
        // Read from source into buffer and write, thereby compressing
        // on the fly
        try (BufferedInputStream source = new BufferedInputStream(in, bufsize)) {
            // Read from source into buffer and write, thereby compressing
            // on the fly
            int len = 0;
            while ((len = source.read(input_buffer, 0, bufsize)) != -1) {
                zos.write(input_buffer, 0, len);
            }
            zos.flush();
        }
        zos.closeEntry();
    } else {
        log.warn("Skipping nonexistant file or directory {}", file);
    }
}

From source file:org.structr.core.graph.SyncCommand.java

private static void exportDirectory(ZipOutputStream zos, File dir, String path, Set<String> filesToInclude)
        throws IOException {

    final String nestedPath = path + dir.getName() + "/";
    final ZipEntry dirEntry = new ZipEntry(nestedPath);
    zos.putNextEntry(dirEntry);//  www.java2 s .co  m

    final File[] contents = dir.listFiles();
    if (contents != null) {

        for (File file : contents) {

            if (file.isDirectory()) {

                exportDirectory(zos, file, nestedPath, filesToInclude);

            } else {

                final String fileName = file.getName();
                final String relativePath = nestedPath + fileName;
                boolean includeFile = true;

                if (filesToInclude != null) {

                    includeFile = false;

                    if (filesToInclude.contains(fileName)) {

                        includeFile = true;
                    }
                }

                if (includeFile) {

                    // create ZIP entry
                    ZipEntry fileEntry = new ZipEntry(relativePath);
                    fileEntry.setTime(file.lastModified());
                    zos.putNextEntry(fileEntry);

                    // copy file into stream
                    FileInputStream fis = new FileInputStream(file);
                    IOUtils.copy(fis, zos);
                    fis.close();

                    // flush and close entry
                    zos.flush();
                    zos.closeEntry();
                }
            }
        }
    }

    zos.closeEntry();

}

From source file:cross.io.misc.WorkflowZipper.java

private void addRelativeZipEntry(final int bufsize, final ZipOutputStream zos, final byte[] input_buffer,
        final String relativePath, final File file, final HashSet<String> zipEntries) throws IOException {
    log.debug("Adding zip entry for file {}", file);
    if (file.exists() && file.isFile()) {
        // Use the file name for the ZipEntry name.
        final ZipEntry zip_entry = new ZipEntry(relativePath);
        if (zipEntries.contains(relativePath)) {
            log.info("Skipping duplicate zip entry {}", relativePath + "/" + file.getName());
            return;
        } else {/*from w w w .ja v  a  2  s  .c  o m*/
            zipEntries.add(relativePath);
        }
        zos.putNextEntry(zip_entry);

        // Create a buffered input stream from the file stream.
        final FileInputStream in = new FileInputStream(file);
        // Read from source into buffer and write, thereby compressing
        // on the fly
        try (BufferedInputStream source = new BufferedInputStream(in, bufsize)) {
            // Read from source into buffer and write, thereby compressing
            // on the fly
            int len = 0;
            while ((len = source.read(input_buffer, 0, bufsize)) != -1) {
                zos.write(input_buffer, 0, len);
            }
            zos.flush();
        }
        zos.closeEntry();
    } else {
        log.warn("Skipping nonexistant file or directory {}", file);
    }
}

From source file:com.flexive.core.storage.GenericDivisionExporter.java

/**
 * Dump a single file to a zip output stream
 *
 * @param zip  zip output stream/*from w w  w .j av  a 2s  .c  o  m*/
 * @param file the file to dump
 * @param path absolute base directory path (will be stripped in the archive from file)
 * @throws IOException on errors
 */
private void dumpFile(ZipOutputStream zip, File file, String path) throws IOException {
    if (file.isDirectory()) {
        for (File f : file.listFiles())
            dumpFile(zip, f, path);
        return;
    }
    ZipEntry ze = new ZipEntry(FOLDER_FS_BINARY + file.getAbsolutePath().substring(path.length()));
    zip.putNextEntry(ze);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte[] buffer = new byte[4096];
        int read;
        while ((read = fis.read(buffer)) != -1)
            zip.write(buffer, 0, read);
    } finally {
        if (fis != null)
            fis.close();
    }
    zip.closeEntry();
    zip.flush();
}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnRGraphServiceImpl.java

private void addZipEntry(RConnection c, ZipOutputStream zout, String inputFileName, String outputFileName)
        throws IOException {
    RFileInputStream tmpin = c.openFile(inputFileName);
    byte[] dataBuffer = new byte[8192];
    int i = 0;//from  w  ww  .jav a  2  s .  c  o  m

    ZipEntry e = new ZipEntry(outputFileName);
    zout.putNextEntry(e);

    while ((i = tmpin.read(dataBuffer)) > 0) {
        zout.write(dataBuffer, 0, i);
        zout.flush();
    }
    tmpin.close();
    zout.closeEntry();
}