Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:org.joget.apps.app.controller.ConsoleWebController.java

@RequestMapping("/console/monitor/log/(*:fileName)")
public void consoleMonitorLogs(HttpServletResponse response, @RequestParam("fileName") String fileName)
        throws IOException {
    if (HostManager.isVirtualHostEnabled()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from w  w w.  ja v  a 2s.  co  m
    }

    ServletOutputStream stream = response.getOutputStream();

    String decodedFileName = fileName;
    try {
        decodedFileName = URLDecoder.decode(fileName, "UTF8");
    } catch (UnsupportedEncodingException e) {
        // ignore
    }

    File file = LogUtil.getTomcatLogFile(decodedFileName);
    if (file == null || file.isDirectory() || !file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    DataInputStream in = new DataInputStream(new FileInputStream(file));
    byte[] bbuf = new byte[65536];

    try {
        // set attachment filename
        response.setHeader("Content-Disposition",
                "attachment; filename*=UTF-8''" + URLEncoder.encode(decodedFileName, "UTF8"));

        // send output
        int length = 0;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            stream.write(bbuf, 0, length);
        }
    } finally {
        in.close();
        stream.flush();
        stream.close();
    }
}

From source file:org.joget.apps.app.controller.ConsoleWebController.java

@RequestMapping("/console/app/(*:appId)/(~:version)/export")
public void consoleAppExport(HttpServletResponse response, @RequestParam(value = "appId") String appId,
        @RequestParam(value = "version", required = false) String version) throws IOException {
    ServletOutputStream output = null;
    try {//from w  w  w  .jav a2 s.  c o m
        // verify app
        AppDefinition appDef = appService.getAppDefinition(appId, version);
        if (appDef == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // determine output filename
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        String filename = APP_ZIP_PREFIX + appDef.getId() + "-" + appDef.getVersion() + "-" + timestamp
                + ".jwa";

        // set response headers
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "inline; filename=" + filename);
        output = response.getOutputStream();

        // export app
        appService.exportApp(appDef.getId(), appDef.getVersion().toString(), output);

    } catch (Exception ex) {
        LogUtil.error(getClass().getName(), ex, "");
    } finally {
        if (output != null) {
            output.flush();
        }
    }
}

From source file:info.magnolia.cms.filters.RangeSupportFilter.java

