Example usage for java.util.zip ZipOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:edu.mit.lib.bagit.Filler.java

private void fillZip(File dirFile, String relBase, ZipOutputStream zout) throws IOException {
    for (File file : dirFile.listFiles()) {
        String relPath = relBase + File.separator + file.getName();
        if (file.isDirectory()) {
            fillZip(file, relPath, zout);
        } else {//  ww w  .  j  a v  a2 s .  c  om
            ZipEntry entry = new ZipEntry(relPath);
            entry.setTime(0L);
            zout.putNextEntry(entry);
            Files.copy(file.toPath(), zout);
            zout.closeEntry();
        }
    }
}

From source file:org.apache.openmeetings.backup.BackupExport.java

private void writeZipDir(URI base, File dir, ZipOutputStream zos, File zipFile) throws IOException {
    for (File file : dir.listFiles()) {
        if (zipFile.equals(file)) {
            continue;
        }/*from   ww  w  .  j  a  v a2s  .  co  m*/
        if (file.isDirectory()) {
            writeZipDir(base, file, zos, zipFile);
        } else {
            String path = base.relativize(file.toURI()).toString();
            log.debug("Writing '" + path + "' to zip file");
            ZipEntry zipEntry = new ZipEntry(path);
            zos.putNextEntry(zipEntry);

            OmFileHelper.copyFile(file, zos);
            zos.closeEntry();
        }
    }
}

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;//from  ww w.j a  va  2  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:com.simiacryptus.mindseye.lang.Layer.java

/**
 * Write zip.// ww w  . j  a  va 2s. c  om
 *
 * @param out       the out
 * @param precision the precision
 */
default void writeZip(@Nonnull ZipOutputStream out, SerialPrecision precision) {
    try {
        @Nonnull
        HashMap<CharSequence, byte[]> resources = new HashMap<>();
        JsonObject json = getJson(resources, precision);
        out.putNextEntry(new ZipEntry("model.json"));
        @Nonnull
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(out));
        writer.setIndent("  ");
        writer.setHtmlSafe(true);
        writer.setSerializeNulls(false);
        new GsonBuilder().setPrettyPrinting().create().toJson(json, writer);
        writer.flush();
        out.closeEntry();
        resources.forEach((name, data) -> {
            try {
                out.putNextEntry(new ZipEntry(String.valueOf(name)));
                IOUtils.write(data, out);
                out.flush();
                out.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.mpg.escidoc.services.exportmanager.Export.java

/**
 * Write License Agreement file to the archive OutputStream
 * /* w  w  w .j  a v  a2  s.  c  om*/
 * @param af
 *            is Archive Format
 * @param os
 *            - archive OutputStream
 * @throws IOException
 * @throws ExportManagerException
 */
private void addLicenseAgreement(File license, OutputStream os) throws IOException, ExportManagerException {

    if (license != null) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(license));
        if (os instanceof TarOutputStream) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(baos);
            writeFromStreamToStream(bis, baos);
            bis.close();
            byte[] file = baos.toByteArray();
            bos.close();
            TarEntry te = new TarEntry(license.getName());
            te.setSize(file.length);
            TarOutputStream tos = (TarOutputStream) os;
            tos.putNextEntry(te);
            tos.write(file);
            tos.closeEntry();
        } else if (os instanceof ZipOutputStream) {
            ZipEntry ze = new ZipEntry(license.getName());
            ZipOutputStream zos = (ZipOutputStream) os;
            zos.putNextEntry(ze);
            writeFromStreamToStream(bis, zos);
            bis.close();
            zos.closeEntry();
        } else {
            throw new ExportManagerException("Wrong archive OutputStream: " + os);
        }
    }
}

From source file:cascading.tap.hadoop.ZipInputFormatTest.java

public void testSplits() throws Exception {
    JobConf job = new JobConf();
    FileSystem currentFs = FileSystem.get(job);

    Path file = new Path(workDir, "test.zip");

    Reporter reporter = Reporter.NULL;// w  w w.  j a  v  a2s .  c o m

    int seed = new Random().nextInt();
    LOG.info("seed = " + seed);
    Random random = new Random(seed);
    FileInputFormat.setInputPaths(job, file);

    for (int entries = 1; entries < MAX_ENTRIES; entries += random.nextInt(MAX_ENTRIES / 10) + 1) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream);
        long length = 0;

        LOG.debug("creating; zip file with entries = " + entries);

        // for each entry in the zip file
        for (int entryCounter = 0; entryCounter < entries; entryCounter++) {
            // construct zip entries splitting MAX_LENGTH between entries
            long entryLength = MAX_LENGTH / entries;
            ZipEntry zipEntry = new ZipEntry("/entry" + entryCounter + ".txt");
            zipEntry.setMethod(ZipEntry.DEFLATED);
            zos.putNextEntry(zipEntry);

            for (length = entryCounter * entryLength; length < (entryCounter + 1) * entryLength; length++) {
                zos.write(Long.toString(length).getBytes());
                zos.write("\n".getBytes());
            }

            zos.flush();
            zos.closeEntry();
        }

        zos.flush();
        zos.close();

        currentFs.delete(file, true);

        OutputStream outputStream = currentFs.create(file);

        byteArrayOutputStream.writeTo(outputStream);
        outputStream.close();

        ZipInputFormat format = new ZipInputFormat();
        format.configure(job);
        LongWritable key = new LongWritable();
        Text value = new Text();
        InputSplit[] splits = format.getSplits(job, 100);

        BitSet bits = new BitSet((int) length);
        for (int j = 0; j < splits.length; j++) {
            LOG.debug("split[" + j + "]= " + splits[j]);
            RecordReader<LongWritable, Text> reader = format.getRecordReader(splits[j], job, reporter);

            try {
                int count = 0;

                while (reader.next(key, value)) {
                    int v = Integer.parseInt(value.toString());
                    LOG.debug("read " + v);

                    if (bits.get(v))
                        LOG.warn("conflict with " + v + " in split " + j + " at position " + reader.getPos());

                    assertFalse("key in multiple partitions.", bits.get(v));
                    bits.set(v);
                    count++;
                }

                LOG.debug("splits[" + j + "]=" + splits[j] + " count=" + count);
            } finally {
                reader.close();
            }
        }

        assertEquals("some keys in no partition.", length, bits.cardinality());
    }
}

