Example usage for java.util.zip ZipOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing the contents of the ZIP output stream without closing the underlying stream.

Usage

From source file:com.vmware.appfactory.recipe.controller.RecipeApiController.java

private void writeToZip(OutputStream os, Recipe recipe) throws IOException {
    InputStream is = null;/*from   w  ww .j av  a2  s  . c om*/
    ZipOutputStream zos = null;

    try {
        zos = new ZipOutputStream(os);
        _log.debug("Opened a ZIP stream");

        /* Write recipe into the ZIP stream */
        String jsonFileName = toFileName(recipe.getName() + AfConstant.RECIPE_FILE_EXTENSION);
        _log.debug("Writing the JSON file ({})", jsonFileName);
        zos.putNextEntry(new ZipEntry(jsonFileName));
        String json = EXPORT_OBJECT_MAPPER.writeValueAsString(recipe);
        zos.write(json.getBytes());

        /* Copy all payload files into the temporary directory */
        for (RecipeFile file : recipe.getFiles()) {
            if (file.getPath() != null) {
                try {
                    writeRecipeFileToZip(recipe, file, zos);
                } catch (IOException ex) {
                    throw new IOException("Failed to export recipe file " + file.getURI().toString(), ex);
                }
            }
        }

        /* Done with the ZIP file */
        zos.finish();
        zos = null;
    } catch (IOException ex) {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(is);
        throw ex;
    }
}

From source file:org.dspace.app.itemexport.ItemExportServiceImpl.java

@Override
public void zip(String strSource, String target) throws Exception {
    ZipOutputStream cpZipOutputStream = null;
    String tempFileName = target + "_tmp";
    try {/* www  .j a  va  2s. c  om*/
        File cpFile = new File(strSource);
        if (!cpFile.isFile() && !cpFile.isDirectory()) {
            return;
        }
        File targetFile = new File(tempFileName);
        if (!targetFile.createNewFile()) {
            log.warn("Target file already exists: " + targetFile.getName());
        }

        FileOutputStream fos = new FileOutputStream(tempFileName);
        cpZipOutputStream = new ZipOutputStream(fos);
        cpZipOutputStream.setLevel(9);
        zipFiles(cpFile, strSource, tempFileName, cpZipOutputStream);
        cpZipOutputStream.finish();
        cpZipOutputStream.close();
        cpZipOutputStream = null;

        // Fix issue on Windows with stale file handles open before trying to delete them
        System.gc();

        deleteDirectory(cpFile);
        if (!targetFile.renameTo(new File(target))) {
            log.error("Unable to rename file");
        }
    } finally {
        if (cpZipOutputStream != null) {
            cpZipOutputStream.close();
        }
    }
}

From source file:org.olat.ims.qti.qpool.QTIPoolWordExport.java

