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:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Zip File into Archive/*  ww  w. ja  v  a  2s .c o m*/
 *
 * @param GENERATION_LOGGER Reference
 * @param zipFilePath       Zip file Destination.
 * @param fileFolder        Folder to be zipped Up ...
 * @throws IOException
 */
protected static boolean zipFile(GenerationLogger GENERATION_LOGGER, String zipFilePath, String fileFolder)
        throws IOException {
    /**
     * First get All Nodes with Folder
     */
    List<String> fileList = new ArrayList<>();
    generateFileListForCompression(new File(fileFolder), fileList);
    File sourceFolder = new File(fileFolder);
    byte[] buffer = new byte[8192];
    try {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);

        GENERATION_LOGGER.info("Compressing Instance Generation to Zip: " + zipFilePath);
        /**
         * Loop Over Files
         */
        for (String filename : fileList) {
            String zipEntryName = filename.substring(sourceFolder.getParent().length() + 1, filename.length());
            ZipEntry ze = new ZipEntry(zipEntryName);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(filename);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
            GENERATION_LOGGER.debug("File Added to Archive: " + zipEntryName);
        }
        /**
         * Close
         */
        zos.closeEntry();
        zos.close();
        return true;
    } catch (IOException ex) {
        GENERATION_LOGGER.error(ex.getMessage());
        ex.printStackTrace();
        return false;
    }
}

From source file:ch.puzzle.itc.mobiliar.business.shakedown.control.ShakedownTestRunner.java

String bundleSTM(String strcsv, String stscsv, STS sts) throws ShakedownTestException {
    String tmpdir = System.getProperty("java.io.tmpdir");
    String stmpath = ConfigurationService.getProperty(ConfigKey.STM_PATH);
    if (tmpdir != null && !tmpdir.trim().isEmpty()) {
        if (stmpath != null && new File(stmpath).exists()) {
            try {
                File bundle = new File(tmpdir + File.separator + sts.getTestId() + "stm.jar");
                ZipOutputStream bundleZOS = new ZipOutputStream(new FileOutputStream(bundle));
                bundleZOS.putNextEntry(new ZipEntry("str.csv"));
                IOUtils.write(strcsv, bundleZOS);
                bundleZOS.putNextEntry(new ZipEntry("sts.csv"));
                IOUtils.write(stscsv, bundleZOS);
                ZipInputStream zin = new ZipInputStream(new FileInputStream(stmpath));
                ZipEntry ze;/*from w ww.ja  va2 s.c o m*/
                while ((ze = zin.getNextEntry()) != null) {
                    bundleZOS.putNextEntry(ze);
                    IOUtils.copy(zin, bundleZOS);
                }
                bundleZOS.close();
                log.info("Successfully bundled STM and stored to " + bundle.getAbsolutePath());
            } catch (IOException e) {
                throw new ShakedownTestException("Was not able to bundle STM", e);
            }
        } else {
            throw new ShakedownTestException(
                    "No STM found at location configured with system property " + ConfigKey.STM_PATH + ".");
        }
    } else {
        throw new ShakedownTestException("No temporary folder found - is java.io.tmpdir defined?");
    }
    return tmpdir + File.separator + sts.getTestId() + "stm.jar";
}

From source file:edu.jhuapl.graphs.controller.GraphController.java

