Example usage for javax.servlet.http HttpServletResponse setCharacterEncoding

List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setCharacterEncoding.

Prototype

public void setCharacterEncoding(String charset);

Source Link

Document

Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

Usage

From source file:com.momoplan.pet.framework.manager.controller.GetServerController.java

@RequestMapping("/best.html")
public void best(String license, HttpServletResponse response) throws Exception {
    long s = System.currentTimeMillis();
    response.setCharacterEncoding("UTF-8");
    String license_key = "license:" + license;
    logger.debug("license_key=" + license_key);
    //TODO check license
    String license_info = Config.publicConfig.get(license_key);
    logger.debug("license_info=" + license_info);
    logger.debug("nodeServiceUrl=" + nodeServiceUrl);
    URL u = new URL(nodeServiceUrl);
    URLConnection conn = u.openConnection();
    InputStream is = conn.getInputStream();
    byte[] buff = new byte[4096];
    int t = 0;//from www . j a  va 2  s.  c  o m
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((t = is.read(buff)) != -1) {
        bos.write(buff, 0, t);
    }
    String nodes = new String(bos.toByteArray());
    is.close();
    bos.close();

    JSONObject json = new JSONObject(nodes);
    boolean success = json.getBoolean("success");

    JSONObject rtnJson = new JSONObject();
    rtnJson.put("success", success);
    if (success) {
        try {
            JSONArray arr = json.getJSONArray("entity");
            int len = arr.length();
            Map<String, Object> tmp = new HashMap<String, Object>();
            tmp.put("node", "");
            tmp.put("totalCount", Integer.MAX_VALUE);
            for (int i = 0; i < len; i++) {
                JSONObject node = arr.getJSONObject(i);
                Integer c = node.getInt("totalCount");
                if (c < (Integer) tmp.get("totalCount")) {
                    tmp.put("node", node.getString("node"));
                    tmp.put("totalCount", c);
                }
            }
            logger.debug(tmp.toString());
            String nodeKey = (String) tmp.get("node");
            String ipHost = Config.publicConfig.get(nodeKey);
            String[] hostArr = ipHost.split(":");
            JSONObject entity = new JSONObject();
            entity.put("ip", hostArr[0]);
            entity.put("port", hostArr[1]);
            rtnJson.put("entity", entity);
        } catch (Exception e) {
            logger.error("XXXXXX", e);
            rtnJson.put("entity", defNode);
        }
    } else {
        rtnJson.put("entity", json.get("entity"));
    }
    logger.debug(nodes);
    long e = System.currentTimeMillis();
    logger.info("license_key=" + license_key + ";license_info=" + license_info + ";rtn=" + rtnJson.toString()
            + " -- " + (e - s) + "ms");
    response.getWriter().write(rtnJson.toString());
}

From source file:cn.vlabs.clb.server.ui.frameservice.document.handler.GetDocContentHandler.java

private void writeFileContentToResponse(GridFSDBFile dbfile, HttpServletRequest request,
        HttpServletResponse response) {
    OutputStream os = null;/*from w  ww  .j a va  2  s  .c om*/
    try {
        long start = System.currentTimeMillis();
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) dbfile.getLength());
        response.setContentType("application/x-download");
        String filename = dbfile.getFilename();
        if (filename == null) {
            filename = "file" + dbfile.getId();
        }
        LOG.debug(dbfile.getFilename() + "," + dbfile.getLength());
        String headerValue = ResponseHeaderUtils.buildResponseHeader(request, filename, true);
        response.setHeader("Content-Disposition", headerValue);
        response.setHeader("Content-Length", dbfile.getLength() + "");
        os = response.getOutputStream();
        dbfile.writeTo(os);
        long end = System.currentTimeMillis();
        LOG.info("Read doc content using stream mode for doc [" + filename + "], use time " + (end - start)
                + "ms");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * Writes a response to the client.//from ww  w.  j  av  a2 s. c  o  m
 */
protected static void renderMessage(HttpServletResponse response, String message, String contentType)
        throws IOException {
    response.addHeader("Cache-Control", "no-cache");
    response.setContentType(contentType + "; charset=GB2312");
    response.setCharacterEncoding("GB2312");
    PrintWriter out = response.getWriter();
    out.print(message);

    System.out.println("=======>" + message);
    out.flush();
    out.close();
}

From source file:net.acesinc.convergentui.BaseFilter.java

protected void writeResponse(String responseBody, MimeType contentType) throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (responseBody == null || responseBody.isEmpty()) {
        return;//from w  w w.  j av  a 2 s. c om
    }
    HttpServletResponse servletResponse = context.getResponse();
    servletResponse.setCharacterEncoding("UTF-8");
    servletResponse.setContentType(contentType.toString());
    OutputStream outStream = servletResponse.getOutputStream();
    InputStream is = null;
    try {
        writeResponse(new ByteArrayInputStream(responseBody.getBytes()), outStream);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
        }
    }
}

From source file:com.flaptor.indextank.api.resources.Autocomplete.java

