Example usage for java.util.zip ZipOutputStream setLevel

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

Introduction

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

Prototype

public void setLevel(int level) 

Source Link

Document

Sets the compression level for subsequent entries which are DEFLATED.

Usage

From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getRequestURI().endsWith(RAW_FILE_MARKER) || req.getRequestURI().endsWith(ZIP_FILE_MARKER)) {

        InputStream input = null;
        OutputStream output = null;
        try {// www . j a  v  a 2 s . c o  m
            input = new FileInputStream(this.logFile);
            output = resp.getOutputStream();

            if (req.getRequestURI().endsWith(ZIP_FILE_MARKER)) {
                ZipOutputStream zip = new ZipOutputStream(output);
                zip.setLevel(Deflater.BEST_SPEED);

                ZipEntry entry = new ZipEntry(this.logFile.getName());
                entry.setTime(this.logFile.lastModified());
                entry.setMethod(ZipEntry.DEFLATED);

                zip.putNextEntry(entry);

                output = zip;
                resp.setContentType("application/zip");
            } else {
                resp.setContentType("text/plain");
                resp.setCharacterEncoding("UTF-8");
                resp.setHeader("Content-Length", String.valueOf(this.logFile.length())); // might be bigger than
            }
            resp.setDateHeader("Last-Modified", this.logFile.lastModified());

            IOUtils.copy(input, output);
        } catch (IOException ioe) {
            throw new ServletException("Cannot create copy of log file", ioe);
        } finally {
            IOUtils.closeQuietly(input);

            if (output instanceof ZipOutputStream) {
                ((ZipOutputStream) output).closeEntry();
                ((ZipOutputStream) output).finish();
            }
        }

        resp.flushBuffer();

    } else if (req.getRequestURI().endsWith(WINDOW_MARKER)) {

        if (canOpenSwingGui(req)) {
            showWindow();
        }

        String target = req.getRequestURI();
        target = target.substring(0, target.length() - WINDOW_MARKER.length());
        resp.sendRedirect(target);
        resp.flushBuffer();

    } else {

        super.service(req, resp);

    }
}

From source file:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Generates a zip file./*  w ww.j  ava 2  s .co  m*/
 *
 * @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:org.waterforpeople.mapping.dataexport.KMLApplet.java

private void processFile(String fileName, ArrayList<String> countryList) throws Exception {
    System.out.println("Calling GenerateDocument");
    VelocityContext context = new VelocityContext();
    File f = new File(fileName);
    if (!f.exists()) {
        f.createNewFile();//from  ww  w  .ja  va  2  s  .co  m
    }
    ZipOutputStream zipOut = null;
    try {

        zipOut = new ZipOutputStream(new FileOutputStream(fileName));
        zipOut.setLevel(ZipOutputStream.DEFLATED);
        ZipEntry entry = new ZipEntry("ap.kml");
        zipOut.putNextEntry(entry);

        zipOut.write(mergeContext(context, "template/DocumentHead.vm").getBytes("UTF-8"));
        for (String countryCode : countryList) {
            int i = 0;
            String cursor = null;
            PlacemarkDtoResponse pdr = BulkDataServiceClient.fetchPlacemarks(countryCode, serverBase, cursor);
            if (pdr != null) {
                cursor = pdr.getCursor();
                List<PlacemarkDto> placemarkDtoList = pdr.getDtoList();
                SwingUtilities.invokeLater(new StatusUpdater("Staring to processes " + countryCode));
                writePlacemark(placemarkDtoList, zipOut);
                SwingUtilities.invokeLater(new StatusUpdater("Processing complete for " + countryCode));
                while (cursor != null) {
                    pdr = BulkDataServiceClient.fetchPlacemarks(countryCode, serverBase, cursor);
                    if (pdr != null) {
                        if (pdr.getCursor() != null)
                            cursor = pdr.getCursor();
                        else
                            cursor = null;
                        placemarkDtoList = pdr.getDtoList();
                        System.out.println("Starting to process: " + countryCode);
                        writePlacemark(placemarkDtoList, zipOut);
                        System.out.println("Fetching next set of records for: " + countryCode + " : " + i++);
                    } else {
                        break;
                    }
                }
            }
        }
        zipOut.write(mergeContext(context, "template/DocumentFooter.vm").getBytes("UTF-8"));
        zipOut.closeEntry();
        zipOut.close();
    } catch (Exception ex) {
        System.out.println(ex + " " + ex.getMessage() + " ");
        ex.printStackTrace(System.out);
    }
}

From source file:sk.baka.aedict.indexer.Main.java

