Example usage for java.util.zip ZipOutputStream putNextEntry

List of usage examples for java.util.zip ZipOutputStream putNextEntry

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream putNextEntry.

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

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  .  java2s  .com
    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: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/*  ww w.  j a  v a  2  s .c  om*/
 *          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:cross.io.misc.WorkflowZipper.java

private void addRelativeZipEntry(final int bufsize, final ZipOutputStream zos, final byte[] input_buffer,
        final String relativePath, final File file, final HashSet<String> zipEntries) throws IOException {
    log.debug("Adding zip entry for file {}", file);
    if (file.exists() && file.isFile()) {
        // Use the file name for the ZipEntry name.
        final ZipEntry zip_entry = new ZipEntry(relativePath);
        if (zipEntries.contains(relativePath)) {
            log.info("Skipping duplicate zip entry {}", relativePath + "/" + file.getName());
            return;
        } else {//from w ww.  ja  v a 2  s . c  om
            zipEntries.add(relativePath);
        }
        zos.putNextEntry(zip_entry);

        // Create a buffered input stream from the file stream.
        final FileInputStream in = new FileInputStream(file);
        // Read from source into buffer and write, thereby compressing
        // on the fly
        try (BufferedInputStream source = new BufferedInputStream(in, bufsize)) {
            // Read from source into buffer and write, thereby compressing
            // on the fly
            int len = 0;
            while ((len = source.read(input_buffer, 0, bufsize)) != -1) {
                zos.write(input_buffer, 0, len);
            }
            zos.flush();
        }
        zos.closeEntry();
    } else {
        log.warn("Skipping nonexistant file or directory {}", file);
    }
}

