List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java
/** * Given a DITA map bounded object set, zips it up into a DXP Zip package. * @param mapBos// w w w . j a va2 s .co m * @param outputZipFile * @throws Exception */ public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options) throws Exception { /* * Some potential complexities: * * - DXP package spec requires either a map manifest or that * there be exactly one map at the root of the zip package. This * means that the file structure of the BOS needs to be checked to * see if the files already conform to this structure and, if not, * they need to be reorganized and have pointers rewritten if a * map manifest has not been requested. * * - If the file structure of the original data includes files not * below the root map, the file organization must be reworked whether * or not a map manifest has been requested. * * - Need to generate DXP map manifest if a manifest is requested. * * - If user has requested that the original file structure be * remembered, a manifest must be generated. */ log.debug("Determining zip file organization..."); BosVisitor visitor = new DxpFileOrganizingBosVisitor(); visitor.visit(mapBos); if (!options.isQuiet()) log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"..."); OutputStream outStream = new FileOutputStream(outputZipFile); ZipOutputStream zipOutStream = new ZipOutputStream(outStream); ZipEntry entry = null; // At this point, URIs of all members should reflect their // storage location within the resulting DXP package. There // must also be a root map, either the original map // we started with or a DXP manifest map. URI rootMapUri = mapBos.getRoot().getEffectiveUri(); URI baseUri = null; try { baseUri = AddressingUtil.getParent(rootMapUri); } catch (URISyntaxException e) { throw new BosException("URI syntax exception getting parent URI: " + e.getMessage()); } Set<String> dirs = new HashSet<String>(); if (!options.isQuiet()) log.info("Constructing DXP package..."); for (BosMember member : mapBos.getMembers()) { if (!options.isQuiet()) log.info("Adding member " + member + " to zip..."); URI relativeUri = baseUri.relativize(member.getEffectiveUri()); File temp = new File(relativeUri.getPath()); String parentPath = temp.getParent(); if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) { parentPath += "/"; } log.debug("parentPath=\"" + parentPath + "\""); if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) { entry = new ZipEntry(parentPath); zipOutStream.putNextEntry(entry); zipOutStream.closeEntry(); dirs.add(parentPath); } entry = new ZipEntry(relativeUri.getPath()); zipOutStream.putNextEntry(entry); IOUtils.copy(member.getInputStream(), zipOutStream); zipOutStream.closeEntry(); } zipOutStream.close(); if (!options.isQuiet()) log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created."); }
From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java
private void zipWebInfJar(String zipName, File[] files) throws Exception { byte[] buffer = new byte[4096]; // Create a buffer for copying int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipName)); try {/*www. j ava2 s.com*/ for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isDirectory()) { continue; } String fileName = "WEB-INF/" + f.getName(); FileInputStream in = new FileInputStream(f); // Stream to read file try { ZipEntry entry = new ZipEntry(fileName); // Make a ZipEntry out.putNextEntry(entry); // Store entry while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } finally { in.close(); } } } finally { out.close(); } }
From source file:nl.nn.adapterframework.pipes.CompressPipe.java
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException { try {//from w ww . j av a2s.c om Object result; InputStream in; OutputStream out; boolean zipMultipleFiles = false; if (messageIsContent) { if (input instanceof byte[]) { in = new ByteArrayInputStream((byte[]) input); } else { in = new ByteArrayInputStream(input.toString().getBytes()); } } else { if (compress && StringUtils.contains((String) input, ";")) { zipMultipleFiles = true; in = null; } else { in = new FileInputStream((String) input); } } if (resultIsContent) { out = new ByteArrayOutputStream(); result = out; } else { String outFilename = null; if (messageIsContent) { outFilename = FileUtils.getFilename(getParameterList(), session, (File) null, filenamePattern); } else { outFilename = FileUtils.getFilename(getParameterList(), session, new File((String) input), filenamePattern); } File outFile = new File(outputDirectory, outFilename); result = outFile.getAbsolutePath(); out = new FileOutputStream(outFile); } if (zipMultipleFiles) { ZipOutputStream zipper = new ZipOutputStream(out); StringTokenizer st = new StringTokenizer((String) input, ";"); while (st.hasMoreElements()) { String fn = st.nextToken(); String zipEntryName = getZipEntryName(fn, session); zipper.putNextEntry(new ZipEntry(zipEntryName)); in = new FileInputStream(fn); try { int readLength = 0; byte[] block = new byte[4096]; while ((readLength = in.read(block)) > 0) { zipper.write(block, 0, readLength); } } finally { in.close(); zipper.closeEntry(); } } zipper.close(); out = zipper; } else { if (compress) { if ("gz".equals(fileFormat) || fileFormat == null && resultIsContent) { out = new GZIPOutputStream(out); } else { ZipOutputStream zipper = new ZipOutputStream(out); String zipEntryName = getZipEntryName(input, session); zipper.putNextEntry(new ZipEntry(zipEntryName)); out = zipper; } } else { if ("gz".equals(fileFormat) || fileFormat == null && messageIsContent) { in = new GZIPInputStream(in); } else { ZipInputStream zipper = new ZipInputStream(in); String zipEntryName = getZipEntryName(input, session); if (zipEntryName.equals("")) { // Use first entry found zipper.getNextEntry(); } else { // Position the stream at the specified entry ZipEntry zipEntry = zipper.getNextEntry(); while (zipEntry != null && !zipEntry.getName().equals(zipEntryName)) { zipEntry = zipper.getNextEntry(); } } in = zipper; } } try { int readLength = 0; byte[] block = new byte[4096]; while ((readLength = in.read(block)) > 0) { out.write(block, 0, readLength); } } finally { out.close(); in.close(); } } return new PipeRunResult(getForward(), getResultMsg(result)); } catch (Exception e) { PipeForward exceptionForward = findForward(EXCEPTIONFORWARD); if (exceptionForward != null) { log.warn(getLogPrefix(session) + "exception occured, forwarded to [" + exceptionForward.getPath() + "]", e); String originalMessage; if (input instanceof String) { originalMessage = (String) input; } else { originalMessage = "Object of type " + input.getClass().getName(); } String resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), e, this, originalMessage, session.getMessageId(), 0); return new PipeRunResult(exceptionForward, resultmsg); } throw new PipeRunException(this, "Unexpected exception during compression", e); } }
From source file:com.koushikdutta.superuser.MainActivity.java
void doRecoveryInstall() { final ProgressDialog dlg = new ProgressDialog(this); dlg.setTitle(R.string.installing);//from w ww. jav a2s. c o m dlg.setMessage(getString(R.string.installing_superuser)); dlg.setIndeterminate(true); dlg.show(); new Thread() { void doEntry(ZipOutputStream zout, String entryName, String dest) throws IOException { ZipFile zf = new ZipFile(getPackageCodePath()); ZipEntry ze = zf.getEntry(entryName); zout.putNextEntry(new ZipEntry(dest)); InputStream in; StreamUtility.copyStream(in = zf.getInputStream(ze), zout); zout.closeEntry(); in.close(); zf.close(); } public void run() { try { File zip = getFileStreamPath("superuser.zip"); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zip)); doEntry(zout, "assets/update-binary", "META-INF/com/google/android/update-binary"); doEntry(zout, "assets/install-recovery.sh", "install-recovery.sh"); zout.close(); ZipFile zf = new ZipFile(getPackageCodePath()); ZipEntry ze = zf.getEntry("assets/" + getArch() + "/reboot"); InputStream in; FileOutputStream reboot; StreamUtility.copyStream(in = zf.getInputStream(ze), reboot = openFileOutput("reboot", MODE_PRIVATE)); reboot.close(); in.close(); final File su = extractSu(); String command = String.format("cat %s > /cache/superuser.zip\n", zip.getAbsolutePath()) + String.format("cat %s > /cache/su\n", su.getAbsolutePath()) + String.format("cat %s > /cache/Superuser.apk\n", getPackageCodePath()) + "mkdir /cache/recovery\n" + "echo '--update_package=CACHE:superuser.zip' > /cache/recovery/command\n" + "chmod 644 /cache/superuser.zip\n" + "chmod 644 /cache/recovery/command\n" + "sync\n" + String.format("chmod 755 %s\n", getFileStreamPath("reboot").getAbsolutePath()) + "reboot recovery\n"; Process p = Runtime.getRuntime().exec("su"); p.getOutputStream().write(command.getBytes()); p.getOutputStream().close(); File rebootScript = getFileStreamPath("reboot.sh"); StreamUtility.writeFile(rebootScript, "reboot recovery ; " + getFileStreamPath("reboot").getAbsolutePath() + " recovery ;"); p.waitFor(); Runtime.getRuntime().exec(new String[] { "su", "-c", ". " + rebootScript.getAbsolutePath() }); if (p.waitFor() != 0) throw new Exception("non zero result"); } catch (Exception ex) { ex.printStackTrace(); dlg.dismiss(); runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setPositiveButton(android.R.string.ok, null); builder.setTitle(R.string.install); builder.setMessage(R.string.install_error); builder.create().show(); } }); } } }.start(); }
From source file:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java
/** * Call the taskmodel-core-view application via http for every user, that has processed the given task. Streams a zip * archive with all rendered pdf files to <code>os</code>. * * @param tasklets/*w w w . ja v a 2 s. c o m*/ * all tasklets to render * @param os * the outputstream the zip shall be written to * @param pdfExporter * @throws IOException */ private void renderAllPdfs(final List<Tasklet> tasklets, final OutputStream os, final PDFExporter pdfExporter) throws IOException { // create zip with all generated pdfs final ZipOutputStream zos = new ZipOutputStream(os); // fetch pdf for every user/tasklet // render a pdf for every user that has a tasklet for the current task for (final Tasklet tasklet : tasklets) { final String userId = tasklet.getUserId(); if (!tasklet.hasOrPassedStatus(Status.INPROGRESS)) { log.info(String.format("Skipping PDF for user %s, last try has no contents.", userId)); continue; } log.debug("exporting pdf for " + userId); // add new zipentry (for next pdf) if (!addGeneratedPDFS(tasklet, userId, zos)) { final String filename = userId + ".pdf"; final ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); // fetch the generated pdf from taskmodel-core-view pdfExporter.renderPdf(tasklet, filename, zos); // close this zipentry zos.closeEntry(); } } zos.close(); }
From source file:abfab3d.shapejs.Project.java
public void save(String file) throws IOException { EvaluatedScript escript = m_script.getEvaluatedScript(); Map<String, Parameter> scriptParams = escript.getParamMap(); Gson gson = JSONParsing.getJSONParser(); String code = escript.getCode(); Path workingDirName = Files.createTempDirectory("saveScript"); String workingDirPath = workingDirName.toAbsolutePath().toString(); Map<String, Object> params = new HashMap<String, Object>(); // Write the script to file File scriptFile = new File(workingDirPath + "/main.js"); FileUtils.writeStringToFile(scriptFile, code, "UTF-8"); // Loop through params and create key/pair entries for (Map.Entry<String, Parameter> entry : scriptParams.entrySet()) { String name = entry.getKey(); Parameter pval = entry.getValue(); if (pval.isDefaultValue()) continue; ParameterType type = pval.getType(); switch (type) { case URI: URIParameter urip = (URIParameter) pval; String u = (String) urip.getValue(); // System.out.println("*** uri: " + u); File f = new File(u); String fileName = null; // TODO: This is hacky. If the parameter value is a directory, then assume it was // originally a zip file, and its contents were extracted in the directory. // Search for the zip file in the directory and copy that to the working dir. if (f.isDirectory()) { File[] files = f.listFiles(); for (int i = 0; i < files.length; i++) { String fname = files[i].getName(); if (fname.endsWith(".zip")) { fileName = fname; f = files[i];//from ww w . j av a 2 s .com } } } else { fileName = f.getName(); } params.put(name, fileName); // Copy the file to working directory FileUtils.copyFile(f, new File(workingDirPath + "/" + fileName), true); break; case LOCATION: LocationParameter lp = (LocationParameter) pval; Vector3d p = lp.getPoint(); Vector3d n = lp.getNormal(); double[] point = { p.x, p.y, p.z }; double[] normal = { n.x, n.y, n.z }; // System.out.println("*** lp: " + java.util.Arrays.toString(point) + ", " + java.util.Arrays.toString(normal)); Map<String, double[]> loc = new HashMap<String, double[]>(); loc.put("point", point); loc.put("normal", normal); params.put(name, loc); break; case AXIS_ANGLE_4D: AxisAngle4dParameter aap = (AxisAngle4dParameter) pval; AxisAngle4d a = (AxisAngle4d) aap.getValue(); params.put(name, a); break; case DOUBLE: DoubleParameter dp = (DoubleParameter) pval; Double d = (Double) dp.getValue(); // System.out.println("*** double: " + d); params.put(name, d); break; case INTEGER: IntParameter ip = (IntParameter) pval; Integer i = ip.getValue(); // System.out.println("*** int: " + pval); params.put(name, i); break; case STRING: StringParameter sp = (StringParameter) pval; String s = sp.getValue(); // System.out.println("*** string: " + s); params.put(name, s); break; case COLOR: ColorParameter cp = (ColorParameter) pval; Color c = cp.getValue(); // System.out.println("*** string: " + s); params.put(name, c.toHEX()); break; case ENUM: EnumParameter ep = (EnumParameter) pval; String e = ep.getValue(); // System.out.println("*** string: " + s); params.put(name, e); break; default: params.put(name, pval); } } if (params.size() > 0) { String paramsJson = gson.toJson(params); File paramFile = new File(workingDirPath + "/" + "params.json"); FileUtils.writeStringToFile(paramFile, paramsJson, "UTF-8"); } File[] files = (new File(workingDirPath)).listFiles(); FileOutputStream fos = new FileOutputStream(file); ZipOutputStream zos = new ZipOutputStream(fos); System.out.println("*** Num files to zip: " + files.length); try { byte[] buffer = new byte[1024]; for (int i = 0; i < files.length; i++) { // if (files[i].getName().endsWith(".zip")) continue; System.out.println("*** Adding file: " + files[i].getName()); FileInputStream fis = new FileInputStream(files[i]); ZipEntry ze = new ZipEntry(files[i].getName()); zos.putNextEntry(ze); int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } fis.close(); } } finally { zos.closeEntry(); zos.close(); } }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * /*from ww w. j a v a 2s .co m*/ * @param to - to email address * @param docType - String value for the attached document type * @param subject - Subject for the email * @param instructions - email body * @param content - content to be sent as attachment * @return MimeMessage instance */ public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content, String metadataXMl, String title, String indexBodyToken, String readmeToken) { final MimeMessage msg = mailSender.createMimeMessage(); UUID uniqueID = UUID.randomUUID(); tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID); try { msg.setFrom(new InternetAddress(getFrom())); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // The readable part final MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(instructions); mbp1.setHeader("Content-Type", "text/plain"); // The notification final MimeBodyPart mbp2 = new MimeBodyPart(); final String contentType = "application/xml; charset=UTF-8"; String extension; // HL7 messages should be a txt file, otherwise xml if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) { extension = TXT_EXT; } else { extension = XML_EXT; } final String fileName = docType + UUID.randomUUID() + extension; // final DataSource ds = new AttachmentDS(fileName, content, contentType); // mbp2.setDataHandler(new DataHandler(ds)); /******** START NHIN COMPLIANCE CHANGES *****/ boolean isTempZipFolderCreated = tempZipFolder.mkdirs(); if (!isTempZipFolderCreated) { LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); } String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM")); String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT")); indexFileString = StringUtils.replace(indexFileString, "@document_title@", title); indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString); readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString); // move template files & replace tokens // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false); // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false); // create sub-directories String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01"; File nhinSubDirectory = new File(nhinSubDirectoryPath); boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs(); if (!isNhinSubDirectoryCreated) { LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); } FileOutputStream metadataStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/METADATA.XML")); metadataStream.write(metadataXMl.getBytes()); metadataStream.flush(); metadataStream.close(); FileOutputStream documentStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/DOCUMENT" + extension)); documentStream.write(content.getBytes()); documentStream.flush(); documentStream.close(); String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP"; byte[] buffer = new byte[1024]; // FileOutputStream fos = new FileOutputStream(zipFile); // ZipOutputStream zos = new ZipOutputStream(fos); List<String> fileList = generateFileList(tempZipFolder); ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size()); ZipOutputStream zos = new ZipOutputStream(bout); // LOG.info("File List size: "+fileList.size()); for (String file : fileList) { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); // remember close it zos.close(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); mbp2.setDataHandler(new DataHandler(source)); mbp2.setFileName(docType + ".ZIP"); /******** END NHIN COMPLIANCE CHANGES *****/ // mbp2.setFileName(fileName); // mbp2.setHeader("Content-Type", contentType); final Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); msg.setSentDate(new Date()); // FileUtils.deleteDirectory(tempZipFolder); } catch (AddressException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (MessagingException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (IOException e) { LOG.error(e.getMessage()); throw new ApplicationRuntimeException(e.getMessage()); } finally { //reset filelist contents fileList = new ArrayList<String>(); } return msg; }
From source file:com.funambol.framework.tools.FileArchiver.java
private void internalCompress(FileOutputStream outputStream) throws FileArchiverException { ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); if (sourceFile.exists()) { if (sourceFile.isFile()) { addFile(zipOutputStream, EMPTY_PATH, sourceFile); } else if (sourceFile.isDirectory()) { if (includeRoot) { addDirectory(zipOutputStream, EMPTY_PATH, sourceFile); } else { addDirectoryContent(zipOutputStream, EMPTY_PATH, sourceFile); }/*from ww w . j a va 2s. com*/ } else { throw new FileArchiverException("Unable to handle input file type."); } } else { throw new FileArchiverException("Unable to zip a not existing file"); } try { zipOutputStream.flush(); zipOutputStream.close(); } catch (IOException e) { throw new FileArchiverException( "Unable to close the zip destination file '" + destinationFilename + "'", e); } }
From source file:link.kjr.file_manager.MainActivity.java
public void createZipFile(String name, final MainActivity activity) { activity.handler.post(new Runnable() { @Override/*from ww w . j a v a 2 s . c o m*/ public void run() { activity.postMessage(activity.getBaseContext().getString(R.string.creating_zip_file)); } }); try { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(currentPath + "/" + name + ".zip")); for (String file : selectedFiles) { ZipEntry ze = new ZipEntry(file); FileInputStream fis = new FileInputStream(file); zos.putNextEntry(ze); byte[] data = new byte[1024]; int length; while ((length = fis.read(data)) >= 0) { zos.write(data, 0, length); } zos.closeEntry(); fis.close(); } zos.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } activity.handler.post(new Runnable() { @Override public void run() { activity.postMessage(activity.getBaseContext().getString(R.string.done_creating_zip_file)); activity.deselectFiles(); activity.refresh(); } }); }
From source file:eu.delving.services.controller.DataSetController.java
private void writeSipZip(String dataSetSpec, OutputStream outputStream, String accessKey) throws IOException, MappingNotFoundException, AccessKeyException, XMLStreamException, MetadataException, MappingException { MetaRepo.DataSet dataSet = metaRepo.getDataSet(dataSetSpec); if (dataSet == null) { throw new IOException("Data Set not found"); // IOException? }/*from w ww . j a v a2s . co m*/ ZipOutputStream zos = new ZipOutputStream(outputStream); zos.putNextEntry(new ZipEntry(FileStore.FACTS_FILE_NAME)); Facts facts = Facts.fromBytes(dataSet.getDetails().getFacts()); facts.setDownloadedSource(true); zos.write(Facts.toBytes(facts)); zos.closeEntry(); zos.putNextEntry(new ZipEntry(FileStore.SOURCE_FILE_NAME)); String sourceHash = writeSourceStream(dataSet, zos, accessKey); zos.closeEntry(); for (MetaRepo.Mapping mapping : dataSet.mappings().values()) { RecordMapping recordMapping = mapping.getRecordMapping(); zos.putNextEntry( new ZipEntry(String.format(FileStore.MAPPING_FILE_PATTERN, recordMapping.getPrefix()))); RecordMapping.write(recordMapping, zos); zos.closeEntry(); } zos.finish(); zos.close(); dataSet.setSourceHash(sourceHash, true); dataSet.save(); }