From source file:com.founder.fix.fixflow.FlowManager.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CurrentThread.init();// w w  w.  j  a va2s  . c  om
    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:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

private void zipUp(File out, File[] in) {
    FileOutputStream fout = null;
    ZipOutputStream zout = null;
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    try {/*from w  w  w  .  j av a 2 s .com*/
        fout = new FileOutputStream(out);
        zout = new ZipOutputStream(fout);
        zout.setMethod(ZipOutputStream.DEFLATED);

        for (File currFile : in) {
            FileInputStream fin = new FileInputStream(currFile);
            ZipEntry currEntry = new ZipEntry(currFile.getName());
            zout.putNextEntry(currEntry);
            while ((bytesRead = fin.read(buffer)) > 0) {
                zout.write(buffer, 0, bytesRead);
            }
            zout.closeEntry();
            fin.close();
        }
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    } finally {
        try {
            zout.close();
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

}

From source file:de.bps.onyx.plugin.OnyxExportManager.java

public void exportResults(List<QTIResultSet> resultSets, ZipOutputStream exportStream,
        CourseNode currentCourseNode) {/*from ww w . ja va  2s .  c o m*/
    final String path = createTargetFilename(currentCourseNode.getShortTitle(), "TEST");
    for (final QTIResultSet rs : resultSets) {
        String resultXml = getResultXml(rs.getIdentity().getName(),
                currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(),
                currentCourseNode.getIdent(), rs.getAssessmentID());

        String filename = path + "/" + rs.getIdentity().getName() + "_" + rs.getCreationDate() + ".xml";
        try {
            exportStream.putNextEntry(new ZipEntry(filename));
            IOUtils.write(resultXml, exportStream);
            exportStream.closeEntry();
        } catch (IOException e) {
            log.error("", e);
        }
    }
}

From source file:eu.scape_project.planning.xml.ProjectExportAction.java

/**
 * new helper method that was refactored from
 * {@link #exportAllProjectsToZip()} It takes a list of
 * {@link PlanProperties} and exports it to a zip file.
 * //from   w w w .j  av  a  2 s.com
 * @param ppList
 *            {@link PlanProperties} for plans to export
 * 
 * @return True if export was successful, false otherwise.
 */
private boolean exportPPListToZip(List<PlanProperties> ppList) {
    if (!ppList.isEmpty()) {
        log.debug("number of plans to export: " + ppList.size());
        String filename = "allprojects.zip";

        lastProjectExportPath = OS.getTmpPath() + "export" + System.currentTimeMillis() + "/";
        new File(lastProjectExportPath).mkdirs();

        String binarydataTempPath = lastProjectExportPath + "binarydata/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();

        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(lastProjectExportPath + filename));
            ZipOutputStream zipOut = new ZipOutputStream(out);

            for (PlanProperties pp : ppList) {
                log.debug("EXPORTING: " + pp.getName());
                ZipEntry zipAdd = new ZipEntry(String.format("%1$03d", pp.getId()) + "-"
                        + FileUtils.makeFilename(pp.getName()) + ".xml");
                zipOut.putNextEntry(zipAdd);
                // export the complete project, including binary data
                exportComplete(pp.getId(), zipOut, binarydataTempPath);
                zipOut.closeEntry();
            }
            zipOut.close();
            out.close();
            new File(lastProjectExportPath + "finished.info").createNewFile();

            // FacesMessages.instance().add(FacesMessage.SEVERITY_INFO,
            // "Export was written to: " + exportPath);
            log.info("Export was written to: " + lastProjectExportPath);
        } catch (IOException e) {
            // FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
            // "An error occured while generating the export file.");
            log.error("An error occured while generating the export file.", e);
            File errorInfo = new File(lastProjectExportPath + "error.info");
            try {
                Writer w = new FileWriter(errorInfo);
                w.write("An error occured while generating the export file:");
                w.write(e.getMessage());
                w.close();
            } catch (IOException e1) {
                log.error("Could not write error file.");
            }

            return false;
        } finally {
            // remove all binary temp files
            OS.deleteDirectory(binarydataTempDir);
        }
    }

    return true;
}