/**
 * @see java.lang.Runnable#run()//w  w w  . ja  v  a 2  s  . c o  m
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    HttpServletResponse res = res();

    String characterEncoding = api.getCharacterEncoding();
    try {
        req().setCharacterEncoding(characterEncoding);
        res.setCharacterEncoding(characterEncoding);
        res.setContentType("application/json");
    } catch (UnsupportedEncodingException ignored) {
    }

    String query = params("query");
    String field = params("field");
    String callback = params("callback");

    if (field == null || field.isEmpty()) {
        field = "text";
    }

    List<String> complete = api.complete(query, field);

    JSONObject json = new JSONObject();
    json.put("query", query);
    json.put("suggestions", complete);

    if (callback != null && !callback.trim().isEmpty()) {
        print(callback.trim() + "(" + json.toJSONString() + ")");
    } else {
        print(json.toJSONString());
    }

}

From source file:com.kysoft.cpsi.audit.controller.SelfCheckAjaxUploadController.java

/**
 * //from w  ww.jav  a2  s . c om
 * @param response
 * @param state
 */
@SuppressWarnings("unused")
private void responseMessage(HttpServletResponse response, State state) {
    response.setCharacterEncoding(HuskyConstants.ENCODING_UTF8);
    response.setContentType("text/html; charset=UTF-8");
    Writer writer = null;
    try {
        writer = response.getWriter();
        writer.write("{\"code\":" + state.getCode() + ",\"message\":\"" + state.getMessage() + "\"}");
        writer.flush();
        writer.close();
    } catch (Exception e) {
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:no.dusken.barweb.view.InvoiceView.java

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    response.setContentType("application/pdf");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=faktura.pdf");

    Map<BarPerson, Integer> persons = (Map<BarPerson, Integer>) model.get("persons");
    Gjeng g = (Gjeng) model.get("gjeng");
    Invoice invoice = (Invoice) model.get("invoice");
    //Setup FOP/*from w  w  w . ja v  a2 s  .  co  m*/
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, response.getOutputStream());

    //Setup Transformer
    Source xsltSrc = new StreamSource(
            this.getClass().getResourceAsStream("/no/dusken/barweb/stylesheets/" + styleSheet));
    Transformer transformer = tFactory.newTransformer(xsltSrc);

    //Make sure the XSL transformation's result is piped through to FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    //Setup input
    DOMSource src = new DOMSource(generateXml(persons, g, invoice));

    //Start the transformation and rendering process
    transformer.transform(src, res);
    response.getOutputStream().flush();

}

From source file:no.dusken.barweb.view.XListView.java

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    response.setContentType("application/pdf");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=xlist.pdf");

    List<BarPerson> barPersons = (List<BarPerson>) model.get("barPersons");
    Gjeng g = (Gjeng) model.get("gjeng");
    List<Vare> varer = (List<Vare>) model.get("varer");
    Integer lowlimit = (Integer) model.get("lowLimit");
    Boolean panger = (Boolean) model.get("panger");
    //Setup FOP/*from www  .  j  av  a 2 s  .  c  om*/
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, response.getOutputStream());

    //Setup Transformer
    Source xsltSrc = new StreamSource(
            this.getClass().getResourceAsStream("/no/dusken/barweb/stylesheets/" + styleSheet));
    Transformer transformer = tFactory.newTransformer(xsltSrc);

    //Make sure the XSL transformation's result is piped through to FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    //Setup input
    DOMSource src = new DOMSource(generateXml(barPersons, g, varer, lowlimit, panger));

    //Start the transformation and rendering process
    transformer.transform(src, res);
    response.getOutputStream().flush();

}

From source file:de.mpg.escidoc.services.aa.web.AaStart.java

/**
 * This servlet is expecting 2 parameters:
 * /* ww  w .j  a va 2 s.  c om*/
 * - tan: A random string generated by the client system to check whether the result is valid or not.
 * - target: The URL the user should be redirected to after authentication.
 * 
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding(DEFAULT_ENCODING);
    response.setCharacterEncoding(DEFAULT_ENCODING);

    String from = request.getParameter("from");
    String tan = request.getParameter("tan");

    // TODO: Make this generic
    String handle = request.getParameter("eSciDocUserHandle");

    Matcher matcher = authPattern.matcher(from);
    from = matcher.replaceAll("");

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

    if (target == null) {
        target = Config.getProperty("escidoc.aa.default.target");
    }

    String separator = "?";
    if (target.contains("?")) {
        separator = "&";
    }
    target += separator + "target=" + URLEncoder.encode(from, "ISO-8859-1") + "&tan="
            + URLEncoder.encode(tan, "ISO-8859-1");

    if (handle != null) {
        target += "&eSciDocUserHandle=" + URLEncoder.encode(handle, "ISO-8859-1");
    }

    response.sendRedirect(target);

}

From source file:com.mirth.connect.server.servlets.ChannelStatusServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {/*from w ww  .j  a v a2s .  c o m*/
        try {
            ChannelStatusController channelStatusController = ControllerFactory.getFactory()
                    .createChannelStatusController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String channelId = request.getParameter("id");
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            parameterMap.put("channelId", channelId);

            if (operation.equals(Operations.CHANNEL_START)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.startChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_STOP)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.stopChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_PAUSE)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.pauseChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_RESUME)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.resumeChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_GET_STATUS)) {
                response.setContentType(APPLICATION_XML);
                List<ChannelStatus> channelStatuses = null;

                if (!isUserAuthorized(request, null)) {
                    channelStatuses = new ArrayList<ChannelStatus>();
                } else if (doesUserHaveChannelRestrictions(request)) {
                    channelStatuses = redactChannelStatuses(request,
                            channelStatusController.getChannelStatusList());
                } else {
                    channelStatuses = channelStatusController.getChannelStatusList();
                }

                serializer.toXML(channelStatuses, out);
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}