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.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ?/* w  w  w  . ja v a  2  s .  c o  m*/
 * 
 * @param files 
 * @param out ?
 * @throws IOException
 * @throws Exception
 */
public static void zipDownLoad(Map<File, String> downQuene, HttpServletResponse response) throws IOException {

    ServletOutputStream out = response.getOutputStream();
    ZipOutputStream zipout = new ZipOutputStream(out);
    ZipEntry entry = null;
    zipout.setLevel(1);
    // zipout.setEncoding("GBK");
    if (downQuene != null && downQuene.size() > 0) {
        for (Entry<File, String> fileInfo : downQuene.entrySet()) {
            File file = fileInfo.getKey();
            try {
                String filename = new String(fileInfo.getValue().getBytes(), "GBK");
                entry = new ZipEntry(filename);
                entry.setSize(file.length());
                zipout.putNextEntry(entry);
            } catch (IOException e) {
                // Logger.getLogger(FileUtil.class).warn(":", e);
            }
            BufferedInputStream fr = new BufferedInputStream(new FileInputStream(fileInfo.getKey()));
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fr.read(buffer)) != -1)
                zipout.write(buffer, 0, len);
            fr.close();
        }
    }

    zipout.finish();
    zipout.flush();
    // out.flush();
}

From source file:PolyGlot.IOHandler.java

public static void writeFile(String _fileName, Document doc, DictCore core)
        throws IOException, TransformerException {
    final String tempFileName = "xxTEMPPGTFILExx";
    String directoryPath;/*from  w  w  w. j ava 2s .  c o  m*/

    File finalFile = new File(_fileName);

    directoryPath = finalFile.getParentFile().getAbsolutePath();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));

    StringBuilder sb = new StringBuilder();

    sb.append(writer.getBuffer().toString());

    // save file to temp location initially.
    final File f = new File(directoryPath, tempFileName);
    final ZipOutputStream out;

    if (System.getProperty("java.version").startsWith("1.6")) {
        out = new ZipOutputStream(new FileOutputStream(f));
    } else {
        out = new ZipOutputStream(new FileOutputStream(f), Charset.forName("ISO-8859-1"));
    }

    ZipEntry e = new ZipEntry(PGTUtil.dictFileName);
    out.putNextEntry(e);

    byte[] data = sb.toString().getBytes("UTF-8");
    out.write(data, 0, data.length);

    out.closeEntry();

    // embed font in PGD archive if applicable
    File fontFile = IOHandler.getFontFile(core.getPropertiesManager().getFontCon());

    if (fontFile != null) {
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(fontFile);
        out.putNextEntry(new ZipEntry(PGTUtil.fontFileName));
        int length;

        while ((length = fis.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }

        out.closeEntry();
        fis.close();
    }

    // write all logograph images to file
    Iterator<LogoNode> it = core.getLogoCollection().getAllLogos().iterator();
    if (it.hasNext()) {
        out.putNextEntry(new ZipEntry(PGTUtil.logoGraphSavePath));

        while (it.hasNext()) {
            LogoNode curNode = it.next();
            out.putNextEntry(new ZipEntry(PGTUtil.logoGraphSavePath + curNode.getId().toString() + ".png"));

            ImageIO.write(curNode.getLogoGraph(), "png", out);

            out.closeEntry();
        }
    }

    out.finish();
    out.close();

    // attempt to open file in dummy core. On success, copy file to end
    // destination, on fail, delete file, and inform user by bubbling error
    try {
        DictCore test = new DictCore();
        test.readFile(f.getAbsolutePath());

    } catch (Exception ex) {
        f.delete();

        throw new IOException(ex);
    }

    try {
        if (System.getProperty("java.version").startsWith("1.6")) {
            if (finalFile.exists()) {
                finalFile.delete();
            }
            FileUtils.copyFile(f, finalFile);
        } else {
            java.nio.file.Files.copy(f.toPath(), finalFile.toPath(),
                    java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        }
        f.delete();
    } catch (IOException ex) {
        f.delete();
        throw new IOException("Unable to save file: " + ex.getMessage());
    }
}

From source file:net.solarnetwork.node.backup.DefaultBackupManager.java

@Override
public void exportBackupArchive(String backupKey, OutputStream out) throws IOException {
    final BackupService service = activeBackupService();
    if (service == null) {
        return;//from  w w  w.  j  a  v a 2s  . com
    }

    final Backup backup = service.backupForKey(backupKey);
    if (backup == null) {
        return;
    }

    // create the zip archive for the backup files
    ZipOutputStream zos = new ZipOutputStream(out);
    try {
        BackupResourceIterable resources = service.getBackupResources(backup);
        for (BackupResource r : resources) {
            zos.putNextEntry(new ZipEntry(r.getBackupPath()));
            FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) {

                @Override
                public void close() throws IOException {
                    // FileCopyUtils closed the stream, which we don't want here
                }

            });
        }
        resources.close();
    } finally {
        zos.flush();
        zos.finish();
        zos.close();
    }
}

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

