Example usage for java.util.zip ZipOutputStream setMethod

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

Introduction

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

Prototype

public void setMethod(int method) 

Source Link

Document

Sets the default compression method for subsequent entries.

Usage

From source file:com.espringtran.compressor4j.processor.GzipProcessor.java

/**
 * Compress data//from  ww w .  j ava  2  s .co  m
 * 
 * @param fileCompressor
 *            FileCompressor object
 * @return
 * @throws Exception
 */
@Override
public byte[] compressData(FileCompressor fileCompressor) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GzipCompressorOutputStream cos = new GzipCompressorOutputStream(baos);
    ZipOutputStream zos = new ZipOutputStream(cos);
    try {
        zos.setLevel(fileCompressor.getLevel().getValue());
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setComment(fileCompressor.getComment());
        for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) {
            zos.putNextEntry(new ZipEntry(binaryFile.getDesPath()));
            zos.write(binaryFile.getData());
            zos.closeEntry();
        }
        zos.flush();
        zos.finish();
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on compress data", e);
    } finally {
        zos.close();
        cos.close();
        baos.close();
    }
    return baos.toByteArray();
}

From source file:it.geosolutions.mariss.wps.ppio.OutputResourcesPPIO.java

@Override
public void encode(Object value, OutputStream os) throws Exception {

    ZipOutputStream zos = null;
    try {//from   w w w.java2s  . c  om
        OutputResource or = (OutputResource) value;

        zos = new ZipOutputStream(os);
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        Iterator<File> iter = or.getDeletableResourcesIterator();
        while (iter.hasNext()) {

            File tmp = iter.next();
            if (!tmp.exists() || !tmp.canRead() || !tmp.canWrite()) {
                LOGGER.warning("Skip Deletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

            if (!tmp.delete()) {
                LOGGER.warning("File '" + tmp.getName() + "' cannot be deleted...");
            }
        }
        iter = null;

        Iterator<File> iter2 = or.getUndeletableResourcesIterator();
        while (iter2.hasNext()) {

            File tmp = iter2.next();
            if (!tmp.exists() || !tmp.canRead()) {
                LOGGER.warning("Skip Undeletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

        }
    } finally {
        try {
            zos.close();
        } catch (IOException e) {
            LOGGER.severe(e.getMessage());
        }
    }
}

From source file:org.nuxeo.ecm.platform.io.impl.IOManagerImpl.java

void exportDocumentsAndResources(OutputStream out, String repo, DocumentsExporter docsExporter,
        Collection<String> ioAdapters) throws IOException {
    List<String> doneAdapters = new ArrayList<>();

    ZipOutputStream zip = new ZipOutputStream(out);
    zip.setMethod(ZipOutputStream.DEFLATED);
    zip.setLevel(9);//from   w w w . j  a  v a  2 s  .c  o m

    ByteArrayOutputStream docsZip = new ByteArrayOutputStream();
    DocumentTranslationMap map = docsExporter.exportDocs(docsZip);

    ZipEntry docsEntry = new ZipEntry(DOCUMENTS_ADAPTER_NAME + ".zip");
    zip.putNextEntry(docsEntry);
    zip.write(docsZip.toByteArray());
    zip.closeEntry();
    docsZip.close();
    doneAdapters.add(DOCUMENTS_ADAPTER_NAME);

    Collection<DocumentRef> allSources = map.getDocRefMap().keySet();

    if (ioAdapters != null && !ioAdapters.isEmpty()) {
        for (String adapterName : ioAdapters) {
            String filename = adapterName + ".xml";
            IOResourceAdapter adapter = getAdapter(adapterName);
            if (adapter == null) {
                log.warn("Adapter " + adapterName + " not found");
                continue;
            }
            if (doneAdapters.contains(adapterName)) {
                log.warn("Export for adapter " + adapterName + " already done");
                continue;
            }
            IOResources resources = adapter.extractResources(repo, allSources);
            resources = adapter.translateResources(repo, resources, map);
            ByteArrayOutputStream adapterOut = new ByteArrayOutputStream();
            adapter.getResourcesAsXML(adapterOut, resources);
            ZipEntry adapterEntry = new ZipEntry(filename);
            zip.putNextEntry(adapterEntry);
            zip.write(adapterOut.toByteArray());
            zip.closeEntry();
            doneAdapters.add(adapterName);
            adapterOut.close();
        }
    }
    try {
        zip.close();
    } catch (ZipException e) {
        // empty zip file, do nothing
    }
}

From source file:org.nuxeo.ecm.platform.picture.web.PictureBookManagerBean.java

protected String createZip(List<DocumentModel> documents) throws IOException {

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

    BufferedOutputStream buff = new BufferedOutputStream(response.getOutputStream());
    ZipOutputStream out = new ZipOutputStream(buff);
    out.setMethod(ZipOutputStream.DEFLATED);
    out.setLevel(9);/*  ww  w .  ja  v a2s . co  m*/
    byte[] data = new byte[BUFFER];
    for (DocumentModel doc : documents) {

        // first check if DM is attached to the core
        if (doc.getSessionId() == null) {
            // refetch the doc from the core
            doc = documentManager.getDocument(doc.getRef());
        }

        // NXP-2334 : skip deleted docs
        if (doc.getCurrentLifeCycleState().equals("delete")) {
            continue;
        }

        BlobHolder bh = doc.getAdapter(BlobHolder.class);
        if (doc.isFolder() && !isEmptyFolder(doc)) {
            addFolderToZip("", out, doc, data);
        } else if (bh != null) {
            addBlobHolderToZip("", out, data, (PictureBlobHolder) bh);
        }
    }
    try {
        out.close();
    } catch (ZipException e) {
        // empty zip file, do nothing
        setFacesMessage("label.clipboard.emptyDocuments");
        return null;
    }
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "clipboard.zip" + "\";");
    response.setContentType("application/gzip");
    response.flushBuffer();
    context.responseComplete();
    return null;
}

From source file:edu.mayo.pipes.iterators.Compressor.java

/**
 * Create a single entry Zip archive, and prepare it for writing
 *
 * @throws IOException//from  w  w  w . j  a va  2 s  .  c om
 */
public BufferedWriter makeZipWriter() throws IOException {
    if (outFile == null)
        return null;

    FileOutputStream outFileStream = new FileOutputStream(outFile);
    ZipOutputStream zipWrite = new ZipOutputStream(outFileStream);
    ZipEntry zE;

    // Setup the zip writing things
    zipWrite.setMethod(ZipOutputStream.DEFLATED);
    zipWrite.setLevel(9); // Max compression
    zE = new ZipEntry("Default");
    zipWrite.putNextEntry(zE);
    // Now can attach the writer to write to this zip entry
    OutputStreamWriter wStream = new OutputStreamWriter(zipWrite);
    writer = new BufferedWriter(wStream);
    comp = kZipCompression;
    return writer;
}

From source file:ZipImploder.java

protected void configure(ZipOutputStream zos, String comment, int method, int level) {
    if (comment != null) {
        zos.setComment(comment);/* www  .  j  av a2  s  .  com*/
    }
    if (method >= 0) {
        zos.setMethod(method);
    }
    if (level >= 0) {
        zos.setLevel(level);
    }
}

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

private void zipUp(File out, File[] in) {
    FileOutputStream fout = null;
    ZipOutputStream zout = null;
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    try {/* w  ww.  j av  a  2s .c om*/
        fout = new FileOutputStream(out);
        zout = new ZipOutputStream(fout);
        zout.setMethod(ZipOutputStream.DEFLATED);

        for (File currFile : in) {
            FileInputStream fin = new FileInputStream(currFile);
            ZipEntry currEntry = new ZipEntry(currFile.getName());
            zout.putNextEntry(currEntry);
            while ((bytesRead = fin.read(buffer)) > 0) {
                zout.write(buffer, 0, bytesRead);
            }
            zout.closeEntry();
            fin.close();
        }
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    } finally {
        try {
            zout.close();
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

}

From source file:org.eclipse.mylyn.internal.context.core.InteractionContextExternalizer.java

/**
 * For testing/*  w  ww .  j a  va  2  s. co m*/
 */
public void writeContext(IInteractionContext context, ZipOutputStream outputStream,
        IInteractionContextWriter writer) throws IOException {
    String handleIdentifier = context.getHandleIdentifier();
    String encoded = URLEncoder.encode(handleIdentifier, InteractionContextManager.CONTEXT_FILENAME_ENCODING);
    ZipEntry zipEntry = new ZipEntry(encoded + InteractionContextManager.CONTEXT_FILE_EXTENSION_OLD);
    outputStream.putNextEntry(zipEntry);
    outputStream.setMethod(ZipOutputStream.DEFLATED);

    writer.setOutputStream(outputStream);
    writer.writeContextToStream(context);
    outputStream.flush();
    outputStream.closeEntry();

    addAdditionalInformation(context, outputStream);
}

From source file:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);/*from  w w w .  jav  a 2s.c  o m*/
    boolean Fileexists = false;

    String realZipfilename = StringUtil.environmentSubstitute(zipFilename);
    String realWildcard = StringUtil.environmentSubstitute(wildcard);
    String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude);
    String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory);
    String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory);

    if (realZipfilename != null) {
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);
            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                        + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            } else {
                Fileexists = false;
            }

            // Let's start the process now
            if (ifzipfileexists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                result.setResult(false);
                result.setNrErrors(1);

            } else if (ifzipfileexists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                result.setResult(true);

            } else if (afterzip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination Folder
                result.setResult(false);
                result.setNrErrors(1);
                log.logError(toString(),
                        Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));

            } else
            // After Zip, Move files..User must give a destination Folder
            {

                if (ifzipfileexists == 0 && Fileexists) {

                    // the zip file exists and user want to create new one with unique name
                    //Format Date

                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");
                    realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip";
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));

                } else if (ifzipfileexists == 1 && Fileexists) {
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
                }

                // Get all the files in the directory...

                File f = new File(realTargetdirectory);

                String[] filelist = f.list();

                log.logDetailed(toString(),
                        Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length
                                + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory
                                + Messages.getString("JobZipFiles.Files_Found3.Label"));

                Pattern pattern = null;
                if (!Const.isEmpty(realWildcard)) {
                    pattern = Pattern.compile(realWildcard);

                }
                Pattern patternexclude = null;
                if (!Const.isEmpty(realWildcardExclude)) {
                    patternexclude = Pattern.compile(realWildcardExclude);

                }

                // Prepare Zip File
                byte[] buffer = new byte[18024];

                FileOutputStream dest = new FileOutputStream(realZipfilename);
                BufferedOutputStream buff = new BufferedOutputStream(dest);
                ZipOutputStream out = new ZipOutputStream(buff);

                // Set the method
                out.setMethod(ZipOutputStream.DEFLATED);

                // Set the compression level
                if (compressionrate == 0) {
                    out.setLevel(Deflater.NO_COMPRESSION);
                } else if (compressionrate == 1) {
                    out.setLevel(Deflater.DEFAULT_COMPRESSION);
                }
                if (compressionrate == 2) {
                    out.setLevel(Deflater.BEST_COMPRESSION);
                }
                if (compressionrate == 3) {
                    out.setLevel(Deflater.BEST_SPEED);
                }

                // Specify Zipped files (After that we will move,delete them...)
                String[] ZippedFiles = new String[filelist.length];
                int FileNum = 0;

                // Get the files in the list...
                for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
                    boolean getIt = true;
                    boolean getItexclude = false;

                    // First see if the file matches the regular expression!
                    if (pattern != null) {
                        Matcher matcher = pattern.matcher(filelist[i]);
                        getIt = matcher.matches();
                    }

                    if (patternexclude != null) {
                        Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                        getItexclude = matcherexclude.matches();
                    }

                    // Get processing File
                    String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                    File file = new File(targetFilename);

                    if (getIt && !getItexclude && !file.isDirectory()) {

                        // We can add the file to the Zip Archive

                        log.logDebug(toString(),
                                Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                        + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                        + realTargetdirectory
                                        + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                        // Associate a file input stream for the current file
                        FileInputStream in = new FileInputStream(targetFilename);

                        // Add ZIP entry to output stream.
                        out.putNextEntry(new ZipEntry(filelist[i]));

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

                        out.closeEntry();

                        // Close the current file input stream
                        in.close();

                        // Get Zipped File
                        ZippedFiles[FileNum] = filelist[i];
                        FileNum = FileNum + 1;
                    }
                }

                // Close the ZipOutPutStream
                out.close();

                //-----Get the list of Zipped Files and Move or Delete Them
                if (afterzip == 1 || afterzip == 2) {
                    // iterate through the array of Zipped files
                    for (int i = 0; i < ZippedFiles.length; i++) {
                        if (ZippedFiles[i] != null) {
                            // Delete File
                            FileObject fileObjectd = KettleVFS
                                    .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);

                            // Here we can move, delete files
                            if (afterzip == 1) {
                                // Delete File
                                boolean deleted = fileObjectd.delete();
                                if (!deleted) {
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Delete_File1.Label")
                                                    + realTargetdirectory + Const.FILE_SEPARATOR
                                                    + ZippedFiles[i] + Messages
                                                            .getString("JobZipFiles.Cant_Delete_File2.Label"));

                                }
                                // File deleted
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.File_Deleted2.Label"));
                            } else if (afterzip == 2) {
                                // Move File   
                                try {
                                    FileObject fileObjectm = KettleVFS.getFileObject(
                                            realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                    fileObjectd.moveTo(fileObjectm);
                                } catch (IOException e) {
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                    + ZippedFiles[i]
                                                    + Messages.getString("JobZipFiles.Cant_Move_File2.Label")
                                                    + e.getMessage());
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                }
                                // File moved
                                log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label")
                                        + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label"));
                            }
                        }
                    }
                }
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        result.setResult(false);
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
    }

    return result;
}

