Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:be.fedict.eid.applet.service.signer.odf.AbstractODFSignatureService.java

private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
    LOG.debug("output signed open document");
    OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
    if (null == signedOdfOutputStream) {
        throw new NullPointerException("signedOpenDocumentOutputStream is null");
    }// w  ww .  ja  v a2  s .  c o  m
    /*
     * Copy the original ODF content to the signed ODF package.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();
    /*
     * Add the ODF XML signature file to the signed ODF package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

/**
 * //from w  ww.j  ava2  s  . co  m
 * @param path
 */
public void createZipFile(String path) {
    File dir = new File(path);
    String[] list = dir.list();
    String name = path.substring(path.lastIndexOf("/"), path.length());
    String _path;

    if (!dir.canRead() || !dir.canWrite())
        return;

    int len = list.length;

    if (path.charAt(path.length() - 1) != '/')
        _path = path + "/";
    else
        _path = path;

    try {
        ZipOutputStream zip_out = new ZipOutputStream(
                new BufferedOutputStream(new FileOutputStream(_path + name + ".zip"), BUFFER));

        for (int i = 0; i < len; i++)
            zip_folder(new File(_path + list[i]), zip_out);

        zip_out.close();

    } catch (FileNotFoundException e) {
        Log.e("File not found", e.getMessage());

    } catch (IOException e) {
        Log.e("IOException", e.getMessage());
    }
}

From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java

/**
 * Exports all projects into separate xml files and adds them to a zip archive.  
 * @return null Always returns null, so user stays on same screen after action performed
 */// w w w  . j  a v a2s . c o m
public String exportAllProjectsToZip() {
    List<PlanProperties> ppList = em.createQuery("select p from PlanProperties p").getResultList();

    if (!ppList.isEmpty()) {
        log.debug("number of plans to export: " + ppList.size());
        String filename = "allprojects.zip";

        String exportPath = OS.getTmpPath() + "export" + System.currentTimeMillis() + "/";
        new File(exportPath).mkdirs();

        String binarydataTempPath = exportPath + "binarydata/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();

        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(exportPath + filename));
            ZipOutputStream zipOut = new ZipOutputStream(out);

            for (PlanProperties pp : ppList) {
                log.debug("EXPORTING: " + pp.getName());
                ZipEntry zipAdd = new ZipEntry(String.format("%1$03d", pp.getId()) + "-"
                        + FileUtils.makeFilename(pp.getName()) + ".xml");
                zipOut.putNextEntry(zipAdd);
                // export the complete project, including binary data
                exportComplete(pp.getId(), zipOut, binarydataTempPath);
                zipOut.closeEntry();
            }
            zipOut.close();
            out.close();
            new File(exportPath + "finished.info").createNewFile();

            FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "Export was written to: " + exportPath);
            log.info("Export was written to: " + exportPath);
        } catch (IOException e) {
            FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                    "An error occured while generating the export file.");
            log.error("An error occured while generating the export file.", e);
            File errorInfo = new File(exportPath + "error.info");
            try {
                Writer w = new FileWriter(errorInfo);
                w.write("An error occured while generating the export file:");
                w.write(e.getMessage());
                w.close();
            } catch (IOException e1) {
                log.error("Could not write error file.");
            }

        } finally {
            // remove all binary temp files
            OS.deleteDirectory(binarydataTempDir);
        }

    } else {
        FacesMessages.instance().add("No Projects found!");
    }
    return null;
}

From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.zipFile = this.temporaryFolder.newFile("zipfile.zip");
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(this.zipFile));
    try {/*from   w  w  w  .j ava 2 s  . c o  m*/
        zipOutputStream.putNextEntry(new ZipEntry("/a/b/c.txt"));
        zipOutputStream.write("c".getBytes());
        zipOutputStream.putNextEntry(new ZipEntry("/d/"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/e/"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/f/"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/f/g.txt"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/f/h/"));
        zipOutputStream.write("g".getBytes());
    } finally {
        zipOutputStream.close();
    }
    this.zip = new ZipArchive(new LocalFolder(this.zipFile.getParentFile()).getFile(this.zipFile.getName()));
}

From source file:com.ephesoft.gxt.admin.server.ExportDocumentTypeDownloadServlet.java

/**
 * This API is used to process request to export the documents .
 * //from   w  w  w . ja  v  a 2 s .co  m
 * @param docTypeList {@link List<{@link DocumentType}>} selected document type list to export.
 * @param resp {@link HttpServletResponse}.
 * @return
 */