From source file:org.geoserver.spatialite.SpatiaLiteOutputFormat.java

/**
 * @see WFSGetFeatureOutputFormat#write(Object, OutputStream, Operation)
 *///ww  w  .j  ava 2s .co m

/*
protected void write(FeatureCollectionType featureCollection,
     OutputStream output, Operation getFeature) throws IOException, 
    ServiceException {
 //create a writer
 BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( output ) );
 //get the feature collection
 //SimpleFeatureCollection fc = (SimpleFeatureCollection) featureCollection.getFeature().get(0);
 //write out the header
 //SimpleFeatureType ft = fc.getSchema();
 bw.write("HOLA");
 bw.flush();
}
*/

public void write(List<SimpleFeatureCollection> collections, Charset charset, OutputStream output,
        GetFeatureType request) throws IOException, ServiceException {
    //We might get multiple featurecollections in our response (multiple queries?) so we need to
    //write out multiple shapefile sets, one for each query response.
    File tempDir = IOUtils.createTempDirectory("shpziptemp");

    // target charset

    try {
        // if an empty result out of feature type with unknown geometry is created, the
        // zip file will be empty and the zip output stream will break
        boolean shapefileCreated = false;
        for (SimpleFeatureCollection curCollection : collections) {

            if (curCollection.getSchema().getGeometryDescriptor() == null) {
                throw new WFSException("Cannot write geometryless shapefiles, yet " + curCollection.getSchema()
                        + " has no geometry field");
            }
            Class geomType = curCollection.getSchema().getGeometryDescriptor().getType().getBinding();
            if (GeometryCollection.class.equals(geomType) || Geometry.class.equals(geomType)) {
                // in this case we fan out the output to multiple shapefiles
                shapefileCreated |= writeCollectionToShapefiles(curCollection, tempDir, charset, request);
            } else {
                // simple case, only one and supported type
                writeCollectionToShapefile(curCollection, tempDir, charset, request);
                shapefileCreated = true;
            }

        }

        // take care of the case the output is completely empty
        if (!shapefileCreated) {
            SimpleFeatureCollection fc;
            fc = (SimpleFeatureCollection) collections.get(0);
            fc = remapCollectionSchema(fc, Point.class);
            writeCollectionToShapefile(fc, tempDir, charset, request);
            createEmptyZipWarning(tempDir);
        }

        // dump the request
        createRequestDump(tempDir, request, collections.get(0));

        // zip all the files produced
        final FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.endsWith(".shp") || name.endsWith(".shx") || name.endsWith(".dbf")
                        || name.endsWith(".prj") || name.endsWith(".cst") || name.endsWith(".txt");
            }
        };
        ZipOutputStream zipOut = new ZipOutputStream(output);
        IOUtils.zipDirectory(tempDir, zipOut, filter);
        zipOut.finish();

        // This is an error, because this closes the output stream too... it's
        // not the right place to do so
        // zipOut.close();
    } finally {
        // make sure we remove the temp directory and its contents completely now
        try {
            FileUtils.deleteDirectory(tempDir);
        } catch (IOException e) {
            LOGGER.warning("Could not delete temp directory: " + tempDir.getAbsolutePath() + " due to: "
                    + e.getMessage());
        }
    }
}

