List of usage examples for java.util.zip ZipOutputStream finish
public void finish() throws IOException
From source file:org.bimserver.servlets.DownloadServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w ww.j av a 2 s.c om*/ String acceptEncoding = request.getHeader("Accept-Encoding"); boolean useGzip = false; if (acceptEncoding != null && acceptEncoding.contains("gzip")) { useGzip = true; } OutputStream outputStream = response.getOutputStream(); boolean zip = request.getParameter("zip") != null && request.getParameter("zip").equals("on"); if (useGzip && !zip) { response.setHeader("Content-Encoding", "gzip"); outputStream = new GZIPOutputStream(response.getOutputStream()); } String token = (String) request.getSession().getAttribute("token"); if (token == null) { token = request.getParameter("token"); } long topicId = -1; if (request.getParameter("topicId") != null) { topicId = Long.parseLong(request.getParameter("topicId")); } ServiceMap serviceMap = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL); String action = request.getParameter("action"); if (action != null) { if (action.equals("extendeddata")) { SExtendedData sExtendedData = serviceMap.getServiceInterface() .getExtendedData(Long.parseLong(request.getParameter("edid"))); SFile file = serviceMap.getServiceInterface().getFile(sExtendedData.getFileId()); if (file.getMime() != null) { response.setContentType(file.getMime()); } if (file.getFilename() != null) { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getFilename() + "\""); } outputStream.write(file.getData()); if (outputStream instanceof GZIPOutputStream) { ((GZIPOutputStream) outputStream).finish(); } outputStream.flush(); return; } else if (action.equals("getfile")) { String type = request.getParameter("type"); if (type.equals("proto")) { try { String protocolBuffersFile = serviceMap.getAdminInterface() .getProtocolBuffersFile(request.getParameter("name")); outputStream.write(protocolBuffersFile.getBytes(Charsets.UTF_8)); outputStream.flush(); } catch (ServiceException e) { LOGGER.error("", e); } } else if (type.equals("serverlog")) { try { OutputStreamWriter writer = new OutputStreamWriter(outputStream); writer.write(serviceMap.getAdminInterface().getServerLog()); writer.flush(); } catch (ServerException e) { LOGGER.error("", e); } catch (UserException e) { LOGGER.error("", e); } } } else if (action.equals("getBcfImage")) { long extendedDataId = Long.parseLong(request.getParameter("extendedDataId")); String topicGuid = request.getParameter("topicGuid"); String imageGuid = request.getParameter("imageGuid"); String name = request.getParameter("name"); BcfFile bcfFile = BcfCache.INSTANCE.get(extendedDataId); if (bcfFile == null) { SExtendedData extendedData = serviceMap.getServiceInterface() .getExtendedData(extendedDataId); long fileId = extendedData.getFileId(); SFile file = serviceMap.getServiceInterface().getFile(fileId); try { bcfFile = BcfFile.read(new ByteArrayInputStream(file.getData()), new ReadOptions(false)); BcfCache.INSTANCE.put(extendedDataId, bcfFile); } catch (BcfException e) { e.printStackTrace(); } } TopicFolder topicFolder = bcfFile.getTopicFolder(topicGuid); if (topicFolder != null) { byte[] data = topicFolder.getSnapshot(topicGuid + "/" + name); if (data != null) { response.setContentType("image/png"); IOUtils.write(data, outputStream); if (outputStream instanceof GZIPOutputStream) { ((GZIPOutputStream) outputStream).finish(); } outputStream.flush(); return; } } } } else { SSerializerPluginConfiguration serializer = null; if (request.getParameter("serializerOid") != null) { long serializerOid = Long.parseLong(request.getParameter("serializerOid")); serializer = serviceMap.getServiceInterface().getSerializerById(serializerOid); } else { serializer = serviceMap.getServiceInterface() .getSerializerByName(request.getParameter("serializerName")); } if (request.getParameter("topicId") != null) { topicId = Long.parseLong(request.getParameter("topicId")); } if (topicId == -1) { response.getWriter().println("No valid topicId"); return; } SDownloadResult checkoutResult = serviceMap.getServiceInterface().getDownloadData(topicId); if (checkoutResult == null) { LOGGER.error("Invalid topicId: " + topicId); } else { DataSource dataSource = checkoutResult.getFile().getDataSource(); PluginConfiguration pluginConfiguration = new PluginConfiguration( serviceMap.getPluginInterface().getPluginSettings(serializer.getOid())); final ProgressTopic progressTopic = getBimServer().getNotificationsManager() .getProgressTopic(topicId); ProgressReporter progressReporter = new ProgressReporter() { private long lastMax; private long lastProgress; private int stage = 3; private Date start = new Date(); private String title = "Downloading..."; @Override public void update(long progress, long max) { if (progressTopic != null) { LongActionState ds = StoreFactory.eINSTANCE.createLongActionState(); ds.setStart(start); ds.setState(progress == max ? ActionState.FINISHED : ActionState.STARTED); ds.setTitle(title); ds.setStage(stage); ds.setProgress((int) Math.round(100.0 * progress / max)); progressTopic.stageProgressUpdate(ds); this.lastMax = max; this.lastProgress = progress; } } @Override public void setTitle(String title) { if (progressTopic != null) { stage++; this.title = title; LongActionState ds = StoreFactory.eINSTANCE.createLongActionState(); ds.setStart(new Date()); ds.setState(lastProgress == lastMax ? ActionState.FINISHED : ActionState.STARTED); ds.setTitle(title); ds.setStage(stage); ds.setProgress((int) Math.round(100.0 * lastProgress / lastMax)); progressTopic.stageProgressUpdate(ds); } } }; try { if (zip) { if (pluginConfiguration.getString("ZipExtension") != null) { response.setHeader("Content-Disposition", "inline; filename=\"" + dataSource.getName() + "." + pluginConfiguration.getString(SerializerPlugin.ZIP_EXTENSION) + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + dataSource.getName() + ".zip" + "\""); } response.setContentType("application/zip"); String nameInZip = dataSource.getName() + "." + pluginConfiguration.getString(SerializerPlugin.EXTENSION); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); zipOutputStream.putNextEntry(new ZipEntry(nameInZip)); processDataSource(zipOutputStream, dataSource, progressReporter); try { zipOutputStream.finish(); } catch (IOException e) { // Sometimes it's already closed, that's no problem } } else { if (request.getParameter("mime") == null) { response.setContentType( pluginConfiguration.getString(SerializerPlugin.CONTENT_TYPE)); response.setHeader("Content-Disposition", "inline; filename=\"" + dataSource.getName() + "." + pluginConfiguration.getString(SerializerPlugin.EXTENSION) + "\""); } else { response.setContentType(request.getParameter("mime")); } processDataSource(outputStream, dataSource, progressReporter); } } catch (SerializerException s) { if (s.getCause() != null && s.getCause() instanceof IOException) { } else { LOGGER.error("", s); } LongActionState ds = StoreFactory.eINSTANCE.createLongActionState(); ds.setStart(new Date()); ds.setState(ActionState.AS_ERROR); ds.setTitle("Serialization Error"); ds.setProgress(-1); ds.setStage(3); ds.getErrors().add(s.getMessage()); progressTopic.stageProgressUpdate(ds); } } } if (outputStream instanceof GZIPOutputStream) { ((GZIPOutputStream) outputStream).finish(); } outputStream.flush(); } catch (NumberFormatException e) { LOGGER.error("", e); response.getWriter().println("Some number was incorrectly formatted"); } catch (ServiceException e) { LOGGER.error("", e); response.getWriter().println(e.getUserMessage()); } catch (EOFException e) { } catch (Exception e) { LOGGER.error("", e); } }
From source file:org.structr.core.graph.SyncCommand.java
/** * Exports the given part of the structr database to the given output stream. * * @param outputStream/*from ww w . j av a 2s . 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.theospi.portfolio.guidance.impl.GuidanceManagerImpl.java
public void packageGuidanceForExport(List guidanceIds, OutputStream os) throws IOException { CheckedOutputStream checksum = new CheckedOutputStream(os, new Adler32()); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(checksum)); List exportedRefs = new ArrayList(); for (Iterator i = guidanceIds.iterator(); i.hasNext();) { String id = (String) i.next(); processGuidance(id, zos, exportedRefs); }// ww w . jav a 2s .c o m zos.finish(); zos.flush(); }
From source file:org.dspace.app.itemexport.ItemExport.java
public static void zip(String strSource, String target) throws Exception { ZipOutputStream cpZipOutputStream = null; String tempFileName = target + "_tmp"; try {/*from w ww . jav a 2 s. c o m*/ File cpFile = new File(strSource); if (!cpFile.isFile() && !cpFile.isDirectory()) { return; } File targetFile = new File(tempFileName); if (!targetFile.createNewFile()) { log.warn("Target file already exists: " + targetFile.getName()); } FileOutputStream fos = new FileOutputStream(tempFileName); cpZipOutputStream = new ZipOutputStream(fos); cpZipOutputStream.setLevel(9); zipFiles(cpFile, strSource, tempFileName, cpZipOutputStream); cpZipOutputStream.finish(); cpZipOutputStream.close(); cpZipOutputStream = null; // Fix issue on Windows with stale file handles open before trying to delete them System.gc(); deleteDirectory(cpFile); if (!targetFile.renameTo(new File(target))) { log.error("Unable to rename file"); } } finally { if (cpZipOutputStream != null) { cpZipOutputStream.close(); } } }
From source file:org.openmrs.module.reporting.report.renderer.DelimitedTextReportRenderer.java
/** * @see ReportRenderer#render(ReportData, String, OutputStream) */// w w w .jav a2 s . com public void render(ReportData results, String argument, OutputStream out) throws IOException, RenderingException { DataSet dataset = results.getDataSets().values().iterator().next(); ReportDesign design = getDesign(argument); String textDelimiter = getTextDelimiter(design); String fieldDelimiter = getFieldDelimiter(design); String lineEnding = getLineEnding(design); String characterEncoding = getCharacterEncoding(design); Pattern blacklistRegex = getBlacklistRegex(design); DateFormat dateFormat = getDateFormat(design); if (results.getDataSets().size() > 1) { ZipOutputStream zip = new ZipOutputStream(out); Set<String> usedFilenames = new HashSet<String>(); for (Map.Entry<String, DataSet> e : results.getDataSets().entrySet()) { String fn = getFilenameBaseForName(e.getKey(), usedFilenames) + "." + getFilenameExtension(getDesign(argument)); zip.putNextEntry(new ZipEntry(fn)); writeDataSet(e.getValue(), zip, textDelimiter, fieldDelimiter, lineEnding, characterEncoding, blacklistRegex, dateFormat); zip.closeEntry(); } zip.finish(); } else { writeDataSet(dataset, out, textDelimiter, fieldDelimiter, lineEnding, characterEncoding, blacklistRegex, dateFormat); } }
From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java
/** * Create a XAR file using java.util.zip. * * @param docs The documents to include. * @param encodings The charset for each document. * @param packageXmlEncoding The encoding of package.xml * @return the XAR file as a byte array. *///from w w w . j a v a 2 s . c om protected byte[] createZipFile(XWikiDocument docs[], String[] encodings, String packageXmlEncoding) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); ZipEntry zipp = new ZipEntry("package.xml"); zos.putNextEntry(zipp); zos.write(getEncodedByteArray(getPackageXML(docs, packageXmlEncoding), packageXmlEncoding)); for (int i = 0; i < docs.length; i++) { String zipEntryName = docs[i].getSpace() + "/" + docs[i].getName(); if (docs[i].getTranslation() != 0) { zipEntryName += "." + docs[i].getLanguage(); } ZipEntry zipe = new ZipEntry(zipEntryName); zos.putNextEntry(zipe); String xmlCode = docs[i].toXML(false, false, false, false, getContext()); zos.write(getEncodedByteArray(xmlCode, encodings[i])); } zos.finish(); zos.close(); return baos.toByteArray(); }
From source file:io.neba.core.logviewer.LogfileViewerConsolePlugin.java
/** * Streams the contents of the log directory as a zip file. */// w ww . ja v a2 s . c om private void download(HttpServletResponse res, HttpServletRequest req) throws IOException { final String selectedLogfile = req.getParameter("file"); final String filenameSuffix = isEmpty(selectedLogfile) ? "" : "-" + substringAfterLast(selectedLogfile, File.separator); res.setContentType("application/zip"); res.setHeader("Content-Disposition", "attachment;filename=logfiles-" + req.getServerName() + filenameSuffix + ".zip"); ZipOutputStream zos = new ZipOutputStream(res.getOutputStream()); try { for (File file : this.logFiles.resolveLogFiles()) { if (selectedLogfile != null && !file.getAbsolutePath().equals(selectedLogfile)) { continue; } ZipEntry ze = new ZipEntry(toZipFileEntryName(file)); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(file); try { copy(in, zos); zos.closeEntry(); } finally { closeQuietly(in); } } zos.finish(); } finally { closeQuietly(zos); } }
From source file:org.apache.sling.oakui.OakUIWebConsole.java
private void downloadSegment(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull String index, @Nonnull String file) throws IOException { NodeStore ns = getNodeStore();/*w w w .j av a 2 s . co m*/ NodeState oakIndex = ns.getRoot().getChildNode("oak:index"); NodeStoreDirectory nsDirectory = new NodeStoreDirectory(oakIndex, index); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"" + index + ".zip\";"); ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream()); for (String f : nsDirectory.listAll()) { ZipEntry ze = new ZipEntry(f); ze.setSize(nsDirectory.fileLength(f)); ze.setTime(nsDirectory.getLastModified(f)); zipOutputStream.putNextEntry(ze); OakIndexInput input = nsDirectory.openInput(f); transferBytes(input, zipOutputStream); zipOutputStream.closeEntry(); } zipOutputStream.finish(); }
From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java
public static File generateZipFile(List<File> files, String dirPath) { File dir_file = new File(dirPath); File zip_file = new File(dirPath + "/temp_" + (fileNum++) + ".zip"); int dir_l = dir_file.getAbsolutePath().length(); FileOutputStream fos = null;/*w w w.ja v a2 s . c o m*/ try { fos = new FileOutputStream(zip_file); } catch (FileNotFoundException e1) { log.warning("File not found", e1); return null; } ZipOutputStream zipout = new ZipOutputStream(fos); zipout.setLevel(1); for (int i = 0; i < files.size(); i++) { File f = (File) files.get(i); if (f.canRead()) { log.info("Adding file: " + f.getAbsolutePath()); try { zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1))); } catch (Exception e) { log.warning("Error adding to zip file", e); return null; } BufferedInputStream fr; try { fr = new BufferedInputStream(new FileInputStream(f)); byte buffer[] = new byte[0xffff]; int b; while ((b = fr.read(buffer)) != -1) zipout.write(buffer, 0, b); fr.close(); zipout.closeEntry(); } catch (Exception e) { log.warning("Error closing zip file", e); return null; } } } try { zipout.finish(); fos.flush(); } catch (IOException e) { e.printStackTrace(); return null; } log.info("file zipped and returning as " + zip_file.getAbsolutePath()); return zip_file; }
From source file:org.geoserver.wfs.response.ShapeZipOutputFormat.java
/** * @see WFSGetFeatureOutputFormat#write(Object, OutputStream, Operation) */// w ww. j av a2 s . c o m public void write(List<SimpleFeatureCollection> collections, Charset charset, OutputStream output, GetFeatureRequest 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(request, "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()); } } }