private HttpServletResponse wrapResponse(final HttpServletRequest request, final HttpServletResponse response) {
    return new HttpServletResponseWrapper(response) {

        /** default length is max. We hope that the underlying code will set proper content length as a header before we proceed serving some bytes. */
        private int length = Integer.MAX_VALUE;

        private final Map<String, Object> headers = new HashMap<String, Object>();

        private String eTag;

        private List<RangeInfo> ranges;

        private RangeInfo full;

        private ServletOutputStream stream;

        private PrintWriter writer;

        @Override// w  w w.  java 2s. c  o  m
        public void addDateHeader(String name, long date) {
            super.addDateHeader(name, date);
            this.headers.put(name, date);
            if ("Last-Modified".equalsIgnoreCase(name)) {
                lastModTime = date;
            }
        }

        @Override
        public void setDateHeader(String name, long date) {
            super.setDateHeader(name, date);
            this.headers.put(name, date);
            if ("Last-Modified".equalsIgnoreCase(name)) {
                lastModTime = date;
            }
        }

        @Override
        public void addHeader(String name, String value) {
            if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) {
                log.warn("content disposition enforced by underlying filter/servlet");
            }
            super.addHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setHeader(String name, String value) {
            if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) {
                log.warn("content disposition enforced by underlying filter/servlet");
            }
            super.setHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void addIntHeader(String name, int value) {
            super.addIntHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setIntHeader(String name, int value) {
            super.setIntHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setContentLength(int len) {
            this.length = len;
            // do not propagate length up. We might not be able to change it once it is set. We will set it ourselves once we are ready to serve bytes.
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            // make sure we set stream only once. Multiple calls to this method are allowed.
            if (this.stream == null) {
                ServletOutputStream stream = super.getOutputStream();
                // wrap the response to filter out everything except desired range
                this.stream = addRangeSupportWrapper(request, response, stream);

                if (!isServeContent || this.stream == null) {
                    // swallow output on head requests
                    this.stream = new ServletOutputStream() {

                        @Override
                        public void write(int b) throws IOException {
                            // do nothing, we do not write any output now
                        }
                    };
                }
            }
            return stream;
        }

        private ServletOutputStream addRangeSupportWrapper(final HttpServletRequest request,
                final HttpServletResponse response, ServletOutputStream stream) throws IOException {
            if (!processContent(request, response)) {
                // we might have to return null stream instead as the previous method already called res.sendError();
                return null;
            }

            if (headers.containsKey("Content-Range")) {
                // doesn't work for tomcat as it accesses underlying stream under our hands!!!
                log.debug("Range request was handled by underlying filter/servlet.");
                return stream;
            }
            if (ranges == null || ranges.isEmpty()) {
                // no op, serve all as usual
                log.debug("Didn't find any range to speak of. Serving all content as usual.");
                if (length != Integer.MAX_VALUE) {
                    // set real length when we know it
                    response.setContentLength(length);
                }
            } else if (ranges.size() == 1) {
                RangeInfo range = ranges.get(0);
                log.debug("Serving range [{}].", range);
                // setting 206 header is essential for some clients. The would abort if response is set to 200
                response.setStatus(SC_PARTIAL_CONTENT);
                stream = new RangedOutputStream(stream, range);
            } else {
                log.error("Requested multiple ranges [{}].", ranges.size());
                // TODO: add support for multiple ranges (sent as multipart request), for now just send error back
                response.setHeader("Content-Range", "bytes */" + length);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                // again we might have to return null stream after calling sendError() as the original stream might no longer be valid
            }
            return stream;
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            if (!wrapWriter) {
                return super.getWriter();
            }
            if (this.writer == null) {
                this.writer = new PrintWriter(new OutputStreamWriter(getOutputStream()));
            }
            return writer;
        }

        private boolean processContent(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            log.debug("Serving binary on uri {} was last modified at {}",
                    new Object[] { request.getRequestURI(), lastModTime });
            if (!isRequestValid(request, response)) {
                log.debug("Skipping request {} since it doesn't require body",
                        new Object[] { request.getRequestURI() });
                return false;
            }
            if (!processRange(request)) {
                log.debug("Could not process range of request {}", new Object[] { request.getRequestURI() });
                return false;
            }
            return true;
        }

        private boolean processRange(HttpServletRequest request) throws IOException {
            full = new RangeInfo(0, length - 1, length);
            ranges = new ArrayList<RangeInfo>();

            String range = request.getHeader("Range");

            // Valid range header format is "bytes=n-n,n-n,n-n...". If not, then return 416.
            if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                response.setHeader("Content-Range", "bytes */" + length);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                return false;
            }

            // If-Range header must match ETag or be greater then LastModified. If not, then return full file.
            String ifRange = request.getHeader("If-Range");
            if (ifRange != null && !ifRange.equals(eTag)) {
                try {
                    long ifRangeTime = request.getDateHeader("If-Range");
                    if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModTime) {
                        ranges.add(full);
                    }
                } catch (IllegalArgumentException ignore) {
                    // happens when if-range contains something else then date
                    ranges.add(full);
                }
            }

            // in case there were no invalid If-Range headers, then look at requested byte ranges.
            if (ranges.isEmpty()) {
                for (String part : range.substring(6).split(",")) {
                    int start = intSubstring(StringUtils.substringBefore(part, "-"));
                    int end = intSubstring(StringUtils.substringAfter(part, "-"));

                    if (start == -1) {
                        start = length - end;
                        end = length - 1;
                    } else if (end == -1 || end > length - 1) {
                        end = length - 1;
                    }

                    // Is range valid?
                    if (start > end) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return false;
                    }

                    // Add range.
                    ranges.add(new RangeInfo(start, end, length));
                }
            }

            response.setHeader("ETag", eTag);
            if (ranges.size() == 1) {
                RangeInfo r = ranges.get(0);
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("Content-Range",
                        "bytes " + r.start + "-" + r.end + "/" + r.totalLengthOfServedBinary);
                length = r.lengthOfRange;
            }
            return true;
        }

        private int intSubstring(String value) {
            return value.length() > 0 ? Integer.parseInt(value) : -1;
        }

        @Override
        public void flushBuffer() throws IOException {
            if (writer != null) {
                writer.flush();
            }
            if (stream != null) {
                stream.flush();
            }

            super.flushBuffer();
        }

        private boolean isRequestValid(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            String fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/");
            eTag = fileName + "_" + length + "_" + lastModTime;

            // If-None-Match header should contain "*" or ETag.
            String ifNoneMatch = request.getHeader("If-None-Match");
            if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                response.setHeader("ETag", eTag); // Required in 304.
                log.debug("Returning {} on header If-None-Match", HttpServletResponse.SC_NOT_MODIFIED);
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }

            // If-Modified-Since header must be greater than LastModified. ignore if If-None-Match header exists
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");
            if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModTime) {
                response.setHeader("ETag", eTag); // Required in 304.
                // 304 response should contain Date header unless running on timeless server (see 304 response docu)
                response.addDateHeader("Date", lastModTime);
                log.debug("Returning {} on header If-Modified-Since", HttpServletResponse.SC_NOT_MODIFIED);
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }

            // If-Match header should contain "*" or ETag.
            String ifMatch = request.getHeader("If-Match");
            if (ifMatch != null && !matches(ifMatch, eTag)) {
                log.debug("Returning {} on header If-Match", HttpServletResponse.SC_PRECONDITION_FAILED);
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }

            // If-Unmodified-Since header must be greater than LastModified.
            long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
            if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModTime) {
                log.debug("Returning {} on header If-Unmodified-Since",
                        HttpServletResponse.SC_PRECONDITION_FAILED);
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }

            log.debug("Passed all precondition checkes for request {}", request.getRequestURI());
            return true;
        }
    };
}