private void zipLuceneIndex() throws IOException {
    System.out.println("Zipping the index file");
    final File zip = new File(config.getTargetFileName());
    if (zip.exists() && !zip.delete()) {
        throw new IOException("Cannot delete " + zip.getAbsolutePath());
    }//w w  w. j  a va2 s. c o m
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zip));
    try {
        out.setLevel(9);
        final File[] luceneIndexFiles = new File(LUCENE_INDEX).listFiles();
        for (final File indexFile : luceneIndexFiles) {
            final ZipEntry entry = new ZipEntry(indexFile.getName());
            entry.setSize(indexFile.length());
            out.putNextEntry(entry);
            final InputStream in = new FileInputStream(indexFile);
            try {
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(in);
            }
            out.closeEntry();
        }
    } finally {
        IOUtils.closeQuietly(out);
    }
    System.out.println("Finished index zipping");
}

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

/**
 * Exports the given part of the structr database to the given output stream.
 *
 * @param outputStream//  w  ww.j  av a 2  s  .  c o m
 * @param nodes
 * @param relationships
 * @param filePaths
 * @param includeFiles
 * @throws FrameworkException
 */
public static void exportToStream(final OutputStream outputStream,
        final Iterable<? extends NodeInterface> nodes,
        final Iterable<? extends RelationshipInterface> relationships, final Iterable<String> filePaths,
        final boolean includeFiles) throws FrameworkException {

    try {

        Set<String> filesToInclude = new LinkedHashSet<>();
        ZipOutputStream zos = new ZipOutputStream(outputStream);

        // collect files to include in export
        if (filePaths != null) {

            for (String file : filePaths) {

                filesToInclude.add(file);
            }
        }

        // set compression
        zos.setLevel(6);

        if (includeFiles) {

            logger.log(Level.INFO, "Exporting files..");

            // export files first
            exportDirectory(zos, new File("files"), "", filesToInclude.isEmpty() ? null : filesToInclude);
        }

        // export database
        exportDatabase(zos, new BufferedOutputStream(zos), nodes, relationships);

        // finish ZIP file
        zos.finish();

        // close stream
        zos.flush();
        zos.close();

    } catch (Throwable t) {

        t.printStackTrace();

        throw new FrameworkException(500, t.getMessage());
    }
}

From source file:org.eclipse.wb.internal.core.editor.errors.report2.ZipFileErrorReport.java

/**
 * Compress the contents of report into single zip file.
 *//* w w  w  . j ava 2 s.co  m*/
private String createZipReport(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(Messages.ZipFileErrorReport_taskTitle, m_entries.size());
    // store zip as temp file
    // prepare temp dir and file
    File tempDir = getReportTemporaryDirectory();
    String fileName = "report-" + DateFormatUtils.format(new Date(), "yyyyMMdd-HHmmss") + ".zip";
    File tempFile = new File(tempDir, fileName);
    tempFile.deleteOnExit();
    // create stream
    ZipOutputStream zipStream = null;
    try {
        zipStream = new ZipOutputStream(new FileOutputStream(tempFile));
        zipStream.setLevel(9);
        // compress the files
        for (IReportEntry reportInfo : m_entries) {
            try {
                reportInfo.write(zipStream);
            } catch (Throwable e) {
                DesignerPlugin.log(e);
            }
        }
    } finally {
        IOUtils.closeQuietly(zipStream);
    }
    return tempFile.getAbsolutePath();
}

From source file:org.messic.server.api.APISong.java

@Transactional
public void getSongsZip(User user, List<Long> desiredSongs, OutputStream os) throws IOException {
    ZipOutputStream zos = new ZipOutputStream(os);
    // level - the compression level (0-9)
    zos.setLevel(9);

    HashMap<String, String> songs = new HashMap<String, String>();
    for (Long songSid : desiredSongs) {
        MDOSong song = daoSong.get(user.getLogin(), songSid);
        if (song != null) {
            // add file
            // extract the relative name for entry purpose
            String entryName = song.getLocation();
            if (songs.get(entryName) == null) {
                // not repeated
                songs.put(entryName, "ok");
                ZipEntry ze = new ZipEntry(entryName);
                zos.putNextEntry(ze);//from  ww w  .  j a  v  a2 s .  c  o m
                FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings()));
                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
        }
    }

    zos.close();
}

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);

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

    ZipEntry docsEntry = new ZipEntry(DOCUMENTS_ADAPTER_NAME + ".zip");
    zip.putNextEntry(docsEntry);/*from  ww  w. j  a va  2 s  .co  m*/
    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.egov.wtms.web.controller.reports.GenerateConnectionBillController.java

private ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo,
        final ZipOutputStream out) {
    final byte[] buffer = new byte[1024];
    try {/*from www. j  a  va2 s. co m*/
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_")));
        int len;
        while ((len = inputStream.read(buffer)) > 0)
            out.write(buffer, 0, len);
        inputStream.close();

    } catch (final IllegalArgumentException iae) {
        LOGGER.error("Exception in addFilesToZip : ", iae);
    } catch (final FileNotFoundException fnfe) {
        LOGGER.error("Exception in addFilesToZip : ", fnfe);
    } catch (final IOException ioe) {
        LOGGER.error("Exception in addFilesToZip : ", ioe);
    }
    return out;
}

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);
    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());
        }/*from w  ww .  j a  va 2  s.  com*/

        // 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;
}