List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
From source file:it.geosolutions.tools.compress.file.Compressor.java
/** * @param outputDir/*from www . ja v a 2 s . c o m*/ * The directory where the zipfile will be created * @param zipFileBaseName * The basename of hte zip file (i.e.: a .zip will be appended) * @param folder * The folder that will be compressed * @return The created zipfile, or null if an error occurred. * @deprecated TODO UNTESTED */ public static File deflate(final File outputDir, final String zipFileBaseName, final File folder) { // Create a buffer for reading the files byte[] buf = new byte[4096]; // Create the ZIP file final File outZipFile = new File(outputDir, zipFileBaseName + ".zip"); if (outZipFile.exists()) { if (LOGGER.isInfoEnabled()) LOGGER.info("The output file already exists: " + outZipFile); return outZipFile; } ZipOutputStream out = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(outZipFile); bos = new BufferedOutputStream(fos); out = new ZipOutputStream(bos); Collector c = new Collector(null); List<File> files = c.collect(folder); // Compress the files for (File file : files) { FileInputStream in = null; try { in = new FileInputStream(file); if (file.isDirectory()) { out.putNextEntry(new ZipEntry(Path.toRelativeFile(folder, file).getPath())); } else { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(FilenameUtils.getBaseName(file.getName()))); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } finally { try { // Complete the entry out.closeEntry(); } catch (IOException e) { } IOUtils.closeQuietly(in); } } } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } finally { // Complete the ZIP file IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(out); } return outZipFile; }
From source file:net.minecraftforge.fml.common.asm.transformers.MarkerTransformer.java
private static void processJar(File inFile, File outFile, MarkerTransformer[] transformers) throws IOException { ZipInputStream inJar = null;//from w w w .j a v a 2 s . c o m ZipOutputStream outJar = null; try { try { inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile))); } catch (FileNotFoundException e) { throw new FileNotFoundException("Could not open input file: " + e.getMessage()); } try { outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); } catch (FileNotFoundException e) { throw new FileNotFoundException("Could not open output file: " + e.getMessage()); } ZipEntry entry; while ((entry = inJar.getNextEntry()) != null) { if (entry.isDirectory()) { outJar.putNextEntry(entry); continue; } byte[] data = new byte[4096]; ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream(); int len; do { len = inJar.read(data); if (len > 0) { entryBuffer.write(data, 0, len); } } while (len != -1); byte[] entryData = entryBuffer.toByteArray(); String entryName = entry.getName(); if (entryName.endsWith(".class") && !entryName.startsWith(".")) { ClassNode cls = new ClassNode(); ClassReader rdr = new ClassReader(entryData); rdr.accept(cls, 0); String name = cls.name.replace('/', '.').replace('\\', '.'); for (MarkerTransformer trans : transformers) { entryData = trans.transform(name, name, entryData); } } ZipEntry newEntry = new ZipEntry(entryName); outJar.putNextEntry(newEntry); outJar.write(entryData); } } finally { IOUtils.closeQuietly(outJar); IOUtils.closeQuietly(inJar); } }
From source file:de.brendamour.jpasskit.signing.PKInMemorySigningUtil.java
private byte[] createZippedPassAndReturnAsByteArray(final Map<String, ByteBuffer> files) throws PKSigningException { ByteArrayOutputStream byteArrayOutputStreamForZippedPass = null; ZipOutputStream zipOutputStream = null; byteArrayOutputStreamForZippedPass = new ByteArrayOutputStream(); zipOutputStream = new ZipOutputStream(byteArrayOutputStreamForZippedPass); for (Entry<String, ByteBuffer> passResourceFile : files.entrySet()) { ZipEntry entry = new ZipEntry(getRelativePathOfZipEntry(passResourceFile.getKey(), "")); try {/*from www .j a v a 2 s . co m*/ zipOutputStream.putNextEntry(entry); IOUtils.copy(new ByteArrayInputStream(passResourceFile.getValue().array()), zipOutputStream); } catch (IOException e) { IOUtils.closeQuietly(zipOutputStream); throw new PKSigningException("Error when zipping file", e); } } IOUtils.closeQuietly(zipOutputStream); return byteArrayOutputStreamForZippedPass.toByteArray(); }
From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java
@Override public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { ZipOutputStream zout = null;//from ww w . j ava2 s . c o m OutputStream out = null; try { sCheckPermissions(resourceRequest); _log.info("Export All As Zip"); Map<String, String> savedscripts = new TreeMap<String, String>(); PortletPreferences prefs = resourceRequest.getPreferences(); for (String prefName : prefs.getMap().keySet()) { if (prefName != null && prefName.startsWith("savedscript.")) { String scriptName = prefName.substring("savedscript.".length()); String script = prefs.getValue(prefName, ""); String lang = prefs.getValue("lang." + scriptName, getDefaultLanguage()); savedscripts.put(scriptName + "." + lang, script); } } String filename = "liferay-scripts.zip"; out = resourceResponse.getPortletOutputStream(); zout = new ZipOutputStream(out); for (String key : savedscripts.keySet()) { String value = savedscripts.get(key); zout.putNextEntry(new ZipEntry(key)); zout.write(value.getBytes("utf-8")); } resourceResponse.setContentType("application/zip"); resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate"); resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "filename=" + filename); } catch (Exception e) { _log.error(e); } finally { try { if (zout != null) { zout.close(); } } catch (Exception e) { } try { if (out != null) { out.close(); } } catch (Exception e) { } } }
From source file:com.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java
/** * ??/*w ww . j av a2s. c o m*/ */ private void fuckNotDefinedRes_clearAddRes(File apkFile) throws IOException, ShakaException { if (notDefinedRes.size() <= 0) { return; } File tempFile = File.createTempFile(apkFile.getName(), null); tempFile.delete(); tempFile.deleteOnExit(); boolean renameOk = apkFile.renameTo(tempFile); if (!renameOk) { throw new ShakaException( "could not rename the file " + apkFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath()); } try (ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(apkFile))) { ZipEntry entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean toBeDeleted = false; for (String f : notDefinedRes) { if (f.equals(name)) { toBeDeleted = true; LogHelper.warning("Delete temp res : " + f); break; } } if (!toBeDeleted) { // Add ZIP entry to output stream. zout.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file IOUtils.copy(zin, zout); } entry = zin.getNextEntry(); } } tempFile.delete(); notDefinedRes.clear(); }
From source file:com.ephesoft.gxt.admin.server.TestExtractionResultDownloadServlet.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *///from w w w . j a va 2s .c o m protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOGGER.info("Downloading the result file."); final String identifier = request.getParameter("batchClassIdentifier"); final String zipFileName = EphesoftStringUtil.concatenate(identifier, UNDER_SCORE, "Result"); LOGGER.info("Zip File Name is " + zipFileName); response.setContentType(APPLICATION_ZIP); final String downloadedFile = EphesoftStringUtil.concatenate(zipFileName, ".zip", "\"\r\n"); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=\"" + downloadedFile); final BatchSchemaService batchService = this.getSingleBeanOfType(BatchSchemaService.class); StringBuilder folderPathBuilder = new StringBuilder(batchService.getBaseFolderLocation()); folderPathBuilder.append(File.separator); folderPathBuilder.append(identifier); File batchClassFolder = new File(folderPathBuilder.toString()); if (!batchClassFolder.exists()) { LOGGER.info("Batch Class Folder does not exist."); throw new IOException("Unable to download extraction result. Batch Class Folder does not exist."); } // The path for test classification folder is found....... folderPathBuilder.append(File.separator); folderPathBuilder.append(BatchClassConstants.TEST_EXTRACTION_FOLDER_NAME); folderPathBuilder.append(File.separator); folderPathBuilder.append("test-extraction-result"); System.out.println("The path is : " + folderPathBuilder.toString()); File file = new File(folderPathBuilder.toString()); if (!file.exists()) { throw new IOException("Unable to download the files. The file does not exist."); } LOGGER.info("File path is " + folderPathBuilder.toString()); ServletOutputStream out = null; ZipOutputStream zout = null; try { out = response.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectoryWithFullName(folderPathBuilder.toString(), zout); } catch (IOException ioException) { LOGGER.error("Unable to download the files." + ioException, ioException); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem occured in downloading."); } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); } }
From source file:com.ephesoft.gxt.admin.server.TestContentResultDownloadServlet.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*w ww . j a v a2 s . c om*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOGGER.info("Downloading the result file."); final String identifier = request.getParameter("batchClassIdentifier"); final String zipFileName = EphesoftStringUtil.concatenate(identifier, UNDER_SCORE, "Result"); LOGGER.info("Zip File Name is " + zipFileName); response.setContentType(APPLICATION_ZIP); final String downloadedFile = EphesoftStringUtil.concatenate(zipFileName, ".zip", "\"\r\n"); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=\"" + downloadedFile); final BatchSchemaService batchService = this.getSingleBeanOfType(BatchSchemaService.class); StringBuilder folderPathBuilder = new StringBuilder(batchService.getBaseFolderLocation()); folderPathBuilder.append(File.separator); folderPathBuilder.append(identifier); File batchClassFolder = new File(folderPathBuilder.toString()); if (!batchClassFolder.exists()) { LOGGER.info("Batch Class Folder does not exist."); throw new IOException("Unable to perform Content Classification. Batch Class Folder does not exist."); } // The path for test classification folder is found....... folderPathBuilder.append(File.separator); folderPathBuilder.append(BatchClassConstants.TEST_CLASSIFICATION_FOLDER_NAME); folderPathBuilder.append(File.separator); folderPathBuilder.append("test-classification-result"); System.out.println("The path is : " + folderPathBuilder.toString()); File file = new File(folderPathBuilder.toString()); if (!file.exists()) { throw new IOException("Unable to download the files. The file does not exist."); } LOGGER.info("File path is " + folderPathBuilder.toString()); ServletOutputStream out = null; ZipOutputStream zout = null; try { out = response.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectoryWithFullName(folderPathBuilder.toString(), zout); } catch (IOException ioException) { LOGGER.error("Unable to download the files." + ioException, ioException); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem occured in downloading."); } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); } }
From source file:de.micromata.genome.gdbfs.FileSystemUtils.java
/** * Copy files into a zip file.//from w ww . j av a 2 s. c o m * * @param source the source * @param matcher the matcher * @param zipOut will closed this stream after written. */ public static void copyToZip(FsObject source, Matcher<String> matcher, OutputStream zipOut) { ZipOutputStream zOut = new ZipOutputStream(zipOut); if (source.isDirectory() == true) { FsDirectoryObject dir = (FsDirectoryObject) source; List<FsObject> files = dir.getFileSystem().listFiles(source.getName(), matcher, null, true); for (FsObject f : files) { copyToZip(f, zOut); } } // TODO look in reporting, if zip files will be closed. IOUtils.closeQuietly(zOut); IOUtils.closeQuietly(zipOut); }
From source file:com.thruzero.common.core.fs.walker.visitor.ZipCompressingVisitor.java
/** * create the zip archive file and prepare it to accept files and directory paths. * * @throws IllegalArgumentException if target file already exists, but can't be deleted, or when the target archive * file can't be created./*from www.j av a 2s . co m*/ */ @Override public void open(final File rootDirectory) throws IOException { super.open(rootDirectory); // cache rootDirectory, for determining the relative path during traversals this.rootDirectory = rootDirectory; try { if (targetArchive.exists()) { boolean deleteSuccess = targetArchive.delete(); if (!deleteSuccess) { IllegalArgumentException iae = new IllegalArgumentException( "ERROR: Could not delete target file: " + targetArchive); logHelper.logError(iae); throw iae; } } targetArchive.createNewFile(); zipOut = new ZipOutputStream(new FileOutputStream(targetArchive)); } catch (IOException e) { IllegalArgumentException iae = new IllegalArgumentException( "ERROR: Could not create target file: " + targetArchive + ": " + e); logHelper.logError(iae); throw iae; } }
From source file:eu.esdihumboldt.hale.server.templates.war.components.TemplateUploadForm.java
/** * Constructor/* w ww .j a va 2 s . c om*/ * * @param id the component ID * @param templateId the identifier of the template to update, or * <code>null</code> to create a new template */ public TemplateUploadForm(String id, String templateId) { super(id); this.templateId = templateId; Form<Void> form = new Form<Void>("upload") { private static final long serialVersionUID = 716487990605324922L; @Override protected void onSubmit() { List<FileUpload> uploads = file.getFileUploads(); if (uploads != null && !uploads.isEmpty()) { final boolean newTemplate = TemplateUploadForm.this.templateId == null; final String templateId; final File dir; File oldContent = null; if (newTemplate) { // attempt to reserve template ID Pair<String, File> template; try { template = templates.reserveResource(determinePreferredId(uploads)); } catch (ScavengerException e) { error(e.getMessage()); return; } templateId = template.getFirst(); dir = template.getSecond(); } else { templateId = TemplateUploadForm.this.templateId; dir = new File(templates.getHuntingGrounds(), templateId); // archive old content try { Path tmpFile = Files.createTempFile("hale-template", ".zip"); try (OutputStream out = Files.newOutputStream(tmpFile); ZipOutputStream zos = new ZipOutputStream(out)) { IOUtils.zipDirectory(dir, zos); } oldContent = tmpFile.toFile(); } catch (IOException e) { log.error("Error saving old template content to archive", e); } // delete old content try { FileUtils.cleanDirectory(dir); } catch (IOException e) { log.error("Error deleting old template content", e); } } try { for (FileUpload upload : uploads) { if (isZipFile(upload)) { // extract uploaded file IOUtils.extract(dir, new BufferedInputStream(upload.getInputStream())); } else { // copy uploaded file File target = new File(dir, upload.getClientFileName()); ByteStreams.copy(upload.getInputStream(), new FileOutputStream(target)); } } // trigger scan after upload if (newTemplate) { templates.triggerScan(); } else { templates.forceUpdate(templateId); } TemplateProject ref = templates.getReference(templateId); if (ref != null && ref.isValid()) { info("Successfully uploaded project"); boolean infoUpdate = (updateInfo != null) ? (updateInfo.getModelObject()) : (false); onUploadSuccess(this, templateId, ref.getProjectInfo(), infoUpdate); } else { if (newTemplate) { templates.releaseResourceId(templateId); } else { restoreContent(dir, oldContent); } error((ref != null) ? (ref.getNotValidMessage()) : ("Uploaded files could not be loaded as HALE project")); } } catch (Exception e) { if (newTemplate) { templates.releaseResourceId(templateId); } else { restoreContent(dir, oldContent); } log.error("Error while uploading file", e); error("Error saving the file"); } } else { warn("Please provide a file for upload"); } } @Override protected void onFileUploadException(FileUploadException e, Map<String, Object> model) { if (e instanceof SizeLimitExceededException) { final String msg = "Only files up to " + bytesToString(getMaxSize(), Locale.US) + " can be uploaded."; error(msg); } else { final String msg = "Error uploading the file: " + e.getLocalizedMessage(); error(msg); log.warn(msg, e); } } }; add(form); // multipart always needed for uploads form.setMultiPart(true); // max size for upload if (UserUtil.isAdmin()) { // admin max upload size form.setMaxSize(Bytes.megabytes(100)); } else { // normal user max upload size // TODO differentiate between logged in and anonymous user? form.setMaxSize(Bytes.megabytes(15)); } // Add file input field for multiple files form.add(file = new FileUploadField("file")); file.add(new IValidator<List<FileUpload>>() { private static final long serialVersionUID = -5668788086384105101L; @Override public void validate(IValidatable<List<FileUpload>> validatable) { if (validatable.getValue().isEmpty()) { validatable.error(new ValidationError("No source files specified.")); } } }); // add anonym/recaptcha panel boolean loggedIn = UserUtil.getLogin() != null; WebMarkupContainer anonym = new WebMarkupContainer("anonym"); if (loggedIn) { anonym.add(new WebMarkupContainer("recaptcha")); } else { anonym.add(new RecaptchaPanel("recaptcha")); } anonym.add( new BookmarkablePageLink<>("login", ((BaseWebApplication) getApplication()).getLoginPageClass())); anonym.setVisible(!loggedIn); form.add(anonym); // update panel WebMarkupContainer update = new WebMarkupContainer("update"); update.setVisible(templateId != null); updateInfo = new CheckBox("updateInfo", Model.of(true)); update.add(updateInfo); form.add(update); // feedback panel form.add(new BootstrapFeedbackPanel("feedback")); }