From source file:eionet.gdem.conversion.odf.OpenDocument.java

/**
 * Method unzips the ods file, replaces content.xml and meta.xml and finally zips it together again
 * @param out OutputStream/*from  w  w  w  .  j  av a2 s  .co m*/
 * @throws Exception If an error occurs.
 */
public void createOdsFile(OutputStream out) throws Exception {

    if (strContentFile == null) {
        throw new Exception("Content file is not set!");
    }

    initOdsFiles();

    FileInputStream result_file_input = null;
    FileOutputStream zip_file_output = new FileOutputStream(strOdsOutFile);
    ZipOutputStream zip_out = new ZipOutputStream(zip_file_output);

    try {
        // unzip template ods file to temp directory
        ZipUtil.unzip(strOdsTemplateFile, strWorkingFolder);
        // copy conent file into temp directory
        Utils.copyFile(new File(strContentFile),
                new File(strWorkingFolder + File.separator + CONTENT_FILE_NAME));
        // try to transform meta with XSL, if it fails then copy meta file into temp directory
        try {
            convertMetaFile();
        } catch (Throwable t) {
            Utils.copyFile(new File(strMetaFile), new File(strWorkingFolder + File.separator + META_FILE_NAME));
        }
        // zip temp directory
        ZipUtil.zipDir(strWorkingFolder, zip_out);
        zip_out.finish();
        zip_out.close();

        // Fill outputstream
        result_file_input = new FileInputStream(strOdsOutFile);
        Streams.drain(result_file_input, out);

    } catch (IOException ioe) {
        throw new Exception("Could not create OpenDocument Spreadsheet file: " + ioe.toString());
    } finally {
        IOUtils.closeQuietly(zip_out);
        IOUtils.closeQuietly(zip_file_output);
        IOUtils.closeQuietly(result_file_input);
    }
    try {
        // delete working folder and temporary ods file
        Utils.deleteFolder(strWorkingFolder);
        Utils.deleteFile(strOdsOutFile);
    } catch (Exception ioe) {
        // TODO fix logger
        // couldn't delete temp files
    }

}

From source file:com.music.service.PieceService.java

public void downloadPieces(OutputStream out, Collection<Piece> pieces) throws IOException {
    ZipOutputStream zip = new ZipOutputStream(out);
    for (Piece piece : pieces) {
        ZipEntry entry = new ZipEntry(piece.getTitle() + "-" + piece.getId() + ".mp3");
        zip.putNextEntry(entry);// w  ww  .  j a  v  a 2  s  .  co  m
        zip.write(IOUtils.toByteArray(getPieceFile(piece.getId())));
        zip.closeEntry();

        entry = new ZipEntry(piece.getTitle() + "-" + piece.getId() + ".midi");
        zip.putNextEntry(entry);
        zip.write(IOUtils.toByteArray(getPieceMidiFile(piece.getId())));
        zip.closeEntry();
    }

    ZipEntry license = new ZipEntry("license.txt");
    zip.putNextEntry(license);
    zip.write(IOUtils.toByteArray(getClass().getResourceAsStream("/emailTemplates/license.txt")));
    zip.closeEntry();
    zip.finish();
}

From source file:net.solarnetwork.node.backup.FileSystemBackupService.java