private void process(final List<DocumentType> docTypeList, final HttpServletResponse resp) throws IOException {

    final BatchSchemaService bSService = this.getSingleBeanOfType(BatchSchemaService.class);
    final String exportSerDirPath = bSService.getBatchExportFolderLocation();
    final BatchClass batchClass = docTypeList.get(0).getBatchClass();

    final String zipFileName = batchClass.getIdentifier() + "_" + "DocumentTypes";
    final String copiedParentFolderPath = exportSerDirPath + File.separator + zipFileName;
    final File copiedFd = createDirectory(copiedParentFolderPath);
    // final boolean isIMFdSelected = checkBaseDirectorySelection("image-classification-sample",
    // bSService.getImagemagickBaseFolderName());
    // final boolean isSSFdSelected = checkBaseDirectorySelection("lucene-search-classification-sample",
    // bSService.getSearchSampleName());
    final boolean isIMFdSelected = true;
    final boolean isSSFdSelected = true;
    processDocumentTypes(docTypeList, batchClass, bSService, isIMFdSelected, isSSFdSelected, resp);
    resp.setContentType("application/x-zip\r\n");
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
    ServletOutputStream out = null;
    ZipOutputStream zout = null;
    try {
        out = resp.getOutputStream();
        zout = new ZipOutputStream(out);
        FileUtils.zipDirectory(copiedParentFolderPath, zout, zipFileName);
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (final IOException e) {
        // Unable to create the temporary export file(s)/folder(s)
        log.error("Error occurred while creating the zip file." + e, e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
    } finally {
        // clean up code
        if (zout != null) {
            zout.close();
        }
        if (out != null) {
            out.flush();
        }
        FileUtils.deleteDirectoryAndContentsRecursive(copiedFd);
    }
}

From source file:it.greenvulcano.util.zip.ZipHelper.java

/**
 * Performs the <code>ZIP</code> compression of a file/directory, whose name
 * and parent directory are passed as arguments, on the local filesystem.
 * The result is written into a target file with the <code>zip</code>
 * extension.<br>//from   ww  w  .  j  a  va2 s.co m
 * The source filename may contain a regualr expression: in this
 * case, all the filenames matching the pattern will be compressed and put
 * in the same target <code>zip</code> file.<br>
 *
 *
 * @param srcDirectory
 *            the source parent directory of the file/s to be zipped. Must
 *            be an absolute pathname.
 * @param fileNamePattern
 *            the name of the file to be zipped. May contain a regular expression,
 *            possibly matching multiple files/directories.
 *            If matching a directory, the directory is zipped with all its content as well.
 * @param targetDirectory
 *            the target parent directory of the created <code>zip</code>
 *            file. Must be an absolute pathname.
 * @param zipFilename
 *            the name of the zip file to be created. Cannot be
 *            <code>null</code>, and must have the <code>.zip</code>
 *            extension. If a target file already exists with the same name
 *            in the same directory, it will be overwritten.
 * @throws IOException
 *             If any error occurs during file compression.
 * @throws IllegalArgumentException
 *             if the arguments are invalid.
 */
public void zipFile(String srcDirectory, String fileNamePattern, String targetDirectory, String zipFilename)
        throws IOException {

    File srcDir = new File(srcDirectory);

    if (!srcDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the source parent directory is NOT absolute: " + srcDirectory);
    }

    if (!srcDir.exists()) {
        throw new IllegalArgumentException(
                "Source parent directory " + srcDirectory + " NOT found on local filesystem.");
    }

    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory.");
    }

    File targetDir = new File(targetDirectory);

    if (!targetDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the target parent directory is NOT absolute: " + targetDirectory);
    }

    if (!targetDir.exists()) {
        throw new IllegalArgumentException(
                "Target parent directory " + targetDirectory + " NOT found on local filesystem.");
    }

    if (!targetDir.isDirectory()) {
        throw new IllegalArgumentException(
                "Target parent directory " + targetDirectory + " is NOT a directory.");
    }

    if ((zipFilename == null) || (zipFilename.length() == 0)) {
        throw new IllegalArgumentException("Target zip file name is missing.");
    }

    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(new FileOutputStream(new File(targetDir, zipFilename)));
        zos.setLevel(compressionLevel);

        URI base = srcDir.toURI();
        File[] files = srcDir.listFiles(new RegExFilenameFilter(fileNamePattern));

        for (File file : files) {
            internalZipFile(file, zos, base);
        }
    } finally {
        try {
            if (zos != null) {
                zos.close();
            }
        } catch (Exception exc) {
            // Do nothing
        }
    }
}

From source file:com.bibisco.manager.ProjectManager.java