From source file:nu.nethome.home.items.web.GraphServlet.java

/**
* This is the main enterence point of the class. This is called when a http request is
* routed to this servlet./*w  w w .ja  va 2 s  . c  o m*/
*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServletOutputStream p = res.getOutputStream();
    Date startTime = null;
    Date stopTime = null;

    // Analyse arguments
    String fileName = req.getParameter("file");
    if (fileName != null)
        fileName = getFullFileName(fromURL(fileName));
    String startTimeString = req.getParameter("start");
    String stopTimeString = req.getParameter("stop");
    try {
        if (startTimeString != null) {
            startTime = m_Format.parse(startTimeString);
        }
        if (stopTimeString != null) {
            stopTime = m_Format.parse(stopTimeString);
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    String look = req.getParameter("look");
    if (look == null)
        look = "";

    TimeSeries timeSeries = new TimeSeries("Data", Minute.class);

    // Calculate time window
    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date startOfDay = cal.getTime();
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    Date startOfWeek = cal.getTime();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    Date startOfMonth = cal.getTime();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    Date startOfYear = cal.getTime();

    // if (startTime == null) startTime = startOfWeek;
    if (stopTime == null)
        stopTime = currentTime;
    if (startTime == null)
        startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L);

    try {
        // Open the data file
        File logFile = new File(fileName);
        Scanner fileScanner = new Scanner(logFile);
        Long startTimeMs = startTime.getTime();
        Long month = 1000L * 60L * 60L * 24L * 30L;
        boolean doOptimize = true;
        boolean justOptimized = false;
        try {
            while (fileScanner.hasNext()) {
                try {
                    // Get next log entry
                    String line = fileScanner.nextLine();
                    if (line.length() > 21) {
                        // Adapt the time format
                        String minuteTime = line.substring(0, 16).replace('.', '-');
                        // Parse the time stamp
                        Minute min = Minute.parseMinute(minuteTime);

                        // Ok, this is an ugly optimization. If the current time position in the file
                        // is more than a month (30 days) ahead of the start of the time window, we
                        // quick read two weeks worth of data, assuming that there is 4 samples per hour.
                        // This may lead to scanning past start of window if there are holes in the data
                        // series.
                        if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) {
                            for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) {
                                fileScanner.nextLine();
                            }
                            justOptimized = true;
                            continue;
                        }
                        // Detect if we have scanned past the window start position just after an optimization scan.
                        // If this is the case it may be because of the optimization. In that case we have to switch 
                        // optimization off and start over.
                        if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) {
                            logFile = new File(fileName);
                            fileScanner = new Scanner(logFile);
                            doOptimize = false;
                            continue;
                        }
                        justOptimized = false;
                        // Check if value is within time window
                        if ((min.getFirstMillisecond() > startTimeMs)
                                && (min.getFirstMillisecond() < stopTime.getTime())) {
                            // Parse the value
                            double value = Double.parseDouble((line.substring(20)).replace(',', '.'));
                            // Add the entry
                            timeSeries.add(min, value);
                            doOptimize = false;
                        }
                    }
                } catch (SeriesException se) {
                    // Bad entry, for example due to duplicates at daylight saving time switch
                } catch (NumberFormatException nfe) {
                    // Bad number format in a line, try to continue
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            fileScanner.close();
        }
    } catch (FileNotFoundException f) {
        System.out.println(f.toString());
    }

    // Create a collection for plotting
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(timeSeries);

    JFreeChart chart;

    int xSize = 750;
    int ySize = 450;
    // Customize colors and look of the Graph.
    if (look.equals("mobtemp")) {
        // Look for the mobile GUI
        chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false);
        XYPlot plot = chart.getXYPlot();
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        xSize = 175;
        ySize = 180;
    } else {
        // Create a Chart with time range as heading
        SimpleDateFormat localFormat = new SimpleDateFormat();
        String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime);
        chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false);

        Paint background = new Color(0x9D8140);
        chart.setBackgroundPaint(background);
        TextTitle title = chart.getTitle(); // fix title
        Font titleFont = title.getFont();
        titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0);
        title.setFont(titleFont);
        title.setPaint(Color.darkGray);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(background);
        plot.setDomainGridlinePaint(Color.darkGray);
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        plot.setRangeGridlinePaint(Color.darkGray);
        XYItemRenderer renderer = plot.getRenderer(0);
        renderer.setSeriesPaint(0, Color.darkGray);
        xSize = 750;
        ySize = 450;
    }

    try {
        res.setContentType("image/png");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "no-cache");
        res.setStatus(HttpServletResponse.SC_OK);
        ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

    p.flush();
    p.close();
    return;
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from w  w w. jav a 2  s .c  om
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID));

    if (StringUtil.isEmpty(userId)) {
        String context = request.getContextPath();
        response.sendRedirect(context + "/");
        return;
    }
    CurrentThread.init();
    ServletOutputStream out = null;
    String action = StringUtil.getString(request.getParameter("action"));
    if (StringUtil.isEmpty(action)) {
        action = StringUtil.getString(request.getAttribute("action"));
    }
    if (StringUtil.isEmpty(action)) {
        action = "getMyTask";
    }
    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();
            }
        } 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 (action.equals("getMyProcess")) {
            rd = request.getRequestDispatcher("/fixflow/center/startTask.jsp");
            List<Map<String, String>> result = getFlowCenter().queryStartProcess(userId);

            Map<String, List<Map<String, String>>> newResult = new HashMap<String, List<Map<String, String>>>();
            for (Map<String, String> tmp : result) {
                String category = tmp.get("category");
                if (StringUtil.isEmpty(category))
                    category = "";

                List<Map<String, String>> tlist = newResult.get(category);
                if (tlist == null) {
                    tlist = new ArrayList<Map<String, String>>();
                }
                tlist.add(tmp);
                newResult.put(category, tlist);
            }
            request.setAttribute("result", newResult);
            //??sqlserverbug????
            request.setAttribute("userId", userId); // userId add Rex
            try {
                List<Map<String, String>> lastestProcess = getFlowCenter().queryLastestProcess(userId);
                request.setAttribute("lastest", lastestProcess);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (action.equals("getMyTask")) {
            rd = request.getRequestDispatcher("/fixflow/center/todoTask.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().queryMyTaskNotEnd(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getProcessImage")) {
            response.getOutputStream();
        } else if (action.equals("getAllProcess")) {
            rd = request.getRequestDispatcher("/fixflow/center/queryprocess.jsp");
            Map<String, Object> pageResult = getFlowCenter().queryTaskInitiator(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getPlaceOnFile")) {
            rd = request.getRequestDispatcher("/fixflow/center/placeOnFile.jsp");
            Map<String, Object> pageResult = getFlowCenter().queryPlaceOnFile(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getTaskDetailInfo")) {
            rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp");
            Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getTaskDetailInfoSVG")) {
            rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp");
            Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfoSVG(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getFlowGraph")) {
            InputStream is = getFlowCenter().getFlowGraph(filter);
            out = response.getOutputStream();
            response.setContentType("application/octet-stream;charset=UTF-8");
            byte[] buff = new byte[2048];
            int size = 0;
            while (is != null && (size = is.read(buff)) != -1) {
                out.write(buff, 0, size);
            }
        } else if (action.equals("getUserInfo")) {
            rd = request.getRequestDispatcher("/fixflow/common/userInfo.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getUserIcon")) {
            rd = request.getRequestDispatcher("/fixflow/common/userOperation.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("updateUserIcon")) {
            rd = request.getRequestDispatcher("/FlowCenter?action=getUserInfo");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            getFlowCenter().saveUserIcon(filter);

        } else if (action.equals("selectUserList")) { //
            String isMulti = request.getParameter("isMulti");
            rd = request.getRequestDispatcher("/fixflow/common/selectUserList.jsp?isMulti=" + isMulti);
            Map<String, Object> pageResult = getFlowCenter().getAllUsers(filter);
            filter.putAll(pageResult);

            request.setAttribute("result", filter);
            request.setAttribute("isMulti", isMulti);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("selectNodeList")) { //
            rd = request.getRequestDispatcher("/fixflow/common/selectNodeList.jsp");
            Map<String, Object> pageResult = getFlowCenter().getRollbackNode(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("selectStepList")) { //
            rd = request.getRequestDispatcher("/fixflow/common/selectStepList.jsp");
            Map<String, Object> pageResult = getFlowCenter().getRollbackTask(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("viewDelegation")) { //
            rd = request.getRequestDispatcher("/fixflow/common/setDelegation.jsp");
            Map<String, Object> pageResult = new HashMap<String, Object>();
            pageResult = this.getFlowIdentityService().getUserDelegationInfo(userId);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("saveDelegation")) { //

            String agentInfoJson = StringUtil.getString(request.getParameter("insertAndUpdate"));
            if (StringUtil.isNotEmpty(agentInfoJson)) {
                Map<String, Object> delegationInfo = JSONUtil.parseJSON2Map(agentInfoJson);
                this.getFlowIdentityService().saveUserDelegationInfo(delegationInfo);
            }
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<script>alert('??');window.close();</script>");
        }
    } 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) {
            request.setAttribute("errorMsg", e.getMessage());
            e.printStackTrace();
        }
    }
    if (rd != null) {
        rd.forward(request, response);
    }
}

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CurrentThread.init();/*from  w w w . j a v  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:org.openmrs.module.tracnetreporting.impl.TracNetPatientServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * /*from  w ww .  ja v a2s  .  c o  m*/
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@Override
public void exportDataToCsvFile(HttpServletRequest request, HttpServletResponse response,
        Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;
    for (String indicator : indicatorsList.keySet()) {
        count++;
        outputStream.println(
                count + " , " + indicator.toString() + " , " + indicatorsList.get(indicator).toString());
    }

    outputStream.flush();
    outputStream.close();
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * //from   www . j  a  v a 2 s  .c  o  m
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@SuppressWarnings("unchecked")
@Override
public void exportDataToCsvFile(HttpServletRequest request, HttpServletResponse response,
        Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;

    List<String> indicator_msg = null;

    indicator_msg = (ArrayList<String>) request.getSession().getAttribute(request.getParameter("id") + "_msg");

    for (String indicator : indicatorsList.keySet()) {
        count++;
        outputStream.println(indicator.toString().substring(4) + " , " + indicator_msg.get(count - 1) + " , "
                + indicatorsList.get(indicator).toString());
    }

    outputStream.flush();
    outputStream.close();
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * /*from   w  ww.j  a  va2 s .co  m*/
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@Override
public void exportPatientsListToCsvFile(HttpServletRequest request, HttpServletResponse response,
        List<Person> patientsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    Session session = getSessionFactory().getCurrentSession();
    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;

    for (Person person : patientsList) {

        Date maxEncounterDateTime = (Date) session
                .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where patient_id = "
                        + person.getPersonId())
                .uniqueResult();

        Date maxReturnVisitDay = (Date) session
                .createSQLQuery("select cast(max(value_datetime) as DATE ) " + "from obs where concept_id = "
                        + ConstantValues.NEXT_SCHEDULED_VISIT + " and person_id = " + person.getPersonId())
                .uniqueResult();

        count++;
        outputStream.println(count + " , " + person.getPersonId() + " , " + person.getFamilyName() + " "
                + person.getGivenName() + " , " + person.getGender() + " , " + maxEncounterDateTime.toString()
                + " , " + maxReturnVisitDay.toString());
    }

    outputStream.flush();
    outputStream.close();
}