From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    long now = System.currentTimeMillis();
    Timestamp submissionTimestamp = new Timestamp(now);

    // these are set by filters or previous servlets
    Project project = (Project) request.getAttribute(PROJECT);
    StudentRegistration studentRegistration = (StudentRegistration) request.getAttribute(STUDENT_REGISTRATION);
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    boolean webBasedUpload = ((Boolean) request.getAttribute("webBasedUpload")).booleanValue();
    String clientTool = multipartRequest.getCheckedParameter("submitClientTool");
    String clientVersion = multipartRequest.getOptionalCheckedParameter("submitClientVersion");
    String cvsTimestamp = multipartRequest.getOptionalCheckedParameter("cvstagTimestamp");

    Collection<FileItem> files = multipartRequest.getFileItems();
    Kind kind;/*ww  w  .  j a v a2  s  .c  om*/

    byte[] zipOutput = null; // zipped version of bytesForUpload
    boolean fixedZip = false;
    try {

        if (files.size() > 1) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            for (FileItem item : files) {
                String name = item.getName();
                if (name == null || name.length() == 0)
                    continue;
                byte[] bytes = item.get();
                ZipEntry zentry = new ZipEntry(name);
                zentry.setSize(bytes.length);
                zentry.setTime(now);
                zos.putNextEntry(zentry);
                zos.write(bytes);
                zos.closeEntry();
            }
            zos.flush();
            zos.close();
            zipOutput = bos.toByteArray();
            kind = Kind.MULTIFILE_UPLOAD;

        } else {
            FileItem fileItem = multipartRequest.getFileItem();
            if (fileItem == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "There was a problem processing your submission. "
                                + "No files were found in your submission");
                return;
            }
            // get size in bytes
            long sizeInBytes = fileItem.getSize();
            if (sizeInBytes == 0 || sizeInBytes > Integer.MAX_VALUE) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Trying upload file of size " + sizeInBytes);
                return;
            }

            // copy the fileItem into a byte array
            byte[] bytesForUpload = fileItem.get();
            String fileName = fileItem.getName();

            boolean isSpecialSingleFile = OfficeFileName.matcher(fileName).matches();

            FormatDescription desc = FormatIdentification.identify(bytesForUpload);
            if (!isSpecialSingleFile && desc != null && desc.getMimeType().equals("application/zip")) {
                fixedZip = FixZip.hasProblem(bytesForUpload);
                kind = Kind.ZIP_UPLOAD;
                if (fixedZip) {
                    bytesForUpload = FixZip.fixProblem(bytesForUpload,
                            studentRegistration.getStudentRegistrationPK());
                    kind = Kind.FIXED_ZIP_UPLOAD;
                }
                zipOutput = bytesForUpload;

            } else {

                // ==========================================================================================
                // [NAT] [Buffer to ZIP Part]
                // Check the type of the upload and convert to zip format if
                // possible
                // NOTE: I use both MagicMatch and FormatDescription (above)
                // because MagicMatch was having
                // some trouble identifying all zips

                String mime = URLConnection.getFileNameMap().getContentTypeFor(fileName);

                if (!isSpecialSingleFile && mime == null)
                    try {
                        MagicMatch match = Magic.getMagicMatch(bytesForUpload, true);
                        if (match != null)
                            mime = match.getMimeType();
                    } catch (Exception e) {
                        // leave mime as null
                    }

                if (!isSpecialSingleFile && "application/zip".equalsIgnoreCase(mime)) {
                    zipOutput = bytesForUpload;
                    kind = Kind.ZIP_UPLOAD2;
                } else {
                    InputStream ins = new ByteArrayInputStream(bytesForUpload);
                    if ("application/x-gzip".equalsIgnoreCase(mime)) {
                        ins = new GZIPInputStream(ins);
                    }

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ZipOutputStream zos = new ZipOutputStream(bos);

                    if (!isSpecialSingleFile && ("application/x-gzip".equalsIgnoreCase(mime)
                            || "application/x-tar".equalsIgnoreCase(mime))) {

                        kind = Kind.TAR_UPLOAD;

                        TarInputStream tins = new TarInputStream(ins);
                        TarEntry tarEntry = null;
                        while ((tarEntry = tins.getNextEntry()) != null) {
                            zos.putNextEntry(new ZipEntry(tarEntry.getName()));
                            tins.copyEntryContents(zos);
                            zos.closeEntry();
                        }
                        tins.close();
                    } else {
                        // Non-archive file type
                        if (isSpecialSingleFile)
                            kind = Kind.SPECIAL_ZIP_FILE;
                        else
                            kind = Kind.SINGLE_FILE;
                        // Write bytes to a zip file
                        ZipEntry zentry = new ZipEntry(fileName);
                        zos.putNextEntry(zentry);
                        zos.write(bytesForUpload);
                        zos.closeEntry();
                    }
                    zos.flush();
                    zos.close();
                    zipOutput = bos.toByteArray();
                }

                // [END Buffer to ZIP Part]
                // ==========================================================================================

            }
        }

    } catch (NullPointerException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "There was a problem processing your submission. "
                        + "You should submit files that are either zipped or jarred");
        return;
    } finally {
        for (FileItem fItem : files)
            fItem.delete();
    }

    if (webBasedUpload) {
        clientTool = "web";
        clientVersion = kind.toString();
    }

    Submission submission = uploadSubmission(project, studentRegistration, zipOutput, request,
            submissionTimestamp, clientTool, clientVersion, cvsTimestamp, getDatabaseProps(),
            getSubmitServerServletLog());

    request.setAttribute("submission", submission);

    if (!webBasedUpload) {

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Successful submission #" + submission.getSubmissionNumber() + " received for project "
                + project.getProjectNumber());

        out.flush();
        out.close();
        return;
    }
    boolean instructorUpload = ((Boolean) request.getAttribute("instructorViewOfStudent")).booleanValue();
    // boolean
    // isCanonicalSubmission="true".equals(request.getParameter("isCanonicalSubmission"));
    // set the successful submission as a request attribute
    String redirectUrl;

    if (fixedZip) {
        redirectUrl = request.getContextPath() + "/view/fixedSubmissionUpload.jsp?submissionPK="
                + submission.getSubmissionPK();
    }
    if (project.getCanonicalStudentRegistrationPK() == studentRegistration.getStudentRegistrationPK()) {
        redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
    } else if (instructorUpload) {
        redirectUrl = request.getContextPath() + "/view/instructor/project.jsp?projectPK="
                + project.getProjectPK();
    } else {
        redirectUrl = request.getContextPath() + "/view/project.jsp?projectPK=" + project.getProjectPK();
    }

    response.sendRedirect(redirectUrl);

}

From source file:interactivespaces.workbench.project.java.BndOsgiContainerBundleCreator.java

/**
 * Write out the contents of the folder to the distribution file.
 *
 * @param directory//www  . j av a 2s  .com
 *          folder being written to the build
 * @param buf
 *          a buffer for caching info
 * @param jarOutputStream
 *          the stream where the jar is being written
 * @param parentPath
 *          path up to this point
 *
 * @throws IOException
 *           for IO access errors
 */
private void writeJarFile(File directory, byte[] buf, ZipOutputStream jarOutputStream, String parentPath)
        throws IOException {
    File[] files = directory.listFiles();
    if (files == null || files.length == 0) {
        log.warn("No source files found in " + directory.getAbsolutePath());
        return;
    }
    for (File file : files) {
        if (file.isDirectory()) {
            writeJarFile(file, buf, jarOutputStream, parentPath + file.getName() + "/");
        } else {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);

                // Add ZIP entry to output stream.
                jarOutputStream.putNextEntry(new JarEntry(parentPath + file.getName()));

                // Transfer bytes from the file to the ZIP file
                int len;
                while ((len = in.read(buf)) > 0) {
                    jarOutputStream.write(buf, 0, len);
                }

                // Complete the entry
                jarOutputStream.closeEntry();
            } finally {
                fileSupport.close(in, false);
            }
        }
    }
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);//w  ww. ja  v a  2  s  .co m
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * jarclass/*from w  w  w  . j a v a  2 s.  c  o  m*/
 * @param inJar
 * @param removeClasses
 */
