List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
From source file:edu.dfci.cccb.mev.dataset.rest.controllers.WorkspaceController.java
@RequestMapping(value = "/export/zip", method = POST, consumes = "multipart/form-data") @ResponseStatus(OK)//ww w . j a v a 2 s . c om public byte[] export(@RequestParam("name") String name, @RequestParam("rows") List<String> rows, @RequestParam("columns") List<String> columns, @RequestParam("rowSelections") String jsonRowSelections, @RequestParam("columnSelections") String jsonColumnSelections, @RequestParam("analyses") String[] analyses, HttpServletResponse response) throws DatasetException, IOException { log.info(String.format("Offline %s, %s, %s, %s", name, rows, columns, analyses)); //creating byteArray stream, make it bufforable and passing this buffor to ZipOutputStream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream); ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream); //nw zip entry for dataset Dataset dataset = workspace.get(name); zipOutputStream.putNextEntry(new ZipEntry("dataset.json")); IOUtils.copy(new ByteArrayInputStream(mapper.writeValueAsBytes(dataset)), zipOutputStream); zipOutputStream.closeEntry(); zipAnnotations(name, "row", zipOutputStream); zipAnnotations(name, "column", zipOutputStream); if (dataset.values() instanceof IFlatFileValues) { IFlatFileValues values = (IFlatFileValues) dataset.values(); zipOutputStream.putNextEntry(new ZipEntry("values.bin")); InputStream valuesIs = values.asInputStream(); IOUtils.copy(valuesIs, zipOutputStream); zipOutputStream.closeEntry(); zipOutputStream.flush(); valuesIs.close(); } //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams int i = 0; for (String analysis : analyses) { InputStream analysisOs = new ByteArrayInputStream(analysis.getBytes(StandardCharsets.UTF_8)); zipOutputStream.putNextEntry(new ZipEntry(String.format("analysis_%d.json", i))); JsonNode analysisJson = mapper.readTree(analysis); IOUtils.copy(analysisOs, zipOutputStream); zipOutputStream.closeEntry(); zipOutputStream.flush(); analysisOs.close(); i++; } zipOutputStream.flush(); zipOutputStream.close(); byte[] ret = byteArrayOutputStream.toByteArray(); IOUtils.closeQuietly(bufferedOutputStream); IOUtils.closeQuietly(byteArrayOutputStream); response.setContentLength(ret.length); response.setContentType("application/zip"); //or something more generic... response.setHeader("Accept-Ranges", "bytes"); response.setStatus(HttpServletResponse.SC_OK); response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s.zip\"", name)); return ret; }
From source file:io.frictionlessdata.datapackage.Package.java
private void saveZip(String outputFilePath) throws IOException, DataPackageException { try (FileOutputStream fos = new FileOutputStream(outputFilePath)) { try (BufferedOutputStream bos = new BufferedOutputStream(fos)) { try (ZipOutputStream zos = new ZipOutputStream(bos)) { // File is not on the disk, test.txt indicates // only the file name to be put into the zip. ZipEntry entry = new ZipEntry("datapackage.json"); zos.putNextEntry(entry); zos.write(this.getJson().toString(JSON_INDENT_FACTOR).getBytes()); zos.closeEntry();/*www . j av a2s . c om*/ } } } }
From source file:au.org.ala.layers.web.IntersectService.java
@RequestMapping(value = WS_INTERSECT_BATCH_DOWNLOAD, method = RequestMethod.GET) public void batchDownload(@PathVariable("id") Long id, @RequestParam(value = "csv", required = false, defaultValue = "false") Boolean csv, HttpServletRequest request, HttpServletResponse response) { BatchConsumer.start(layerIntersectDao, userProperties.getProperty("batch_path")); try {/*from ww w .j a v a 2 s .c om*/ Map map = new HashMap(); BatchProducer.addInfoToMap(userProperties.getProperty("batch_path"), String.valueOf(id), map); if (map.get("finished") != null) { OutputStream os = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(userProperties.getProperty("batch_path") + File.separator + id + File.separator + "sample.csv")); if (!csv) { ZipOutputStream zip = new ZipOutputStream(os); zip.putNextEntry(new ZipEntry("sample.csv")); os = zip; } byte[] buffer = new byte[4096]; int size; while ((size = bis.read(buffer)) > 0) { os.write(buffer, 0, size); } bis.close(); os.close(); } } catch (Exception e) { e.printStackTrace(); } return; }
From source file:com.panet.imeta.trans.steps.xmloutput.XMLOutput.java
public boolean openNewFile() { boolean retval = false; data.writer = null;/* www . j a v a2s . co m*/ try { FileObject file = KettleVFS.getFileObject(buildFilename(true)); if (meta.isAddToResultFiles()) { // Add this to the result file names... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname()); resultFile.setComment("This file was created with a xml output step"); addResultFile(resultFile); } OutputStream outputStream; if (meta.isZipped()) { OutputStream fos = KettleVFS.getOutputStream(file, false); data.zip = new ZipOutputStream(fos); File entry = new File(buildFilename(false)); ZipEntry zipentry = new ZipEntry(entry.getName()); zipentry.setComment("Compressed by Kettle"); data.zip.putNextEntry(zipentry); outputStream = data.zip; } else { OutputStream fos = KettleVFS.getOutputStream(file, false); outputStream = fos; } if (meta.getEncoding() != null && meta.getEncoding().length() > 0) { log.logBasic(toString(), "Opening output stream in encoding: " + meta.getEncoding()); data.writer = new OutputStreamWriter(outputStream, meta.getEncoding()); data.writer.write(XMLHandler.getXMLHeader(meta.getEncoding()).toCharArray()); } else { log.logBasic(toString(), "Opening output stream in default encoding : " + Const.XML_ENCODING); data.writer = new OutputStreamWriter(outputStream); data.writer.write(XMLHandler.getXMLHeader(Const.XML_ENCODING).toCharArray()); } // Add the name space if defined StringBuffer nameSpace = new StringBuffer(); if ((meta.getNameSpace() != null) && (!"".equals(meta.getNameSpace()))) { nameSpace.append(" xmlns=\""); nameSpace.append(meta.getNameSpace()); nameSpace.append("\""); } // OK, write the header & the parent element: data.writer.write(("<" + meta.getMainElement() + nameSpace.toString() + ">" + Const.CR).toCharArray()); retval = true; } catch (Exception e) { logError("Error opening new file : " + e.toString()); } // System.out.println("end of newFile(), splitnr="+splitnr); data.splitnr++; return retval; }
From source file:com.streamsets.datacollector.bundles.SupportBundleManager.java
/** * Return InputStream from which a new generated resource bundle can be retrieved. *//* w ww . j a v a 2s . c o m*/ public SupportBundle generateNewBundleFromInstances(List<BundleContentGenerator> generators, BundleType bundleType) throws IOException { PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = new PipedOutputStream(); inputStream.connect(outputStream); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); executor.submit(() -> generateNewBundleInternal(generators, bundleType, zipOutputStream)); String bundleName = generateBundleName(bundleType); String bundleKey = generateBundleDate(bundleType) + "/" + bundleName; return new SupportBundle(bundleKey, bundleName, inputStream); }
From source file:io.neba.core.logviewer.LogfileViewerConsolePlugin.java
/** * Streams the contents of the log directory as a zip file. *//*from w w w. ja v a2 s . com*/ 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:it.govpay.web.rs.dars.base.BaseDarsService.java
@POST @Path("/esporta") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM }) public Response esporta(InputStream is, @Context UriInfo uriInfo) throws Exception { String methodName = "esporta " + this.getNomeServizio(); //+ "[" + sb.toString() + "]"; this.initLogger(methodName); BasicBD bd = null;/*from w w w . ja v a 2 s .c om*/ DarsResponse darsResponse = new DarsResponse(); darsResponse.setCodOperazione(this.codOperazione); String idsAsString = null; try { bd = BasicBD.newInstance(this.codOperazione); bd.setIdOperatore(this.getOperatoreByPrincipal(bd).getId()); ByteArrayOutputStream baosIn = new ByteArrayOutputStream(); Utils.copy(is, baosIn); baosIn.flush(); baosIn.close(); JSONObject jsonObjectFormExport = JSONObject.fromObject(baosIn.toString()); JSONArray jsonIDS = jsonObjectFormExport.getJSONArray(IDS_TO_EXPORT_PARAMETER_ID); List<RawParamValue> rawValues = new ArrayList<RawParamValue>(); for (Object key : jsonObjectFormExport.keySet()) { String value = jsonObjectFormExport.getString((String) key); if (StringUtils.isNotEmpty(value) && !"null".equals(value)) rawValues.add(new RawParamValue((String) key, value)); } idsAsString = Utils.getValue(rawValues, IDS_TO_EXPORT_PARAMETER_ID); this.log.info("Richiesto export degli elementi con id " + idsAsString + ""); List<Long> idsToExport = new ArrayList<Long>(); if (jsonIDS != null && jsonIDS.size() > 0) for (int i = 0; i < jsonIDS.size(); i++) { long id = jsonIDS.getLong(i); idsToExport.add(id); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zout = new ZipOutputStream(baos); String fileName = this.getDarsHandler().esporta(idsToExport, rawValues, uriInfo, bd, zout); this.log.info("Richiesta " + methodName + " evasa con successo, creato file: " + fileName); return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename=\"" + fileName + "\"").build(); } catch (ExportException e) { this.log.info("Esito operazione " + methodName + " [" + idsAsString + "] : " + e.getEsito() + ", causa: " + e.getMessaggi()); darsResponse.setEsitoOperazione(e.getEsito()); darsResponse.setDettaglioEsito(e.getMessaggi()); return Response.ok(darsResponse, MediaType.APPLICATION_JSON).build(); } catch (WebApplicationException e) { this.log.error("Riscontrato errore di autorizzazione durante l'esecuzione del metodo " + methodName + ":" + e.getMessage(), e); throw e; } catch (Exception e) { this.log.error("Esito operazione " + methodName + " [" + idsAsString + "], causa: " + e.getMessage(), e); if (bd != null) bd.rollback(); return Response.serverError().build(); } finally { this.response.setHeader("Access-Control-Allow-Origin", "*"); this.response.setHeader("Access-Control-Expose-Headers", "content-disposition"); if (bd != null) bd.closeConnection(); } }
From source file:com.simiacryptus.mindseye.lang.Layer.java
/** * Write zip.// ww w . j av a 2 s .c om * * @param out the out * @param precision the precision */ default void writeZip(@Nonnull File out, SerialPrecision precision) { try (@Nonnull ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(out))) { writeZip(zipOutputStream, precision); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:ZipTransformTest.java
public void testStringZipEntryTransformerInStream() throws IOException { final String name = "foo"; String FILE_CONTENTS = "bar"; final byte[] contents = FILE_CONTENTS.getBytes(); File file1 = File.createTempFile("temp", null); File file2 = File.createTempFile("temp", null); try {/*from ww w. jav a 2 s.c o m*/ // Create the ZIP file ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1)); try { zos.putNextEntry(new ZipEntry(name)); zos.write(contents); zos.closeEntry(); } finally { IOUtils.closeQuietly(zos); } // Transform the ZIP file FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(file1); out = new FileOutputStream(file2); ZipUtil.transformEntry(in, name, new StringZipEntryTransformer("UTF-8") { protected String transform(ZipEntry zipEntry, String input) throws IOException { return input.toUpperCase(); } }, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } // Test the ZipUtil byte[] actual = ZipUtil.unpackEntry(file2, name); assertEquals(FILE_CONTENTS.toUpperCase(), new String(actual)); } finally { FileUtils.deleteQuietly(file1); FileUtils.deleteQuietly(file2); } }
From source file:net.firejack.platform.core.utils.ArchiveUtils.java
/** * @param zipFile//from w ww.j av a 2 s . c o m * @param files * @throws java.io.IOException */ public static void addFilesToZip(File zipFile, Map<String, File> files) throws IOException { // get a temp file File tempFile = File.createTempFile(zipFile.getName(), null); // delete it, otherwise you cannot rename your existing zip to it. FileUtils.deleteQuietly(tempFile); boolean renameOk = zipFile.renameTo(tempFile); if (!renameOk) { throw new RuntimeException( "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath()); } ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean notInFiles = true; for (Map.Entry<String, File> e : files.entrySet()) { if (e.getKey().equals(name)) { notInFiles = false; break; } } if (notInFiles) { out.putNextEntry(new ZipEntry(name)); IOUtils.copy(zin, out); } entry = zin.getNextEntry(); } // Close the streams zin.close(); // Compress the files for (Map.Entry<String, File> e : files.entrySet()) { InputStream in = new FileInputStream(e.getValue()); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(e.getKey())); // Transfer bytes from the file to the ZIP file IOUtils.copy(in, out); // Complete the entry out.closeEntry(); IOUtils.closeQuietly(in); } // Complete the ZIP file IOUtils.closeQuietly(out); FileUtils.deleteQuietly(tempFile); }