private void exportTest(List<QuestionItemFull> fullItems, OutputStream out, boolean withResponses) {
    ZipOutputStream zout = null;
    try {/*w  w  w. j av a2s. c  om*/
        OpenXMLDocument document = new OpenXMLDocument();
        document.setDocumentHeader("");
        Translator translator = Util.createPackageTranslator(QTIWordExport.class, locale);

        for (Iterator<QuestionItemFull> itemIt = fullItems.iterator(); itemIt.hasNext();) {
            QuestionItemFull fullItem = itemIt.next();

            String dir = fullItem.getDirectory();
            VFSContainer container = qpoolFileStorage.getContainer(dir);
            document.setMediaContainer(container);

            VFSItem rootItem = container.resolve(fullItem.getRootFilename());
            Item item = QTIEditHelper.readItemXml((VFSLeaf) rootItem);
            if (item.isAlient()) {
                QTIWordExport.renderAlienItem(item, document, translator);
            } else {
                QTIWordExport.renderItem(item, document, withResponses, translator);
            }
            if (itemIt.hasNext()) {
                document.appendPageBreak();
            }
        }

        zout = new ZipOutputStream(out);
        zout.setLevel(9);

        OpenXMLDocumentWriter writer = new OpenXMLDocumentWriter();
        writer.createDocument(zout, document);
    } catch (Exception e) {
        log.error("", e);
    } finally {
        if (zout != null) {
            try {
                zout.finish();
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java

public static boolean ZipAndStreamFiles(OutputStream out, List<String> fileNames, String dirPath) {

    File dir_file = new File(dirPath);
    int dir_l = dir_file.getAbsolutePath().length();
    ZipOutputStream zipout = new ZipOutputStream(out);
    zipout.setLevel(1);//from   w w w  .  j a  va2  s. c  o  m
    for (int i = 0; i < fileNames.size(); i++) {
        File f = (File) new File(dirPath + fileNames.get(i));
        if (f.canRead()) {
            log.debug("Adding file: " + f.getAbsolutePath());
            try {
                zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1)));
            } catch (Exception e) {
                log.warning("Error adding to zip file", e);
                return false;
            }
            BufferedInputStream fr;
            try {
                fr = new BufferedInputStream(new FileInputStream(f));

                byte buffer[] = new byte[0xffff];
                int b;
                while ((b = fr.read(buffer)) != -1)
                    zipout.write(buffer, 0, b);

                fr.close();
                zipout.closeEntry();

            } catch (Exception e) {
                log.warning("Error closing zip file", e);
                return false;
            }
        }
    }

    try {
        zipout.finish();
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;

}

From source file:org.panbox.desktop.linux.dbus.PanboxInterfaceImpl.java

@Override
public byte backupIdentity() {
    logger.debug("[DBUS] backupIdentity()");

    byte ret = StatusCode.DBUS_OK;

    File confDir = new File(Settings.getInstance().getConfDir());
    String backupPath = confDir.getParent() + File.separator + ".pbbackup";
    File backupDir = new File(backupPath);

    if (!backupDir.exists()) {
        backupDir.mkdir();/*from  ww w. ja  va2  s. c  om*/
    }

    Calendar cal = Calendar.getInstance();

    String datetime = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH))
            + String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "_" + String.valueOf(cal.get(Calendar.MINUTE))
            + "-" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "-"
            + String.valueOf(cal.get(Calendar.SECOND));
    String outputFileName = backupDir.getPath() + File.separator + datetime + ".pbbak";

    List<String> filesToZip = new ArrayList<String>();

    try {
        IShareManager shareMgr = ShareManagerImpl.getInstance();

        File[] confFiles = confDir.listFiles();
        for (File f : confFiles) {
            filesToZip.add(f.getAbsolutePath());
        }

        List<String> installedShareNames = shareMgr.getInstalledShares();

        List<PanboxShare> installedShares = new ArrayList<PanboxShare>();
        for (String shareName : installedShareNames) {
            PanboxShare share = shareMgr.getShareForName(shareName);
            installedShares.add(share);
        }

        for (PanboxShare share : installedShares) {
            File f = new File(share.getPath() + ".panbox/");
            File[] files = f.listFiles();
            for (File file : files) {
                filesToZip.add(file.getAbsolutePath());
            }
        }

        FileOutputStream fos = new FileOutputStream(outputFileName);
        ZipOutputStream zos = new ZipOutputStream(fos);
        zos.setLevel(9);

        for (String ftz : filesToZip) {

            File fileToZip = new File(ftz);

            if (fileToZip.exists()) {
                ZipEntry ze = new ZipEntry(fileToZip.getAbsolutePath());
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(fileToZip.getPath());

                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
        }
        zos.finish();
        fos.close();

    } catch (Exception e) {
        ret = StatusCode.getAndLog(logger, e);
    }

    return ret;
}

From source file:oscar.form.study.HSFO.pageUtil.XMLTransferUtil.java

public byte[] zipCompress(String fileName, byte[] input) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    try {/*from  w w  w. ja va 2s. co m*/
        zos.putNextEntry(new ZipEntry(fileName));
        zos.write(input);
        zos.closeEntry();
        zos.finish();

        return baos.toByteArray();
    } finally {
        zos.close();
    }
}

From source file:org.zeroturnaround.zip.ZipUtil.java

/**
 * Copies an existing ZIP file and transforms the given entries in it.
 *
 * @param is//from w  w  w  .j  ava2s  .  com
 *          a ZIP input stream.
 * @param entries
 *          ZIP entry transformers.
 * @param os
 *          a ZIP output stream.
 * @return <code>true</code> if at least one entry was replaced.
 */