public static void removeFilesFromJar(File inJar, List<String> removeClasses) throws IOException {
    if (null == removeClasses || removeClasses.isEmpty()) {
        return;
    }
    File outJar = new File(inJar.getParentFile(), inJar.getName() + ".tmp");
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
                continue;
            }
            String name = entry.getName();
            String className = getClassName(name);
            if (removeClasses.contains(className)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
    FileUtils.deleteQuietly(inJar);
    FileUtils.moveFile(outJar, inJar);
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * API to zip list of files to a desired file. Operation aborted if any file is invalid or a directory.
 * /* w  w w  . j a v  a2s  .c  o m*/
 * @param filePaths {@link List}< {@link String}>
 * @param outputFilePath {@link String}
 * @throws IOException in case of error
 */
public static void zipMultipleFiles(List<String> filePaths, String outputFilePath) throws IOException {
    LOGGER.info("Zipping files to " + outputFilePath + ".zip file");
    File outputFile = new File(outputFilePath);

    if (outputFile.exists()) {
        LOGGER.info(outputFilePath + " file already exists. Deleting existing and creating a new file.");
        outputFile.delete();
    }

    byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
    int bytesRead;
    ZipOutputStream out = null;
    FileInputStream input = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(outputFilePath));
        for (String filePath : filePaths) {
            LOGGER.info("Writing file " + filePath + " into zip file.");

            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                throw new Exception("Invalid file: " + file.getAbsolutePath()
                        + ". Either file does not exists or it is a directory.");
            }
            input = new FileInputStream(file); // Stream to read file
            ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry
            out.putNextEntry(entry); // Store entry
            bytesRead = input.read(buffer);
            while (bytesRead != -1) {
                out.write(buffer, 0, bytesRead);
                bytesRead = input.read(buffer);
            }

        }

    } catch (Exception e) {
        LOGGER.error("Exception occured while zipping file." + e.getMessage(), e);
    } finally {
        if (input != null) {
            input.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the images with input device ids from cache and stores it in zip
 * output stream./*  w ww .  ja  va2 s .  co m*/
 *
 * @param capturedImageIds
 *            Ids of captures images
 * @param deviceMacs
 *            Mac address of selected devices
 * @param response
 *            http servelet response
 * @param session
 *            http session.
 */
public void addImagesToZipFile(String[] capturedImageIds, String[] deviceMacs, HttpServletResponse response,
        HttpSession session) {

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + "Images_" + getCurrentDateAndTime() + ".zip\"");
    response.setContentType("application/zip");

    ServletOutputStream serveletOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        serveletOutputStream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        BufferedImage image;
        ZipEntry zipEntry;
        ByteArrayOutputStream imgByteArrayOutputStream = null;

        for (int i = 0; i < deviceMacs.length; i++) {
            // Check whether id of captured image is null or not
            if (!StringUtils.isEmpty(capturedImageIds[i])) {
                image = imgCache.getItem(capturedImageIds[i]);
                zipEntry = new ZipEntry(deviceMacs[i].toUpperCase() + "." + IMG_FORMAT);
                zipOutputStream.putNextEntry(zipEntry);
                imgByteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_FORMAT, imgByteArrayOutputStream);
                imgByteArrayOutputStream.flush();
                zipOutputStream.write(imgByteArrayOutputStream.toByteArray());
                zipOutputStream.closeEntry();
            }
        }

        zipOutputStream.flush();
        zipOutputStream.close();
        serveletOutputStream.write(byteArrayOutputStream.toByteArray());
    } catch (IOException ioe) {
        LOGGER.error("Image zipping failed !!!", ioe);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java

private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile, Map<String, String> excludeFiles)
        throws IOException {
    // First, copy the contents from the existing outFile:
    Enumeration<? extends ZipEntry> entries = inputFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = new ZipEntry(entries.nextElement());
        if (excludeFiles.get(entry.getName()) != null) {
            //??.
            continue;
        }/* www.jav a 2s .c o m*/
        // We can't reuse the compressed size because it depends on compression sizes.
        entry.setCompressedSize(-1);
        outputFile.putNextEntry(entry);

        // No need to create directory entries in the final apk
        if (!entry.isDirectory()) {
            BrutIO.copy(inputFile, outputFile, entry);
        }

        outputFile.closeEntry();
    }
}