From source file:org.apache.felix.webconsole.internal.misc.ConfigurationRender.java

/**
 * @see org.apache.felix.webconsole.AbstractWebConsolePlugin#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  ww w  .j  a  v a  2  s.  co  m*/
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getPathInfo().endsWith(".txt")) {
        response.setContentType("text/plain; charset=utf-8");
        ConfigurationWriter pw = new PlainTextConfigurationWriter(response.getWriter());
        printConfigurationStatus(pw, ConfigurationPrinter.MODE_TXT);
        pw.flush();
    } else if (request.getPathInfo().endsWith(".zip")) {
        String type = getServletContext().getMimeType(request.getPathInfo());
        if (type == null) {
            type = "application/x-zip";
        }
        response.setContentType(type);

        ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
        zip.setLevel(Deflater.BEST_SPEED);
        zip.setMethod(ZipOutputStream.DEFLATED);

        final ConfigurationWriter pw = new ZipConfigurationWriter(zip);
        printConfigurationStatus(pw, ConfigurationPrinter.MODE_ZIP);
        pw.flush();

        addAttachments(pw, ConfigurationPrinter.MODE_ZIP);
        zip.finish();
    } else if (request.getPathInfo().endsWith(".nfo")) {
        WebConsoleUtil.setNoCache(response);
        response.setContentType("text/html; charset=utf-8");

        String name = request.getPathInfo();
        name = name.substring(name.lastIndexOf('/') + 1);
        name = name.substring(0, name.length() - 4);
        name = WebConsoleUtil.urlDecode(name);

        ConfigurationWriter pw = new HtmlConfigurationWriter(response.getWriter());
        pw.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
        pw.println("  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
        pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        pw.println("<head><title>dummy</title></head><body><div>");

        Collection printers = getConfigurationPrinters();
        for (Iterator i = printers.iterator(); i.hasNext();) {
            final PrinterDesc desc = (PrinterDesc) i.next();
            if (desc.label.equals(name)) {
                printConfigurationPrinter(pw, desc, ConfigurationPrinter.MODE_WEB);
                pw.println("</div></body></html>");
                return;
            }
        }

        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Invalid configuration printer: " + name);
    } else {
        super.doGet(request, response);
    }
}