Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

In this page you can find the example usage for java.io Writer flush.

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:grails.plugin.errorpagesfix.PatchedErrorHandlingServlet.java

private void renderDefaultResponse(HttpServletResponse response, int statusCode, String title, String text)
        throws IOException {
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    response.setContentType(TEXT_HTML);

    Writer writer = response.getWriter();

    writer.write("<HTML>\n<HEAD>\n<TITLE>Error " + statusCode + " - " + title);
    writer.write("</TITLE>\n<BODY>\n<H2>Error " + statusCode + " - " + title + ".</H2>\n");
    writer.write(text + "<BR/>");

    for (int i = 0; i < 20; i++) {
        writer.write("\n<!-- Padding for IE                  -->");
    }/*from  w ww.  ja v  a 2s. co  m*/

    writer.write("\n</BODY>\n</HTML>\n");
    writer.flush();
}

From source file:architecture.common.license.io.LicenseWriter.java

public void write(Writer writer, int columns) throws IOException {
    String xml = document.asXML();
    String base64 = new String(Base64.encodeBase64(xml.getBytes(ApplicationConstants.DEFAULT_CHAR_ENCODING)));
    if (columns > 0)
        base64 = addLineBreaks(base64, columns);
    StringReader reader = new StringReader(base64);
    char buffer[] = new char[32768];
    int len;/*w w  w.  j  av  a  2  s  . c om*/
    while ((len = reader.read(buffer)) != -1)
        writer.write(buffer, 0, len);

    writer.flush();
}

From source file:com.aurotech.workfront.sharepoint.dao.WorkfrontServiceDao.java