@Override
public Backup performBackup(final Iterable<BackupResource> resources) {
    if (resources == null) {
        return null;
    }/*from   w  w w  .jav a2s . c  om*/
    final Iterator<BackupResource> itr = resources.iterator();
    if (!itr.hasNext()) {
        log.debug("No resources provided, nothing to backup");
        return null;
    }
    BackupStatus status = setStatusIf(RunningBackup, Configured);
    if (status != RunningBackup) {
        return null;
    }
    final Calendar now = new GregorianCalendar();
    now.set(Calendar.MILLISECOND, 0);
    final String archiveName = String.format(ARCHIVE_NAME_FORMAT, now);
    final File archiveFile = new File(backupDir, archiveName);
    final String archiveKey = getArchiveKey(archiveName);
    log.info("Starting backup to archive {}", archiveName);
    log.trace("Backup archive: {}", archiveFile.getAbsolutePath());
    Backup backup = null;
    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)));
        while (itr.hasNext()) {
            BackupResource r = itr.next();
            log.debug("Backup up resource {} to archive {}", r.getBackupPath(), archiveName);
            zos.putNextEntry(new ZipEntry(r.getBackupPath()));
            FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) {

                @Override
                public void close() throws IOException {
                    // FileCopyUtils closes the stream, which we don't want
                }

            });
        }
        zos.flush();
        zos.finish();
        log.info("Backup complete to archive {}", archiveName);
        backup = new SimpleBackup(now.getTime(), archiveKey, archiveFile.length(), true);

        // clean out older backups
        File[] backupFiles = getAvailableBackupFiles();
        if (backupFiles != null && backupFiles.length > additionalBackupCount + 1) {
            // delete older files
            for (int i = additionalBackupCount + 1; i < backupFiles.length; i++) {
                log.info("Deleting old backup archive {}", backupFiles[i].getName());
                if (!backupFiles[i].delete()) {
                    log.warn("Unable to delete backup archive {}", backupFiles[i].getAbsolutePath());
                }
            }
        }
    } catch (IOException e) {
        log.error("IO error creating backup: {}", e.getMessage());
        setStatus(Error);
    } catch (RuntimeException e) {
        log.error("Error creating backup: {}", e.getMessage());
        setStatus(Error);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                // ignore this
            }
        }
        status = setStatusIf(Configured, RunningBackup);
        if (status != Configured) {
            // clean up if we encountered an error
            if (archiveFile.exists()) {
                archiveFile.delete();
            }
        }
    }
    return backup;
}

From source file:org.tangram.components.CodeExporter.java

@LinkAction("/codes.zip")
public TargetDescriptor codes(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!request.getRequestURI().endsWith(".zip")) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } // if/*  ww  w.ja v  a  2  s  .c  o  m*/
    if (request.getAttribute(Constants.ATTRIBUTE_ADMIN_USER) == null) {
        throw new IOException("User may not execute action");
    } // if

    long now = System.currentTimeMillis();

    response.setContentType("application/x-zip-compressed");

    CRC32 crc = new CRC32();

    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
    zos.setComment("Tangram Repository Codes");
    zos.setLevel(9);
    Collection<CodeResource> codes = codeResourceCache.getCodes();
    for (CodeResource code : codes) {
        if (StringUtils.isNotBlank(code.getAnnotation())) {
            String mimeType = CodeHelper.getNormalizedMimeType(code.getMimeType());
            String folder = CodeHelper.getFolder(mimeType);
            String extension = CodeHelper.getExtension(mimeType);
            if (mimeType.startsWith("text/")) {
                byte[] bytes = code.getCodeText().getBytes("UTF-8");
                ZipEntry ze = new ZipEntry(folder + "/" + getFilename(code) + extension);
                ze.setTime(now);
                crc.reset();
                crc.update(bytes);
                ze.setCrc(crc.getValue());
                zos.putNextEntry(ze);
                zos.write(bytes);
                zos.closeEntry();
            } // if
        } // if
    } // for
    zos.finish();
    zos.close();

    return TargetDescriptor.DONE;
}