public static String zipGraphs(List<GraphObject> graphs, String tempDir, String userId) throws GraphException {
    if (graphs != null && graphs.size() > 0) {
        byte[] byteBuffer = new byte[1024];
        String zipFileName = getUniqueId(userId) + ".zip";

        try {//w  w w .jav a  2 s. c o  m
            File zipFile = new File(tempDir, zipFileName);
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            boolean hasGraphs = false;

            for (GraphObject graph : graphs) {
                if (graph != null) {
                    byte[] renderedGraph = graph.getRenderedGraph().getData();
                    ByteArrayInputStream in = new ByteArrayInputStream(renderedGraph);
                    int len;

                    zos.putNextEntry(new ZipEntry(graph.getImageFileName()));

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

                    in.close();
                    zos.closeEntry();
                    hasGraphs = true;
                }
            }

            zos.close();

            if (hasGraphs) {
                return zipFileName;
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new GraphException("Could not write zip", e);
        }
    }

    return null;
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.ExportBatchClassDownloadServlet.java

/**
 * Overriden doGet method.//from   w  w w .  j  av a  2 s. c o m
 * 
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@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"));
    if (batchClass == null) {
        LOG.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy", Locale.getDefault());
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + BatchClassManagementConstants.UNDERSCORE
                + formattedDate + BatchClassManagementConstants.UNDERSCORE + 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.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);

        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));
            boolean isImagemagickBaseFolder = false;
            String imageMagickBaseFolderParam = req
                    .getParameter(batchSchemaService.getImagemagickBaseFolderName());
            if (imageMagickBaseFolderParam != null && (imageMagickBaseFolderParam
                    .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                    || Boolean.parseBoolean(imageMagickBaseFolderParam))) {
                isImagemagickBaseFolder = true;
            }

            boolean isSearchSampleName = false;
            String isSearchSampleNameParam = req.getParameter(batchSchemaService.getSearchSampleName());
            if (isSearchSampleNameParam != null
                    && (isSearchSampleNameParam.equalsIgnoreCase(batchSchemaService.getSearchSampleName())
                            || Boolean.parseBoolean(isSearchSampleNameParam))) {
                isSearchSampleName = true;
            }

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

            if (originalFolder.isDirectory()) {

                validateFolderAndFile(batchSchemaService, copiedFolder, isImagemagickBaseFolder,
                        isSearchSampleName, originalFolder);
            }

        } 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:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Generates a zip file.//from   w ww  .j  ava 2  s  . com
 *
 * @param source      source file or directory to compress.
 * @param destination destination of zipped file.
 * @return the zipped file.
 */
private void generateZip(File source, File destination) throws IOException {
    if (source == null || !source.exists()) {
        throw new IllegalArgumentException("source file should exist");
    }
    if (destination == null) {
        throw new IllegalArgumentException("destination file should be not null");
    }

    FileOutputStream output = new FileOutputStream(destination);
    ZipOutputStream zip_out = new ZipOutputStream(output);
    zip_out.setLevel(cfgManager.getDownloadConfiguration().getCompressionLevel());

    List<QualifiedFile> file_list = getFileList(source);
    byte[] buffer = new byte[BUFFER_SIZE];
    for (QualifiedFile qualified_file : file_list) {
        ZipEntry entry = new ZipEntry(qualified_file.getQualifier());
        InputStream input = new FileInputStream(qualified_file.getFile());

        int read;
        zip_out.putNextEntry(entry);
        while ((read = input.read(buffer)) != -1) {
            zip_out.write(buffer, 0, read);
        }
        input.close();
        zip_out.closeEntry();
    }
    zip_out.close();
    output.close();
}

From source file:be.fedict.eid.dss.document.zip.ZIPSignatureOutputStream.java

@Override
public void close() throws IOException {
    super.close();

    byte[] signatureData = toByteArray();

    /*//  w ww .  j a v a  2s .  co m
     * Copy the original ZIP content.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
            zipOutputStream.putNextEntry(newZipEntry);
            LOG.debug("copying " + zipEntry.getName());
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();

    /*
     * Add the XML signature file to the ZIP package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    LOG.debug("writing " + zipEntry.getName());
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.yifanlu.PSXperiaTool.ZpakCreate.java

public void create(boolean noCompress) throws IOException {
    Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(),
            !noCompress);//from  ww  w.j a v a  2 s . com
    IOFileFilter filter = new IOFileFilter() {
        public boolean accept(File file) {
            if (file.getName().startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }

        public boolean accept(File file, String s) {
            if (s.startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }
    };
    Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
    ZipOutputStream out = new ZipOutputStream(mOut);
    out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
    while (it.hasNext()) {
        File current = it.next();
        FileInputStream in = new FileInputStream(current);
        ZipEntry zEntry = new ZipEntry(
                current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\", "/"));
        if (noCompress) {
            zEntry.setSize(in.getChannel().size());
            zEntry.setCompressedSize(in.getChannel().size());
            zEntry.setCrc(getCRC32(current));
        }
        out.putNextEntry(zEntry);
        Logger.verbose("Adding file %s", current.getPath());
        int n;
        while ((n = in.read(mBuffer)) != -1) {
            out.write(mBuffer, 0, n);
        }
        in.close();
        out.closeEntry();
    }
    out.close();
    Logger.debug("Done with ZPAK creation.");
}

From source file:net.sourceforge.tagsea.instrumentation.network.NetworkSendJob.java

private File compressLogs(File[] filesToCompress) throws IOException {
    IPath stateLocation = TagSEAInstrumentationPlugin.getDefault().getStateLocation();
    DateFormat format = DateUtils.getDateFormat();
    String sendName = format.format(new Date()).replace('/', '-') + "-workspace"
            + stateLocation.toPortableString().hashCode() + ".zip";
    File sendFile = stateLocation.append(sendName).toFile();
    if (!sendFile.exists()) {
        sendFile.createNewFile();//from   www.jav  a 2  s . c  om
    }
    if (filesToCompress.length == 0) {
        sendFile.delete();
        return null;
    }
    ZipOutputStream zipStream;
    zipStream = new ZipOutputStream(new FileOutputStream(sendFile));

    for (File file : filesToCompress) {
        FileInputStream inputStream = null;
        try {
            ZipEntry entry = new ZipEntry(file.getName());
            zipStream.putNextEntry(entry);
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int read = -1;
            while ((read = inputStream.read(buffer)) != -1) {
                zipStream.write(buffer, 0, read);
            }

            zipStream.closeEntry();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
    zipStream.close();
    return sendFile;
}

From source file:org.saiku.plugin.resources.PentahoRepositoryResource2.java

@GET
@Path("/zip")
public Response getResourcesAsZip(@QueryParam("directory") String directory, @QueryParam("files") String files,
        @QueryParam("type") String type) {
    try {//from  w  w w. j  a  v a2 s  . c  o m
        if (StringUtils.isBlank(directory))
            return Response.ok().build();

        final String fileType = type;
        IUserContentAccess access = contentAccessFactory.getUserContentAccess(null);

        if (!access.fileExists(directory) && access.hasAccess(directory, FileAccess.READ)) {
            throw new SaikuServiceException(
                    "Access to Repository has failed File does not exist or no read right: " + directory);
        }

        IBasicFileFilter txtFilter = StringUtils.isBlank(type) ? null : new IBasicFileFilter() {
            public boolean accept(IBasicFile file) {
                return file.isDirectory() || file.getExtension().equals(fileType);
            }
        };

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

        List<IBasicFile> basicFiles = access.listFiles(directory, txtFilter);

        for (IBasicFile basicFile : basicFiles) {
            if (!basicFile.isDirectory()) {
                String entry = basicFile.getName();
                byte[] doc = IOUtils.toByteArray(basicFile.getContents());
                ZipEntry ze = new ZipEntry(entry);
                zos.putNextEntry(ze);
                zos.write(doc);

            }
        }

        zos.closeEntry();
        zos.close();
        byte[] zipDoc = bos.toByteArray();

        return Response.ok(zipDoc, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename = " + directory + ".zip")
                .header("content-length", zipDoc.length).build();

    } catch (Exception e) {
        log.error("Cannot zip resources " + files, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(error).build();
    }

}

From source file:be.fedict.eid.applet.service.signer.asic.ASiCSignatureOutputStream.java

@Override
public void close() throws IOException {
    super.close();

    byte[] signatureData = toByteArray();

    /*/* w  w  w. j  a va  2 s.c  om*/
     * Copy the original ZIP content.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) {
            ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
            zipOutputStream.putNextEntry(newZipEntry);
            LOG.debug("copying " + zipEntry.getName());
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();

    /*
     * Add the XML signature file to the ASiC package.
     */
    zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE);
    LOG.debug("writing " + zipEntry.getName());
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}