List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
From source file:dpfmanager.shell.modules.server.post.HttpPostHandler.java
public String zipFolder(String folder) { // Zip path/*from ww w . j ava 2 s . c o m*/ String outputFile = folder + ".zip"; if (folder.endsWith("/")) { outputFile = folder.substring(0, folder.length() - 1) + ".zip"; } // Check if exists if (new File(outputFile).exists()) { return outputFile; } // Make the zip try { ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile)); compressDirectoryToZipfile(folder, folder, zipFile); IOUtils.closeQuietly(zipFile); return outputFile; } catch (Exception e) { return null; } }
From source file:com.ibm.amc.FileManager.java
public static File compress(File pathToCompress) { try {//from w ww.java2 s . c om File zipFile = new File(pathToCompress.getCanonicalPath() + ZIP_EXTENSION); FileOutputStream fileOutputStream = new FileOutputStream(zipFile); CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); ZipOutputStream out = new ZipOutputStream(cos); String basedir = ""; compress(pathToCompress, out, basedir); out.close(); return zipFile; } catch (Exception e) { throw new AmcRuntimeException(e); } }
From source file:it.greenvulcano.util.zip.ZipHelper.java
/** * Performs the <code>ZIP</code> compression of a file/directory, whose name * and parent directory are passed as arguments, on the local filesystem. * The result is written into a target file with the <code>zip</code> * extension.<br>//from w w w . j a v a 2 s .c o m * The source filename may contain a regualr expression: in this * case, all the filenames matching the pattern will be compressed and put * in the same target <code>zip</code> file.<br> * * * @param srcDirectory * the source parent directory of the file/s to be zipped. Must * be an absolute pathname. * @param fileNamePattern * the name of the file to be zipped. May contain a regular expression, * possibly matching multiple files/directories. * If matching a directory, the directory is zipped with all its content as well. * @param targetDirectory * the target parent directory of the created <code>zip</code> * file. Must be an absolute pathname. * @param zipFilename * the name of the zip file to be created. Cannot be * <code>null</code>, and must have the <code>.zip</code> * extension. If a target file already exists with the same name * in the same directory, it will be overwritten. * @throws IOException * If any error occurs during file compression. * @throws IllegalArgumentException * if the arguments are invalid. */ public void zipFile(String srcDirectory, String fileNamePattern, String targetDirectory, String zipFilename) throws IOException { File srcDir = new File(srcDirectory); if (!srcDir.isAbsolute()) { throw new IllegalArgumentException( "The pathname of the source parent directory is NOT absolute: " + srcDirectory); } if (!srcDir.exists()) { throw new IllegalArgumentException( "Source parent directory " + srcDirectory + " NOT found on local filesystem."); } if (!srcDir.isDirectory()) { throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory."); } File targetDir = new File(targetDirectory); if (!targetDir.isAbsolute()) { throw new IllegalArgumentException( "The pathname of the target parent directory is NOT absolute: " + targetDirectory); } if (!targetDir.exists()) { throw new IllegalArgumentException( "Target parent directory " + targetDirectory + " NOT found on local filesystem."); } if (!targetDir.isDirectory()) { throw new IllegalArgumentException( "Target parent directory " + targetDirectory + " is NOT a directory."); } if ((zipFilename == null) || (zipFilename.length() == 0)) { throw new IllegalArgumentException("Target zip file name is missing."); } ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(new File(targetDir, zipFilename))); zos.setLevel(compressionLevel); URI base = srcDir.toURI(); File[] files = srcDir.listFiles(new RegExFilenameFilter(fileNamePattern)); for (File file : files) { internalZipFile(file, zos, base); } } finally { try { if (zos != null) { zos.close(); } } catch (Exception exc) { // Do nothing } } }
From source file:io.druid.java.util.common.CompressionUtilsTest.java
@Test public void testDecompressZip() throws IOException { final File tmpDir = temporaryFolder.newFolder("testDecompressZip"); final File zipFile = new File(tmpDir, testFile.getName() + ".zip"); Assert.assertFalse(zipFile.exists()); try (final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) { out.putNextEntry(new ZipEntry("cool.file")); ByteStreams.copy(new FileInputStream(testFile), out); out.closeEntry();/*w w w . j a v a 2 s .c o m*/ } try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(zipFile), zipFile.getName())) { assertGoodDataStream(inputStream); } }
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 w ww. java 2s . c om } 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:com.hazelcast.stabilizer.Utils.java
public static byte[] zip(List<File> roots) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Deque<File> queue = new LinkedList<File>(); ZipOutputStream zout = new ZipOutputStream(out); Set<String> names = new HashSet<String>(); try {/* w w w. j a v a 2s . c om*/ for (File root : roots) { URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI(); queue.push(root); while (!queue.isEmpty()) { File file = queue.pop(); if (file.getName().equals(".DS_Store")) { continue; } // log.finest("Zipping: " + file.getAbsolutePath()); if (file.isDirectory()) { String name = base.relativize(file.toURI()).getPath(); name = name.endsWith("/") ? name : name + "/"; if (names.add(name)) { zout.putNextEntry(new ZipEntry(name)); } for (File kid : file.listFiles()) { queue.push(kid); } } else { String name = base.relativize(file.toURI()).getPath(); zout.putNextEntry(new ZipEntry(name)); copy(file, zout); zout.closeEntry(); } } } } finally { zout.close(); } return out.toByteArray(); }
From source file:com.founder.fix.fixflow.FlowManager.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CurrentThread.init();//from w ww . jav a 2 s . c o m String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID)); if (StringUtil.isEmpty(userId)) { String context = request.getContextPath(); response.sendRedirect(context + "/"); return; } ServletOutputStream out = null; String action = StringUtil.getString(request.getParameter("action")); if (StringUtil.isEmpty(action)) { action = StringUtil.getString(request.getAttribute("action")); } RequestDispatcher rd = null; try { Map<String, Object> filter = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload Uploader = new ServletFileUpload(new DiskFileItemFactory()); // Uploader.setSizeMax("); // Uploader.setHeaderEncoding("utf-8"); List<FileItem> fileItems = Uploader.parseRequest(request); for (FileItem item : fileItems) { filter.put(item.getFieldName(), item); if (item.getFieldName().equals("action")) action = item.getString(); if (item.getFieldName().equals("deploymentId")) { filter.put("deploymentId", item.getString()); } } } else { Enumeration enu = request.getParameterNames(); while (enu.hasMoreElements()) { Object tmp = enu.nextElement(); Object obj = request.getParameter(StringUtil.getString(tmp)); // if (request.getAttribute("ISGET") != null) obj = new String(obj.toString().getBytes("ISO8859-1"), "utf-8"); filter.put(StringUtil.getString(tmp), obj); } } Enumeration attenums = request.getAttributeNames(); while (attenums.hasMoreElements()) { String paramName = (String) attenums.nextElement(); Object paramValue = request.getAttribute(paramName); // ?map filter.put(paramName, paramValue); } filter.put("userId", userId); request.setAttribute("nowAction", action); if ("processDefinitionList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/processDefinitionList.jsp"); Map<String, Object> result = getProcessDefinitionService().getProcessDefitionList(filter); filter.putAll(result); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("processManageList")) { rd = request.getRequestDispatcher("/fixflow/manager/processInstanceList.jsp"); Map<String, Object> result = getFlowManager().getProcessInstances(filter); filter.putAll(result); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("suspendProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().suspendProcessInstance(filter); } else if (action.equals("continueProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().continueProcessInstance(filter); } else if (action.equals("terminatProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().terminatProcessInstance(filter); } else if (action.equals("deleteProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().deleteProcessInstance(filter); } else if (action.equals("toProcessVariable")) { rd = request.getRequestDispatcher("/fixflow/manager/processVariableList.jsp"); Map<String, Object> result = getFlowManager().getProcessVariables(filter); filter.putAll(result); request.setAttribute("result", filter); } else if (action.equals("saveProcessVariables")) { String tmp = (String) filter.get("insertAndUpdate"); if (StringUtil.isNotEmpty(tmp)) { Map<String, Object> tMap = JSONUtil.parseJSON2Map(tmp); filter.put("insertAndUpdate", tMap); } getFlowManager().saveProcessVariables(filter); rd = request.getRequestDispatcher("/FlowManager?action=toProcessVariable"); } else if (action.equals("processTokenList")) { Map<String, Object> result = getFlowManager().getProcessTokens(filter); filter.putAll(result); request.setAttribute("result", filter); rd = request.getRequestDispatcher("/fixflow/manager/processTokenList.jsp"); } else if (action.equals("taskInstanceList")) { rd = request.getRequestDispatcher("/fixflow/manager/taskInstanceList.jsp"); filter.put("path", request.getSession().getServletContext().getRealPath("/")); Map<String, Object> pageResult = getTaskManager().getTaskList(filter); filter.putAll(pageResult); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("doTaskSuspend")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().suspendTask(filter); } else if (action.equals("doTaskResume")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().resumeTask(filter); } else if (action.equals("doTaskTransfer")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().transferTask(filter); } else if (action.equals("doTaskRollBackNode")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().rollBackNode(filter); } else if (action.equals("doTaskRollBackTask")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().rollBackStep(filter); } else if (action.equals("flowLibrary")) { rd = request.getRequestDispatcher("/fixflow-explorer/flowLibrary.jsp"); } //???deploymentId if ("deploy".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList"); response.setContentType("text/html;charset=utf-8"); getProcessDefinitionService().deployByZip(filter); } else if ("deleteDeploy".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList"); getProcessDefinitionService().deleteDeploy(filter); } else if ("download".equals(action)) { String processDefinitionId = StringUtil.getString(filter.get("processDefinitionId")); response.reset(); request.setCharacterEncoding("gbk"); response.setContentType("applcation/octet-stream"); response.setHeader("Content-disposition", "attachment; filename=" + processDefinitionId + ".zip"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0,private, max-age=0"); response.setHeader("Content-Type", "application/octet-stream"); response.setHeader("Content-Type", "application/force-download"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); ZipOutputStream outZip = new ZipOutputStream(response.getOutputStream()); List<Map<String, Object>> fileList = getProcessDefinitionService().getResources(filter); for (Map<String, Object> file : fileList) { ZipEntry entry = new ZipEntry(file.get("FILENAME").toString()); entry.setSize(((byte[]) file.get("BYTES")).length); outZip.putNextEntry(entry); outZip.write((byte[]) file.get("BYTES")); outZip.closeEntry(); } outZip.close(); outZip.flush(); outZip.close(); } else if ("getUserList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/userList.jsp"); request.setAttribute("nowAction", "UserGroup"); Map<String, Object> result = getUserGroupService().getAllUsers(filter); filter.putAll(result); request.setAttribute("result", filter); List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter); request.setAttribute("groupList", groupList); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if ("getGroupList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/groupList.jsp"); request.setAttribute("nowAction", "UserGroup"); Map<String, Object> result = getUserGroupService().getAllGroup(filter); filter.putAll(result); request.setAttribute("result", filter); List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter); request.setAttribute("groupList", groupList); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if ("getUserInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/userInfo.jsp"); Map<String, Object> pageResult = getUserGroupService().getUserInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if ("getGroupInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/groupInfo.jsp"); Map<String, Object> pageResult = getUserGroupService().getGroupInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if ("getJobList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("viewJobInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("suspendJob".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); request.setAttribute("nowAction", "jobManager"); getJobService().suspendJob(filter); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("continueJob".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); getJobService().continueJob(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("suspendTrigger".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); getJobService().suspendTrigger(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("continueTrigger".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); getJobService().continueTrigger(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("setHis".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().setHistory(filter); } else if ("updateCache".equals(action)) { ProcessEngineManagement.getDefaultProcessEngine().cleanCache(true, true); response.getWriter().write("update success!"); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); try { CurrentThread.rollBack(); } catch (SQLException e1) { e1.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); } } finally { if (out != null) { out.flush(); out.close(); } try { CurrentThread.clear(); } catch (SQLException e) { e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); } } if (rd != null) rd.forward(request, response); }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * /*from w w w.jav a 2s. c o 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; }