public static void zipIt(String zipFile) {

    mLog.debug("Start zipIt(String)");

    ContextManager lContextManager = ContextManager.getInstance();

    String lStrDBDirectoryPath = lContextManager.getDbDirectoryPath();
    String lStrDbProjectDirectory = getDBProjectDirectory(lContextManager.getIdProject());
    List<String> lFileList = getDirectoryFileList(new File(lStrDbProjectDirectory));

    try {/*from  w  w w.j av a  2  s .c  o  m*/
        File lFile = new File(zipFile);

        lFile.createNewFile();
        FileOutputStream lFileOutputStream = new FileOutputStream(lFile);
        ZipOutputStream lZipOutputStream = new ZipOutputStream(lFileOutputStream);

        byte[] buffer = new byte[1024];
        for (String lStrFile : lFileList) {

            ZipEntry lZipEntry = new ZipEntry(
                    lStrFile.substring(lStrDBDirectoryPath.length(), lStrFile.length()));
            lZipOutputStream.putNextEntry(lZipEntry);

            FileInputStream lFileInputStream = new FileInputStream(lStrFile);

            int lIntLen;
            while ((lIntLen = lFileInputStream.read(buffer)) > 0) {
                lZipOutputStream.write(buffer, 0, lIntLen);
            }

            lFileInputStream.close();
        }

        lZipOutputStream.closeEntry();
        lZipOutputStream.close();

        mLog.debug("Folder successfully compressed");
    } catch (IOException e) {
        mLog.error(e);
        throw new BibiscoException(e, BibiscoException.IO_EXCEPTION);
    }

    mLog.debug("End zipIt(String)");
}

From source file:com.ephesoft.gxt.admin.server.ExportBatchClassDownloadServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter(IDENTIFIER));
    String exportLearning = req.getParameter(EXPORT_LEARNING);
    if (batchClass == null) {
        log.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {//from w w  w .  ja  va 2 s  .  c  o  m
        // Marking exported batch class as 'Advance' as this batch has some advance feature like new FPR.rsp file.
        batchClass.setAdvancedBatchClass(Boolean.TRUE);
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy");
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + "_" + formattedDate + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyConnections(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);
        BatchClassUtil.exportCMISConfiguration(batchClass);
        // BatchClassUtil.decryptAllPasswords(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);
        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                String[] folderList = originalFolder.list();
                Arrays.sort(folderList);

                for (int i = 0; i < folderList.length; i++) {
                    if (folderList[i].endsWith(SERIALIZATION_EXT)) {
                        // skip previous ser file since new is created.
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getTestKVExtractionFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getTestTableFolderName())
                            || FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                                    batchSchemaService.getFileboundPluginMappingFolderName())) {
                        // Skip this folder
                        continue;
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                            batchSchemaService.getSearchSampleName()) && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (!(FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getSearchSampleName()))) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    }
                }
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}

From source file:com.centurylink.mdw.common.service.JsonExport.java

/**
 * Default behavior adds zip entries for each property on the first (non-mdw) top-level object.
 *///  www  .j  a va2 s  . co  m
public String exportZipBase64() throws JSONException, IOException {
    Map<String, JSONObject> objectMap = JsonUtil.getJsonObjects(jsonable.getJson());
    JSONObject mdw = null;
    JSONObject contents = null;
    for (String name : objectMap.keySet()) {
        if ("mdw".equals(name))
            mdw = objectMap.get(name);
        else if (contents == null)
            contents = objectMap.get(name);
    }
    if (contents == null)
        throw new IOException("Cannot find expected contents property");
    else
        objectMap = JsonUtil.getJsonObjects(contents);
    if (mdw != null)
        objectMap.put(".mdw", mdw);

    byte[] buffer = new byte[ZIP_BUFFER_KB * 1024];
    ZipOutputStream zos = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        zos = new ZipOutputStream(outputStream);
        for (String name : objectMap.keySet()) {
            JSONObject json = objectMap.get(name);
            ZipEntry ze = new ZipEntry(name);
            zos.putNextEntry(ze);
            InputStream inputStream = new ByteArrayInputStream(json.toString(2).getBytes());
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
    } finally {
        if (zos != null) {
            zos.closeEntry();
            zos.close();
        }
    }
    byte[] bytes = outputStream.toByteArray();
    return new String(Base64.encodeBase64(bytes));
}

From source file:nl.b3p.viewer.features.ShapeDownloader.java

/**
 * This method zips the directory/*from w w w  . ja va  2  s  .c  o  m*/
 *
 * @param dir
 * @param zipDirName
 */
private void zipDirectory(File dir, File zip) throws IOException {
    try {
        List<String> filesListInDir = new ArrayList<String>();
        populateFilesList(dir, filesListInDir);
        //now zip files one by one
        //create ZipOutputStream to write to the zip file
        FileOutputStream fos = new FileOutputStream(zip);
        ZipOutputStream zos = new ZipOutputStream(fos);
        for (String filePath : filesListInDir) {
            //for ZipEntry we need to keep only relative file path, so we used substring on absolute path
            ZipEntry ze = new ZipEntry(
                    filePath.substring(dir.getAbsolutePath().length() + 1, filePath.length()));
            zos.putNextEntry(ze);
            //read the file and write to ZipOutputStream
            FileInputStream fis = new FileInputStream(filePath);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
            fis.close();
        }
        zos.close();
        fos.close();
    } catch (IOException e) {
        log.error("Could not write zipfile. Exiting.", e);
        throw e;
    }
}