@SuppressWarnings("rawtypes")
private Object request(String path, Map<String, Object> params, Set<String> fields, String method,
        boolean callAPI) throws WorkfrontException {
    HttpURLConnection conn = null;
    try {/*from  ww  w .j a va2s .co  m*/
        String query = "";
        query = "sessionID=" + sessionID + "&method=" + method;
        if (params != null) {
            for (String key : params.keySet()) {
                Object val = params.get(key);
                if (val instanceof List) {
                    List lVal = (List) val;
                    for (Object obj : lVal) {
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                                + URLEncoder.encode(String.valueOf(obj), "UTF-8");
                    }
                } else {
                    if (val instanceof Set) {
                        Set sVal = (Set) val;
                        for (Object obj : sVal) {
                            query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                                    + URLEncoder.encode(String.valueOf(obj), "UTF-8");
                        }
                    } else {
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                                + URLEncoder.encode(String.valueOf(val), "UTF-8");
                    }
                }
            }
        }

        if (fields != null) {
            query += "&fields=";
            for (String field : fields) {
                query += URLEncoder.encode(field, "UTF-8") + ",";
            }
            query = query.substring(0, query.lastIndexOf(","));
        }

        conn = createConnection(hostname + (callAPI ? apiURL : "") + path, METH_POST);

        // Send request
        Writer out = new OutputStreamWriter(conn.getOutputStream());
        // logger.debug("Query: " + URLDecoder.decode(query));

        out.write(query);
        out.flush();
        out.close();

        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = in.readLine()) != null) {
            response.append(line);
        }

        in.close();
        // Decode JSON
        JSONObject result = new JSONObject(response.toString());
        // Verify result
        if (result.has("error")) {
            throw new WorkfrontException(result.getJSONObject("error").getString("message"));
        } else if (!result.has("data") && callAPI) {
            throw new WorkfrontException("Invalid response from server");
        }

        // Manage the session
        if (path.equals(PATH_LOGIN)) {
            sessionID = result.getJSONObject("data").getString("sessionID");
        } else if (path.equals(PATH_LOGOUT)) {
            sessionID = null;
        }
        if (callAPI) {
            return result.get("data");
        }
        return result;
    } catch (Exception e) {
        logger.debug(e.getMessage(), e);

        if (conn == null) {
            throw new WorkfrontException("Unable to connect. Please check the server name");
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        StringBuilder response = new StringBuilder();
        String line;

        try {
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        JSONObject result;
        try {
            result = new JSONObject(response.toString());
            throw new WorkfrontException(result.getJSONObject("error").getString("message"));
        } catch (JSONException e1) {
            throw new WorkfrontException(response.toString());
        }

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.github.sqltojava.JavaGenerator.java

private void generateJava() {
    Properties p = new Properties();
    p.setProperty("resource.loader", "string");
    p.setProperty("resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
    Velocity.init(p);/*from  www. j a  va2 s  .co m*/

    Template template = getTemplate("sample.vm");

    Iterator<String> tableKey = tables.keySet().iterator();
    while (tableKey.hasNext()) {
        String tableName = tableKey.next();
        String className = tableName.substring(0, 1).toUpperCase()
                + tableName.substring(1).replaceFirst("(^.*?)@.*", "$1");
        VelocityContext context = new VelocityContext();
        context.put("className", className);
        context.put("tableName", tableName.replaceFirst("(^.*?)@(.*)", "$2"));
        context.put("columns", columns.get(tableName));
        context.put("outPackage", outPackage);
        try {
            String outDirs = basedir + "/" + outPackage.replaceAll("\\.", "/");
            new File(outDirs).mkdirs();
            Writer writer = new OutputStreamWriter(new FileOutputStream(outDirs + "/" + className + ".java"),
                    "utf-8");
            template.merge(context, writer);
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            getLog().log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

From source file:net.cit.tetrad.resource.MainResource.java

@RequestMapping("/mainGraph.do")
public void mainGraph(HttpServletRequest request, HttpServletResponse response) {
    log.debug("start - mainGraph.do");
    try {//from w  ww.j  a v  a 2s  .c o m
        PersonJson result = new PersonJson();

        Map<String, String> fileName = setMainGraphInfo();

        List<Object> arrTotInfo = new ArrayList<Object>();
        arrTotInfo.add(fileName);

        result.setsEcho(Integer.parseInt(Utility.isNullNumber(request.getParameter("sEcho"))));
        result.setAaData(arrTotInfo);

        JSONObject jsonObject = JSONObject.fromObject(result);

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");

        Writer writer = response.getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();

    } catch (Exception e) {
        log.error(e, e);
    }
    log.debug("end - mainGraph.do");
}

From source file:net.cit.tetrad.resource.MainResource.java

@RequestMapping("/totalInfo.do")
public void totalInfo(HttpServletRequest request, HttpServletResponse response) {
    log.debug("start - totalInfo.do");
    try {/*  ww  w .  j av a  2s.  c  o  m*/
        PersonJson result = new PersonJson();
        TotalInfo totInfo = (TotalInfo) monadService.getFind(new Query(), TotalInfo.class);

        List<Object> arrTotInfo = new ArrayList<Object>();
        arrTotInfo.add(totInfo);

        result.setsEcho(Integer.parseInt(Utility.isNullNumber(request.getParameter("sEcho"))));
        result.setiTotalRecords(arrTotInfo.size());
        result.setiTotalDisplayRecords(arrTotInfo.size());
        result.setAaData(arrTotInfo);

        JSONObject jsonObject = JSONObject.fromObject(result);

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");

        Writer writer = response.getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();

    } catch (Exception e) {
        log.error(e, e);
    }
    log.debug("end - totalInfo.do");
}

From source file:com.glaf.jbpm.web.springmvc.MxJbpmCompleteTaskController.java

@RequestMapping
public ModelAndView completeTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug(paramMap);/*from   w w  w  .ja  va  2 s . c  o  m*/
    String json = RequestUtils.getStringValue(request, "json");
    Long processInstanceId = ParamUtils.getLong(paramMap, "processInstanceId");
    Long taskInstanceId = ParamUtils.getLong(paramMap, "taskInstanceId");
    String transitionName = RequestUtils.getStringValue(request, "transitionName");
    String jumpToNode = RequestUtils.getStringValue(request, "jumpToNode");
    String isAgree = RequestUtils.getStringValue(request, "isAgree");
    String opinion = RequestUtils.getStringValue(request, "opinion");
    logger.debug("json:" + json);
    logger.debug("processInstanceId:" + processInstanceId);
    logger.debug("taskInstanceId:" + taskInstanceId);
    logger.debug("transitionName:" + transitionName);
    logger.debug("jumpToNode:" + jumpToNode);
    logger.debug("isAgree:" + isAgree);
    logger.debug("opinion:" + opinion);
    String actorId = RequestUtils.getActorId(request);
    ProcessContainer container = ProcessContainer.getContainer();
    String processName = null;
    boolean canSubmit = false;
    boolean isOK = false;
    TaskItem taskItem = null;
    if ("0".equals(isAgree)) {
        isAgree = "false";
    } else if ("1".equals(isAgree)) {
        isAgree = "true";
    }

    if (taskInstanceId != null && StringUtils.isNotEmpty(actorId)) {
        /**
         * ????
         */
        taskItem = container.getTaskItem(taskInstanceId, actorId);
        if (taskItem != null) {
            if (processInstanceId != null) {
                canSubmit = true;
                processInstanceId = taskItem.getProcessInstanceId();
                processName = taskItem.getProcessName();
            }
        }
    } else if (processInstanceId != null && StringUtils.isNotEmpty(actorId)) {
        /**
         * ?????
         */
        taskItem = container.getMinTaskItem(actorId, processInstanceId);
        if (taskItem != null) {
            canSubmit = true;
            processName = taskItem.getProcessName();
        }
    }

    /**
     * ???
     */
    if (canSubmit && taskItem != null) {
        ProcessContext ctx = new ProcessContext();
        /**
         * ??json?.<br>
         * {money:100000,day:5,pass:true,deptId:"123", roleId:"R001"}
         */
        if (StringUtils.isNotEmpty(json)) {
            Map<String, Object> jsonMap = JsonUtils.decode(json);
            if (jsonMap != null && jsonMap.size() > 0) {
                Set<Entry<String, Object>> entrySet = jsonMap.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    if (name != null && value != null) {
                        DataField dataField = new DataField();
                        dataField.setName(name);
                        dataField.setValue(value);
                        ctx.addDataField(dataField);
                    }
                }
            }
        }

        DataField dataField = new DataField();
        dataField.setName("isAgree");
        dataField.setValue(isAgree);
        ctx.addDataField(dataField);

        ctx.setActorId(actorId);
        ctx.setOpinion(opinion);
        ctx.setProcessInstanceId(taskItem.getProcessInstanceId());
        ctx.setTaskInstanceId(taskItem.getTaskInstanceId());
        ctx.setJumpToNode(jumpToNode);
        ctx.setTransitionName(transitionName);

        try {
            isOK = container.completeTask(ctx);
            request.setAttribute("isOK", Boolean.valueOf(isOK));
            if (isOK) {
                request.setAttribute("statusCode", 200);
                request.setAttribute("message", ViewProperties.getString("res_submit_ok"));
            } else {
                request.setAttribute("statusCode", 500);
                request.setAttribute("message", ViewProperties.getString("res_submit_error"));
            }
        } catch (Exception ex) {
            request.setAttribute("statusCode", 500);
            request.setAttribute("message", ViewProperties.getString("res_submit_error"));
            if (LogUtils.isDebug()) {
                ex.printStackTrace();
                logger.debug(ex);
            }
        }
    }

    String responseDataType = RequestUtils.getStringValue(request, "responseDataType");
    /**
     * ??jsonxml???<br>
     * 200-? <br>
     * 500-<br>
     */
    if (StringUtils.equals(responseDataType, "json")) {
        String encoding = request.getParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/plain;charset=" + encoding);
        Map<String, Object> jsonMap = new java.util.HashMap<String, Object>();
        if (isOK) {
            jsonMap.put("statusCode", 200);
            jsonMap.put("success", "true");
            jsonMap.put("data", ViewProperties.getString("res_submit_ok"));
            jsonMap.put("message", ViewProperties.getString("res_submit_ok"));
        } else {
            jsonMap.put("statusCode", 500);
            jsonMap.put("success", "false");
            jsonMap.put("data", ViewProperties.getString("res_submit_error"));
            jsonMap.put("message", ViewProperties.getString("res_submit_error"));
        }
        JSONObject object = new JSONObject(jsonMap);
        Writer writer = response.getWriter();
        writer.write(object.toString());
        writer.flush();
        writer.close();
        writer = null;
        return null;
    } else if (StringUtils.equals(responseDataType, "xml")) {
        String encoding = request.getParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/xml;charset=" + encoding);
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<response>");
        if (isOK) {
            buffer.append("\n    <statusCode>200</statusCode>");
            buffer.append("\n    <message>").append(ViewProperties.getString("res_submit_ok"))
                    .append("</message>");
        } else {
            buffer.append("\n    <statusCode>500</statusCode>");
            buffer.append("\n    <message>").append(ViewProperties.getString("res_submit_error"))
                    .append("</message>");
        }
        buffer.append("\n</response>");
        Writer writer = response.getWriter();
        writer.write(buffer.toString());
        writer.flush();
        writer.close();
        writer = null;
        return null;
    }

    /**
     * ?????<br>
     * ?????_complete_template??jbpm_complete_template
     * WEB-INF\conf\extension??
     */
    String templateId = RequestUtils.getStringValue(request, "y_templateId");
    if (StringUtils.isEmpty(templateId)) {
        templateId = CustomProperties.getString(processName + "_complete_template");
    }
    if (StringUtils.isEmpty(templateId)) {
        templateId = CustomProperties.getString("jbpm_complete_template");
    }
    if (StringUtils.isNotEmpty(templateId)) {

        Map<String, Object> context = new java.util.HashMap<String, Object>();
        context.putAll(paramMap);
        context.put("actorId", actorId);
        context.put("canSubmit", canSubmit);
        context.put("isOK", isOK);
        context.put("taskItem", taskItem);
        context.put("processInstanceId", processInstanceId);
        context.put("contextPath", request.getContextPath());

        if (isOK) {
            context.put("statusCode", 200);
            context.put("message", ViewProperties.getString("res_submit_ok"));
        } else {
            context.put("statusCode", 500);
            context.put("message", ViewProperties.getString("res_submit_error"));
        }
        try {
            logger.debug(context);
            Writer writer = new StringWriter();
            TemplateUtils.evaluate(templateId, context, writer);
            request.setAttribute("templateScript", writer.toString());
            String encoding = request.getParameter("encoding");
            if (encoding == null) {
                encoding = "UTF-8";
            }
            request.setCharacterEncoding(encoding);
            response.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset=" + encoding);
            response.getWriter().write(writer.toString());
            return null;
        } catch (Exception ex) {
            if (LogUtils.isDebug()) {
                ex.printStackTrace();
                logger.debug(ex);
            }
        }
    }

    String jx_view = request.getParameter("jx_view");

    if (StringUtils.isNotEmpty(jx_view)) {
        return new ModelAndView(jx_view);
    }

    String x_view = ViewProperties.getString("jbpm_complete.complateTask");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view);
    }

    return new ModelAndView("/jbpm/complete");
}

From source file:net.cit.tetrad.resource.MainResource.java

/**
 *  //from ww w  .  ja v a2  s. c  o  m
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping("/alarmList.do")
public void alarmList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.debug("start - alarmList()");
    PersonJson result = new PersonJson();

    Class<?> classname = Alarm.class;
    Query query = new Query();
    CommonDto dto = new CommonDto();
    try {
        dto.setAlarm(Integer.parseInt(request.getParameter("alarm")));
        query = setAlarmSort(dto);
        int cnt = (int) monadService.getCount(query, classname);
        List<Object> resultList = monadService.getList(query.skip(0).limit(5), classname);

        result.setsEcho(Integer.parseInt(request.getParameter("sEcho")));
        result.setiTotalRecords(cnt);
        result.setiTotalDisplayRecords(cnt);
        result.setAaData(resultList);

        JSONObject jsonObject = JSONObject.fromObject(result);

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");

        Writer writer = response.getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();

    } catch (Exception e) {
        log.error(e, e);
    }
    log.debug("end - alarmList()");
}

From source file:gov.va.vinci.chartreview.util.CRSchemaXML.java

private void finalizeRender(Writer out) {
    try {//  w  w  w. j  a  v a2  s  .  c  o m
        if (out != null) {
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        log.warn("Unexpected exception while closing a writer: " + e.getMessage());
    }
}

From source file:com.evolveum.midpoint.cli.ninja.action.ExportAction.java

@Override
protected void executeAction() throws Exception {
    ModelPortType port = createModelPort();

    Writer writer = null;
    try {//w  ww  . j a  v a  2  s.c om
        writer = createWriter();
        writeHeader(writer);

        if (StringUtils.isNotEmpty(getParams().getOid())) {
            //get
            executeGet(port, writer);
        } else {
            //search
            executeSearch(port, writer);
        }

        writeFooter(writer);
        writer.flush();
    } catch (SAXException | JAXBException | IOException | FaultMessage ex) {
        handleError("Couldn't export objects", ex);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}