public static boolean transformEntries(InputStream is, ZipEntryTransformerEntry[] entries, OutputStream os) {
    if (log.isDebugEnabled())
        log.debug("Copying '" + is + "' to '" + os + "' and transforming entries " + Arrays.asList(entries)
                + ".");

    try {
        ZipOutputStream out = new ZipOutputStream(os);
        TransformerZipEntryCallback action = new TransformerZipEntryCallback(entries, out);
        iterate(is, action);
        // Finishes writing the contents of the ZIP output stream without closing
        // the underlying stream.
        out.finish();
        return action.found();
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    }
}

From source file:org.olat.ims.qti.export.QTIWordExport.java

private void exportTest(String header, OutputStream out, boolean withResponses) {
    ZipOutputStream zout = null;
    try {/*from  w ww . j  a va  2s .c o m*/
        OpenXMLDocument document = new OpenXMLDocument();
        document.setMediaContainer(mediaContainer);
        document.setDocumentHeader(header);

        Translator translator = Util.createPackageTranslator(QTIWordExport.class, locale,
                Util.createPackageTranslator(QTIEditorMainController.class, locale));

        Assessment assessment = rootNode.getAssessment();
        renderAssessment(assessment, document, translator);

        for (Section section : assessment.getSections()) {
            renderSection(section, document);
            List<Item> items = section.getItems();
            for (Iterator<Item> itemIt = items.iterator(); itemIt.hasNext();) {
                Item item = itemIt.next();
                if (item.isAlient()) {
                    renderAlienItem(item, document, translator);
                } else {
                    renderItem(item, document, withResponses, translator);
                }
                if (itemIt.hasNext()) {
                    document.appendPageBreak();
                }
            }
        }

        zout = new ZipOutputStream(out);
        zout.setLevel(9);

        OpenXMLDocumentWriter writer = new OpenXMLDocumentWriter();
        writer.createDocument(zout, document);
    } catch (Exception e) {
        log.error("", e);
    } finally {
        if (zout != null) {
            try {
                zout.finish();
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }
}

From source file:org.obiba.mica.file.service.FileSystemService.java

/**
 * Creates a zipped file of the path and it's subdirectories/files
 *
 * @param path/* w w w  .j ava2 s .c o m*/
 * @param publishedFS
 * @return
   */
public String zipDirectory(String path, boolean publishedFS) {
    List<AttachmentState> attachmentStates = getAllowedStates(path, publishedFS);
    String zipName = Paths.get(path).getFileName().toString() + ".zip";

    FileOutputStream fos = null;

    try {
        byte[] buffer = new byte[1024];

        fos = tempFileService.getFileOutputStreamFromFile(zipName);

        ZipOutputStream zos = new ZipOutputStream(fos);

        for (AttachmentState state : attachmentStates) {
            if (FileUtils.isDirectory(state)) {
                zos.putNextEntry(new ZipEntry(relativizePaths(path, state.getFullPath()) + File.separator));
            } else {
                zos.putNextEntry(new ZipEntry(relativizePaths(path, state.getFullPath())));

                InputStream in = fileStoreService
                        .getFile(publishedFS ? state.getPublishedAttachment().getFileReference()
                                : state.getAttachment().getFileReference());

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }

                in.close();
            }

            zos.closeEntry();
        }

        zos.finish();
    } catch (IOException ioe) {
        Throwables.propagate(ioe);
    } finally {
        IOUtils.closeQuietly(fos);
    }

    return zipName;
}

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

/**
 * This method will export a form into a stream.  It has the ability to turn off checking
 * for the export form permission.//from  ww w. j  a  va 2  s . c  om
 * @param formId String
 * @param os OutputStream
 * @param checkPermission boolean
 * @throws IOException
 */
public void packageFormForExport(String formId, OutputStream os, boolean checkPermission) throws IOException {
    if (checkPermission) {
        getAuthzManager().checkPermission(SharedFunctionConstants.EXPORT_ARTIFACT_DEF, getToolId());
    }

    CheckedOutputStream checksum = new CheckedOutputStream(os, new Adler32());
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(checksum));

    StructuredArtifactDefinitionBean bean = loadHome(formId);
    writeSADtoZip(bean, zos, "");

    zos.finish();
    zos.flush();
}