List of usage examples for java.util.zip ZipOutputStream setLevel
public void setLevel(int level)
From source file:ZipImploder.java
protected void configure(ZipOutputStream zos, String comment, int method, int level) { if (comment != null) { zos.setComment(comment);/*ww w.j a va 2 s .co m*/ } if (method >= 0) { zos.setMethod(method); } if (level >= 0) { zos.setLevel(level); } }
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 w ww . j ava 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.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 . j a v a 2s .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.deidentifier.arx.gui.worker.WorkerSave.java
@Override public void run(final IProgressMonitor arg0) throws InvocationTargetException, InterruptedException { arg0.beginTask(Resources.getMessage("WorkerSave.0"), 8); //$NON-NLS-1$ File temp = null;/*from ww w . j a v a2 s . c o m*/ try { temp = File.createTempFile("arx", "deid"); final FileOutputStream f = new FileOutputStream(temp); final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f)); zip.setLevel(Deflater.BEST_SPEED); model.createConfig(); writeMetadata(model, zip); arg0.worked(1); writeModel(model, zip); arg0.worked(1); writeInput(model, zip); arg0.worked(1); writeOutput(model, zip); arg0.worked(1); writeConfiguration(model, zip); arg0.worked(1); final Map<String, Integer> map = writeLattice(model, zip); arg0.worked(1); writeClipboard(model, map, zip); arg0.worked(1); writeFilter(model, zip); zip.close(); arg0.worked(1); FileUtils.copyFile(temp, new File(path)); FileUtils.deleteQuietly(temp); } catch (final Exception e) { error = e; arg0.done(); FileUtils.deleteQuietly(temp); return; } arg0.done(); }
From source file:com.cordys.coe.ac.emailio.archive.FileArchiver.java
/** * This method starts the actual archiving of the passed on context containers. * * @param lccContainers The containers to archive. * @param spqmManager The QueryManager to use. * * @throws ArchiverException In case of any exceptions. * * @see com.cordys.coe.ac.emailio.archive.IArchiver#doArchive(java.util.List, com.cordys.coe.ac.emailio.objects.IStorageProviderQueryManager) *//*from w ww.j a v a 2 s . co m*/ @Override public void doArchive(List<ContextContainer> lccContainers, IStorageProviderQueryManager spqmManager) throws ArchiverException { File fArchive = getArchiveFolder(); for (ContextContainer ccContainer : lccContainers) { int iWrapperXML = 0; ZipOutputStream zosZip = null; File fZipFile = null; List<EmailMessage> lEmails = null; try { lEmails = spqmManager.getEmailMessagesByContextID(ccContainer.getID()); // Create the ZipFile fZipFile = new File(fArchive, ccContainer.getID().replaceAll("[^a-zA-Z0-9]", "") + ".zip"); zosZip = new ZipOutputStream(new FileOutputStream(fZipFile, false)); zosZip.setLevel(m_iZipLevel); // Now we have both the container and the emails. We will create an XML // to hold all data. int iObjectData = ccContainer._getObjectData(); // Create the zip entry for it. ZipEntry zeContainer = new ZipEntry("container.xml"); zosZip.putNextEntry(zeContainer); String sXML = Node.writeToString(iObjectData, true); zosZip.write(sXML.getBytes()); zosZip.closeEntry(); // Add the email messages to the zip file. int iCount = 0; for (EmailMessage emMessage : lEmails) { iObjectData = emMessage._getObjectData(); ZipEntry zeEmail = new ZipEntry("email_" + iCount++ + ".xml"); zosZip.putNextEntry(zeEmail); sXML = Node.writeToString(iObjectData, true); zosZip.write(sXML.getBytes()); zosZip.closeEntry(); } // Now all files are written into a single Zip file, so we can close it. } catch (Exception e) { throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ARCHIVING_CONTAINER_0, ccContainer.getID()); } finally { if (iWrapperXML != 0) { Node.delete(iWrapperXML); } if (zosZip != null) { try { zosZip.close(); } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Error closing zip file " + fZipFile.getAbsolutePath(), e); } } } } // If we get here the zipfile was successfully created. So now we need to remove the // mails and the container from the current storage provider. try { spqmManager.removeContextContainer(ccContainer); if (LOG.isDebugEnabled()) { LOG.debug("Archived the container with id " + ccContainer.getID()); } } catch (StorageProviderException e) { throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_REMOVING_CONTEXT_CONTAINER_0_FROM_THE_STORAGE, ccContainer.getID()); } } // Now all containers have been archived, we will create a single zip file. try { File fFinalArchive = new File(fArchive.getParentFile(), fArchive.getName() + ".zip"); if (LOG.isDebugEnabled()) { LOG.debug("Archiving folder " + fArchive.getCanonicalPath() + " into file " + fFinalArchive.getCanonicalPath()); } new ZipUtil().compress(fArchive, fFinalArchive.getAbsolutePath()); } catch (Exception e) { throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ZIPPING_ALL_ARCHIVE_FILES); } }
From source file:org.egov.stms.notice.service.SewerageNoticeService.java
/** * @param inputStream//from ww w . j a v a 2 s.co m * @param noticeNo * @param out * @return zip output stream file */ public ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo, final ZipOutputStream out) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Entered into addFilesToZip method"); final byte[] buffer = new byte[1024]; try { 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_ADD_FILES_TO_ZIP, iae); throw new ValidationException(Arrays.asList(new ValidationError("error", iae.getMessage()))); } catch (final FileNotFoundException fnfe) { LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, fnfe); throw new ValidationException(Arrays.asList(new ValidationError("error", fnfe.getMessage()))); } catch (final IOException ioe) { LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, ioe); throw new ValidationException(Arrays.asList(new ValidationError("error", ioe.getMessage()))); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Exit from addFilesToZip method"); return out; }
From source file:VASSAL.tools.io.ZipArchive.java
private void writeToDisk() throws IOException { // write all files to a temporary zip archive final File tmpFile = File.createTempFile("tmp", ".zip", archiveFile.getParentFile()); ZipOutputStream out = null; try {// ww w. j a v a 2 s .c o m out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile))); out.setLevel(9); final byte[] buf = new byte[8192]; if (zipFile != null) { zipFile.close(); zipFile = null; // copy unmodified file into the temp archive ZipInputStream in = null; try { in = new ZipInputStream(new BufferedInputStream(new FileInputStream(archiveFile))); ZipEntry ze = null; while ((ze = in.getNextEntry()) != null) { // skip modified or removed entries final Entry e = entries.get(ze.getName()); if (e == null || e.file != null) continue; // We can't reuse entries for compressed files because there's // no way to reset all fields to acceptable values. if (ze.getMethod() == ZipEntry.DEFLATED) { ze = new ZipEntry(ze.getName()); ze.setTime(ze.getTime()); } out.putNextEntry(ze); IOUtils.copy(in, out, buf); entries.remove(ze.getName()); } in.close(); } finally { IOUtils.closeQuietly(in); } } for (String name : entries.keySet()) { final Entry e = entries.get(name); // write new or modified file into the temp archive FileInputStream in = null; try { in = new FileInputStream(e.file); out.putNextEntry(e.ze); IOUtils.copy(in, out, buf); in.close(); } finally { IOUtils.closeQuietly(in); } } out.close(); } finally { IOUtils.closeQuietly(out); } // Replace old archive with temp archive. if (!tmpFile.renameTo(archiveFile)) { try { FileUtils.forceDelete(archiveFile); FileUtils.moveFile(tmpFile, archiveFile); } catch (IOException e) { String err = "Unable to overwrite " + archiveFile.getAbsolutePath() + ": "; if (!archiveFile.exists()) { err += " file does not exist."; } else if (!archiveFile.canWrite()) { err += " file is not writable."; } else if (!archiveFile.isFile()) { err += " not a normal file."; } err += " Data written to " + tmpFile.getAbsolutePath() + " instead."; throw (IOException) new IOException(err).initCause(e); } } closed = true; modified = false; entries.clear(); }
From source file:org.olat.ims.qti.export.QTIWordExport.java
@Override public void prepare(HttpServletResponse hres) { try {/*from w w w.j a v a2 s .c o m*/ hres.setCharacterEncoding(encoding); } catch (Exception e) { log.error("", e); } ZipOutputStream zout = null; try { String label = rootNode.getTitle(); String secureLabel = StringHelper.transformDisplayNameToFileSystemName(label); String file = secureLabel + ".zip"; hres.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + StringHelper.urlEncodeUTF8(file)); hres.setHeader("Content-Description", StringHelper.urlEncodeUTF8(label)); zout = new ZipOutputStream(hres.getOutputStream()); zout.setLevel(9); ZipEntry test = new ZipEntry(secureLabel + ".docx"); zout.putNextEntry(test); exportTest(label, zout, false); zout.closeEntry(); ZipEntry responses = new ZipEntry(secureLabel + "_responses.docx"); zout.putNextEntry(responses); exportTest(label, zout, true); zout.closeEntry(); } catch (Exception e) { log.error("", e); } finally { IOUtils.closeQuietly(zout); } }
From source file:com.hichinaschool.flashcards.libanki.Media.java
/** * Add files to a zip until over SYNC_ZIP_SIZE. Return zip data. * /* w w w . j a v a 2 s . c o m*/ * @return Returns a tuple with two objects. The first one is the zip file contents, the second a list with the * filenames of the files inside the zip. */ public Pair<File, List<String>> zipAdded() { File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip")); String sql = "select fname from log where type = " + Integer.toString(MEDIA_ADD); List<String> filenames = mMediaDb.queryColumn(String.class, sql, 0); List<String> fnames = new ArrayList<String>(); try { ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f))); zos.setLevel(8); JSONObject files = new JSONObject(); int cnt = 0; long sz = 0; byte buffer[] = new byte[2048]; boolean finished = true; for (String fname : filenames) { fnames.add(fname); File file = new File(getDir(), fname); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048); ZipEntry entry = new ZipEntry(Integer.toString(cnt)); zos.putNextEntry(entry); int count = 0; while ((count = bis.read(buffer, 0, 2048)) != -1) { zos.write(buffer, 0, count); } zos.closeEntry(); bis.close(); files.put(Integer.toString(cnt), fname); sz += file.length(); if (sz > SYNC_ZIP_SIZE) { finished = false; break; } cnt += 1; } if (finished) { zos.putNextEntry(new ZipEntry("_finished")); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("_meta")); zos.write(Utils.jsonToString(files).getBytes()); zos.close(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new RuntimeException(e); } return new Pair<File, List<String>>(f, fnames); }
From source file:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);/*from w ww .j av a2 s . c om*/ boolean Fileexists = false; String realZipfilename = StringUtil.environmentSubstitute(zipFilename); String realWildcard = StringUtil.environmentSubstitute(wildcard); String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude); String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory); String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory); if (realZipfilename != null) { FileObject fileObject = null; try { fileObject = KettleVFS.getFileObject(realZipfilename); // Check if Zip File exists if (fileObject.exists()) { Fileexists = true; log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label") + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label")); } else { Fileexists = false; } // Let's start the process now if (ifzipfileexists == 3 && Fileexists) { // the zip file exists and user want to Fail result.setResult(false); result.setNrErrors(1); } else if (ifzipfileexists == 2 && Fileexists) { // the zip file exists and user want to do nothing result.setResult(true); } else if (afterzip == 2 && realMovetodirectory == null) { // After Zip, Move files..User must give a destination Folder result.setResult(false); result.setNrErrors(1); log.logError(toString(), Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label")); } else // After Zip, Move files..User must give a destination Folder { if (ifzipfileexists == 0 && Fileexists) { // the zip file exists and user want to create new one with unique name //Format Date DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip"; log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label") + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")); } else if (ifzipfileexists == 1 && Fileexists) { log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label") + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label")); } // Get all the files in the directory... File f = new File(realTargetdirectory); String[] filelist = f.list(); log.logDetailed(toString(), Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory + Messages.getString("JobZipFiles.Files_Found3.Label")); Pattern pattern = null; if (!Const.isEmpty(realWildcard)) { pattern = Pattern.compile(realWildcard); } Pattern patternexclude = null; if (!Const.isEmpty(realWildcardExclude)) { patternexclude = Pattern.compile(realWildcardExclude); } // Prepare Zip File byte[] buffer = new byte[18024]; FileOutputStream dest = new FileOutputStream(realZipfilename); BufferedOutputStream buff = new BufferedOutputStream(dest); ZipOutputStream out = new ZipOutputStream(buff); // Set the method out.setMethod(ZipOutputStream.DEFLATED); // Set the compression level if (compressionrate == 0) { out.setLevel(Deflater.NO_COMPRESSION); } else if (compressionrate == 1) { out.setLevel(Deflater.DEFAULT_COMPRESSION); } if (compressionrate == 2) { out.setLevel(Deflater.BEST_COMPRESSION); } if (compressionrate == 3) { out.setLevel(Deflater.BEST_SPEED); } // Specify Zipped files (After that we will move,delete them...) String[] ZippedFiles = new String[filelist.length]; int FileNum = 0; // Get the files in the list... for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) { boolean getIt = true; boolean getItexclude = false; // First see if the file matches the regular expression! if (pattern != null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (patternexclude != null) { Matcher matcherexclude = patternexclude.matcher(filelist[i]); getItexclude = matcherexclude.matches(); } // Get processing File String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i]; File file = new File(targetFilename); if (getIt && !getItexclude && !file.isDirectory()) { // We can add the file to the Zip Archive log.logDebug(toString(), Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i] + Messages.getString("JobZipFiles.Add_FilesToZip2.Label") + realTargetdirectory + Messages.getString("JobZipFiles.Add_FilesToZip3.Label")); // Associate a file input stream for the current file FileInputStream in = new FileInputStream(targetFilename); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(filelist[i])); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.closeEntry(); // Close the current file input stream in.close(); // Get Zipped File ZippedFiles[FileNum] = filelist[i]; FileNum = FileNum + 1; } } // Close the ZipOutPutStream out.close(); //-----Get the list of Zipped Files and Move or Delete Them if (afterzip == 1 || afterzip == 2) { // iterate through the array of Zipped files for (int i = 0; i < ZippedFiles.length; i++) { if (ZippedFiles[i] != null) { // Delete File FileObject fileObjectd = KettleVFS .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]); // Here we can move, delete files if (afterzip == 1) { // Delete File boolean deleted = fileObjectd.delete(); if (!deleted) { result.setResult(false); result.setNrErrors(1); log.logError(toString(), Messages.getString("JobZipFiles.Cant_Delete_File1.Label") + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i] + Messages .getString("JobZipFiles.Cant_Delete_File2.Label")); } // File deleted log.logDebug(toString(), Messages.getString("JobZipFiles.File_Deleted1.Label") + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Deleted2.Label")); } else if (afterzip == 2) { // Move File try { FileObject fileObjectm = KettleVFS.getFileObject( realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]); fileObjectd.moveTo(fileObjectm); } catch (IOException e) { log.logError(toString(), Messages.getString("JobZipFiles.Cant_Move_File1.Label") + ZippedFiles[i] + Messages.getString("JobZipFiles.Cant_Move_File2.Label") + e.getMessage()); result.setResult(false); result.setNrErrors(1); } // File moved log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label") + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label")); } } } } result.setResult(true); } } catch (IOException e) { log.logError(toString(), Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage()); result.setResult(false); result.setNrErrors(1); } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } } } else { result.setResult(false); result.setNrErrors(1); log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label")); } return result; }