List of usage examples for java.util.zip ZipOutputStream putNextEntry
public void putNextEntry(ZipEntry e) throws IOException
From source file:csns.web.controller.DownloadController.java
private long addToZip(ZipOutputStream zip, String dir, Collection<File> files) throws IOException { files = removeDuplicates(files);//from w ww. ja v a 2 s . c om long totalSize = 0; for (File file : files) { ZipEntry entry = new ZipEntry(dir + "/" + file.getName()); zip.putNextEntry(entry); fileIO.copy(file, zip); zip.closeEntry(); totalSize += entry.getCompressedSize(); } return totalSize; }
From source file:at.alladin.rmbt.controlServer.QualityOfServiceExportResource.java
@Get public Representation request(final String entity) { //Before doing anything => check if a cached file already exists and is new enough String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); final File generatingFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); if (cachedFile.exists()) { //check if file has been recently created OR a file is currently being created if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime()) || (generatingFile.exists() && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) { //if so, return the cached file instead of a cost-intensive new one final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override/*from w w w. j a v a 2 s .c om*/ public void write(OutputStream out) throws IOException { InputStream is = new FileInputStream(cachedFile); IOUtils.copy(is, out); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; } } //final List<String> data = new ArrayList<String>(); final StringBuilder sb = new StringBuilder(); QoSTestObjectiveDao nnObjectiveDao = new QoSTestObjectiveDao(conn); QoSTestDescDao nnDescDao = new QoSTestDescDao(conn, null); try { Map<String, List<QoSTestObjective>> map = nnObjectiveDao.getAllToMap(); Iterator<String> keys = map.keySet().iterator(); sb.append("<h1>Contents:</h1>"); sb.append("<ol>"); sb.append("<li><a href=\"#table1\">qos_test_objective</a></li>"); sb.append("<li><a href=\"#table2\">qos_test_desc</a></li>"); sb.append("</ol><br>"); sb.append("<h1 id=\"table1\">Test objectives table (qos_test_objective)</h1>"); while (keys.hasNext()) { String testType = keys.next(); List<QoSTestObjective> list = map.get(testType); sb.append("<h2>Test group: " + testType.toUpperCase() + "</h2><ul>"); //data.add("<h2>Test group: " + testType.toUpperCase() + "</h2>"); for (QoSTestObjective item : list) { //data.add(item.toHtml()); sb.append("<li>"); sb.append(item.toHtml()); sb.append("</li>"); } sb.append("</ul>"); } Map<String, List<QoSTestDesc>> descMap = nnDescDao.getAllToMapIgnoreLang(); keys = descMap.keySet().iterator(); sb.append("<h1 id=\"table2\">Language table (qos_test_desc)</h1><ul>"); while (keys.hasNext()) { String descKey = keys.next(); List<QoSTestDesc> list = descMap.get(descKey); sb.append("<li><h4 id=\"" + descKey.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">KEY (column: desc_key): <i>" + descKey + "</i></h4><ul>"); //data.add("<h3>KEY: <i>" + descKey + "</i></h3><ul>"); for (QoSTestDesc item : list) { sb.append("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); //data.add("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); } sb.append("</ul></li>"); //data.add("</ul>"); } sb.append("</ul>"); } catch (final SQLException e) { e.printStackTrace(); return null; } final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override public void write(OutputStream out) throws IOException { //cache in file => create temporary temporary file (to // handle errors while fulfilling a request) String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); OutputStream outf = new FileOutputStream(cachedFile); if (zip) { final ZipOutputStream zos = new ZipOutputStream(outf); final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt"); zos.putNextEntry(zeLicense); final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt"); IOUtils.copy(licenseIS, zos); licenseIS.close(); final ZipEntry zeCsv = new ZipEntry(FILENAME_HTML); zos.putNextEntry(zeCsv); outf = zos; } try (OutputStreamWriter osw = new OutputStreamWriter(outf)) { osw.write(sb.toString()); osw.flush(); } if (zip) outf.close(); //if we reach this code, the data is now cached in a temporary tmp-file //so, rename the file for "production use2 //concurrency issues should be solved by the operating system File newCacheFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); FileInputStream fis = new FileInputStream(newCacheFile); IOUtils.copy(fis, out); fis.close(); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; }
From source file:com.espringtran.compressor4j.processor.Bzip2Processor.java
/** * Compress data//from w w w . j a v a2 s . c om * * @param fileCompressor * FileCompressor object * @return * @throws Exception */ @Override public byte[] compressData(FileCompressor fileCompressor) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BZip2CompressorOutputStream cos = new BZip2CompressorOutputStream(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:com.espringtran.compressor4j.processor.GzipProcessor.java
/** * Compress data/*from w w w .j a v a2 s . c o 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:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java
@Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); this.zipFile = this.temporaryFolder.newFile("zipfile.zip"); ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(this.zipFile)); try {//from w w w .j av a 2 s .c o m zipOutputStream.putNextEntry(new ZipEntry("/a/b/c.txt")); zipOutputStream.write("c".getBytes()); zipOutputStream.putNextEntry(new ZipEntry("/d/")); zipOutputStream.putNextEntry(new ZipEntry("/d/e/")); zipOutputStream.putNextEntry(new ZipEntry("/d/f/")); zipOutputStream.putNextEntry(new ZipEntry("/d/f/g.txt")); zipOutputStream.putNextEntry(new ZipEntry("/d/f/h/")); zipOutputStream.write("g".getBytes()); } finally { zipOutputStream.close(); } this.zip = new ZipArchive(new LocalFolder(this.zipFile.getParentFile()).getFile(this.zipFile.getName())); }
From source file:com.solidmaps.webapp.service.ApostilamentosServiceImpl.java
private void addToZip(ZipOutputStream zos, String file) { if (StringUtils.isBlank(file)) { return;//from w w w . j a va 2 s .co m } byte[] buffer = new byte[1024]; try { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(FILE_PATH + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:isl.FIMS.utils.Utils.java
public static void createZip(String zipFile, String sourceDirectory) { try {/*w ww. j a v a 2 s .com*/ // String zipFile = "C:/FileIO/zipdemo.zip"; // String sourceDirectory = "C:/examples"; //create byte buffer byte[] buffer = new byte[1024]; //create object of FileOutputStream FileOutputStream fout = new FileOutputStream(zipFile); //create object of ZipOutputStream from FileOutputStream ZipOutputStream zout = new ZipOutputStream(fout); //create File object from directory name File dir = new File(sourceDirectory); //check to see if this directory exists if (!dir.isDirectory()) { } else { File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { //create object of FileInputStream for source file FileInputStream fin = new FileInputStream(files[i]); zout.putNextEntry(new ZipEntry(files[i].getName())); int length; while ((length = fin.read(buffer)) > 0) { zout.write(buffer, 0, length); } zout.closeEntry(); //close the InputStream fin.close(); } } } //close the ZipOutputStream zout.close(); } catch (IOException ioe) { } }
From source file:org.eclipse.cft.server.core.internal.CloudUtil.java
private static void addZipEntries(ZipOutputStream out, List<IModuleResource> allResources, Set<IModuleResource> filterInFiles) throws Exception { if (allResources == null) return;/*from w w w .j a va 2s . c o m*/ for (IModuleResource resource : allResources) { if (resource instanceof IModuleFolder) { IModuleResource[] folderResources = ((IModuleFolder) resource).members(); String entryPath = getZipRelativeName(resource); ZipEntry zipEntry = new ZipEntry(entryPath); long timeStamp = 0; IContainer folder = (IContainer) resource.getAdapter(IContainer.class); if (folder != null) { timeStamp = folder.getLocalTimeStamp(); } if (timeStamp != IResource.NULL_STAMP && timeStamp != 0) { zipEntry.setTime(timeStamp); } out.putNextEntry(zipEntry); out.closeEntry(); addZipEntries(out, Arrays.asList(folderResources), filterInFiles); continue; } IModuleFile moduleFile = (IModuleFile) resource; // Only add files that are in the filterInList if (!filterInFiles.contains(moduleFile)) { continue; } String entryPath = getZipRelativeName(resource); ZipEntry zipEntry = new ZipEntry(entryPath); InputStream input = null; long timeStamp = 0; IFile iFile = (IFile) moduleFile.getAdapter(IFile.class); if (iFile != null) { timeStamp = iFile.getLocalTimeStamp(); input = iFile.getContents(); } else { File file = (File) moduleFile.getAdapter(File.class); timeStamp = file.lastModified(); input = new FileInputStream(file); } if (timeStamp != IResource.NULL_STAMP && timeStamp != 0) { zipEntry.setTime(timeStamp); } out.putNextEntry(zipEntry); try { int n = 0; while (n > -1) { n = input.read(buf); if (n > 0) { out.write(buf, 0, n); } } } finally { input.close(); } out.closeEntry(); } }
From source file:com.liferay.ide.server.remote.AbstractRemoteServerPublisher.java
protected void addToZip(IPath path, IResource resource, ZipOutputStream zip, boolean adjustGMTOffset) throws IOException, CoreException { switch (resource.getType()) { case IResource.FILE: ZipEntry zipEntry = new ZipEntry(path.toString()); zip.putNextEntry(zipEntry); InputStream contents = ((IFile) resource).getContents(); if (adjustGMTOffset) { TimeZone currentTimeZone = TimeZone.getDefault(); Calendar currentDt = new GregorianCalendar(currentTimeZone, Locale.getDefault()); // Get the Offset from GMT taking current TZ into account int gmtOffset = currentTimeZone.getOffset(currentDt.get(Calendar.ERA), currentDt.get(Calendar.YEAR), currentDt.get(Calendar.MONTH), currentDt.get(Calendar.DAY_OF_MONTH), currentDt.get(Calendar.DAY_OF_WEEK), currentDt.get(Calendar.MILLISECOND)); zipEntry.setTime(System.currentTimeMillis() + (gmtOffset * -1)); }/* w ww . j ava 2 s .c o m*/ try { IOUtils.copy(contents, zip); } finally { contents.close(); } break; case IResource.FOLDER: case IResource.PROJECT: IContainer container = (IContainer) resource; IResource[] members = container.members(); for (IResource res : members) { addToZip(path.append(res.getName()), res, zip, adjustGMTOffset); } } }
From source file:com.stimulus.archiva.presentation.ExportBean.java
@Override protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SearchBean searchBean = (SearchBean) form; String outputDir = Config.getFileSystem().getViewPath() + File.separatorChar; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String zipFileName = "export-" + sdf.format(new Date()) + ".zip"; File zipFile = new File(outputDir + zipFileName); String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { String codedfilename = URLEncoder.encode(zipFileName, "UTF8"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { String codedfilename = MimeUtility.encodeText(zipFileName, "UTF8", "B"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else {//from ww w . j ava2 s . c o m response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName); } logger.debug("size of searchResult = " + searchBean.getSearchResults().size()); //MessageBean.viewMessage List<File> files = new ArrayList<File>(); for (SearchResultBean searchResult : searchBean.getSearchResults()) { if (searchResult.getSelected()) { Email email = MessageService.getMessageByID(searchResult.getVolumeID(), searchResult.getUniqueID(), false); HttpServletRequest hsr = ActionContext.getActionContext().getRequest(); String baseURL = hsr.getRequestURL().substring(0, hsr.getRequestURL().lastIndexOf(hsr.getServletPath())); MessageExtraction messageExtraction = MessageService.extractMessage(email, baseURL, true); // can take a while to extract message // MessageBean mbean = new MessageBean(); // mbean.setMessageID(searchResult.getUniqueID()); // mbean.setVolumeID(searchResult.getVolumeID()); // writer.println(searchResult.toString()); // writer.println(messageExtraction.getFileName()); File fileToAdd = new File(outputDir, messageExtraction.getFileName()); if (!files.contains(fileToAdd)) { files.add(fileToAdd); } } } ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); try { byte[] buf = new byte[1024]; for (File f : files) { ZipEntry ze = new ZipEntry(f.getName()); logger.debug("Adding file " + f.getName()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); for (;;) { int len = is.read(buf); if (len < 0) break; zos.write(buf, 0, len); } is.close(); Config.getFileSystem().getTempFiles().markForDeletion(f); } } finally { zos.close(); } logger.debug("download zipped emails {fileName='" + zipFileName + "'}"); String contentType = "application/zip"; Config.getFileSystem().getTempFiles().markForDeletion(zipFile); return new FileStreamInfo(contentType, zipFile); }