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:net.cloudfree.apps.shop.internal.app.JsonListingServlet.java

/**
 * Prints a help text.//from   ww w.ja v a 2  s  .  co m
 * 
 * @param req
 * @param resp
 * @throws IOException
 */
private void doHelp(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    final PrintWriter writer = resp.getWriter();
    writer.println("JSON Servlet Usage");
    writer.println("==================");
    writer.println();
    writer.print("    Retrieve all products: ");
    writer.println(getBaseUrl(req));
    writer.print("Retrieve a single product: ");
    writer.println(getBaseUrl(req).append("<uripath>"));
    writer.print("                       or: ");
    writer.println(getBaseUrl(req).append(ID_PATH_PREFIX.substring(1)).append("<id>"));
    writer.println();
    writer.println();
    writer.println("Search/Guided Navigation Parameters");
    writer.println("-----------------------------------");
    writer.println();
    writer.println("q ... the query string");
    writer.println("      (see JavaDoc of org.eclipse.gyrex.cds.service.query.ListingQuery#setQuery(String))");
    writer.println("f ... a filter query (multiple possible, will be interpreted as AND; ..&f=..&f=..)");
    writer.println("      (eg. the facet 'filter' attribute from the result set)");
    writer.println(
            "c ... easy retrieval of a category (multiple possible, will be interpreted as AND; ..&c=shirts&c=underwear)");
    writer.println(
            "      (to filter for categories using OR use a filter \"..&f=+category:(shirts underwear)\")");
    writer.println("s ... start index (zero-based, used for paging)");
    writer.println("r ... rows to return (defaults to 10, used for paging)");
    writer.println(
            "t ... easy retrieval of a tag (multiple possible, will be interpreted as AND; ..&t=shirts&t=cool)");
    writer.println("      (to filter for tags using OR use a filter \"..&f=+tags:(shirts cool)\")");
    writer.println();
    writer.println();
    writer.println("Variations");
    writer.println("----------");
    writer.println();
    writer.println(
            "To keep things simple, variations are not searched by default. They should only be relevant");
    writer.println("on product details pages. Thus, they are available in the product details information.");
    writer.println();
    writer.println();
    writer.println("Debug Parameters");
    writer.println("----------------");
    writer.println();
    writer.println("help ... print this help text");
    writer.println("text ... send response as plain/text");
    writer.flush();
}

From source file:net.mindengine.oculus.frontend.web.controllers.project.TestJFreeController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    DefaultPieDataset pieDataset = new DefaultPieDataset();
    pieDataset.setValue("A", new Integer(75));
    pieDataset.setValue("B", new Integer(10));
    pieDataset.setValue("C", new Integer(10));
    pieDataset.setValue("D", new Integer(5));

    JFreeChart chart = ChartFactory.createPieChart("CSC408 Mark Distribution", // Title
            pieDataset, // Dataset
            true, // Show legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );// ww w . ja  v  a 2 s .c o m

    response.setCharacterEncoding("image/jpeg");
    response.setStatus(200);
    ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 500, 400);
    return null;
}

From source file:com.wx.CoacherWXServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  ww  w .j  a  va  2 s . c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sToken = "testToken1";
    String sCorpID = "wxe706b25abb1216c0";
    String sEncodingAESKey = "R5zQRNXirEIQsSGL5Hs5ydZdSuu7EkRLWLViul1P7si";
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    String msg_signature = request.getParameter("msg_signature");
    String timestamp = request.getParameter("timestamp");
    String nonce = request.getParameter("nonce");
    InputStream inputStream = request.getInputStream();
    String postData = IOUtils.toString(inputStream, "UTF-8");
    System.out.println(postData);
    String msg = "";
    WXBizMsgCrypt wxcpt = null;
    try {
        wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        //?
        msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData);
    } catch (AesException e) {
        e.printStackTrace();
    }
    System.out.println("msg=" + msg);
    BaseMessage respMessage = CoreService.processRequest(msg, classService);
    String resMsg = null;
    /** if (request.getSession().getAttribute("accessToken") == null) {
    try {
        String accessToken = CoreService.getAccessToken(config.getInitParameter("corpid"), config.getInitParameter("corpsecret"));
        request.getSession().setAttribute("accessToken", accessToken);
        QyWxURLUtil.applyAccessToken(accessToken);
    } catch (Exception ex) {
        Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
     }
     **/
    /**
     * UploadMediaReturnMessage uploadMediaReturnMsg; try {
     * uploadMediaReturnMsg = WXUtils.send("image",
     * "/root/WXMedia/anranhui520/1.jpg");
     * if("null".equals(uploadMediaReturnMsg.getErrcode())){
     * System.out.println("Media_id:"+uploadMediaReturnMsg.getMedia_id());
     * }else{ System.out.println("Upload error
     * message:"+uploadMediaReturnMsg.getErrmsg()+" error
     * code:"+uploadMediaReturnMsg.getErrcode());
     *
     * }
     * } catch (Exception ex) {
     * Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE,
     * null, ex); }
    *
     */
    if (respMessage instanceof TextMessage) {
        /*try {
        TextMessage txtMsg = (TextMessage) respMessage;
                
        String command = txtMsg.getContent();
                
        CheckCommandReturnMessage ccReturnMsg = CMDService.processCheckingCommand(command);
        Set<UserInfo> userInfoSet = ccReturnMsg.getUserInfos();
        UserInfo userif = null;
        for (UserInfo userInfo : userInfoSet) {
            userif = userInfo;
        }
                
        System.out.println("msgContent:" + ccReturnMsg.getContent());
        System.out.println("weixinid:" + userif.getWeixinid());
                
        try {
                
            UploadMediaReturnMessage uploadMediaReturnMsg = null;
            try {
                QRCodeGenerator.encode(ccReturnMsg.getContent(), "/root/WXMedia/"+userif.getWeixinid());
                        
                uploadMediaReturnMsg = WXUtils.send("image", "/root/WXMedia/"+userif.getWeixinid()+"/qrcode.jpg");
                if ("null".equals(uploadMediaReturnMsg.getErrcode())) {
                    System.out.println("Media_id:" + uploadMediaReturnMsg.getMedia_id());
                } else {
                    System.out.println("Upload error message:" + uploadMediaReturnMsg.getErrmsg() + " error code:" + uploadMediaReturnMsg.getErrcode());
                
                }
            } catch (Exception ex) {
                Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
            }*/

        /**
         * TextSendMessage textMsg = new TextSendMessage(); String
         * msgtxt = ccReturnMsg.getContent();
         * textMsg.setTextContent(msgtxt);
         * textMsg.setMsgtype("text");
         * textMsg.setTouser(userif.getWeixinid());
         * textMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); *
         */
        /*  ImageSendMessage imgMsg = new ImageSendMessage();
          imgMsg.setImageMedia(uploadMediaReturnMsg.getMedia_id());
          imgMsg.setMsgtype("image");
          imgMsg.setTouser(userif.getWeixinid());
          imgMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId")));
                
          AccessTokenReturnMessage returnMsg = CoreService.sendMessage(imgMsg);
        } catch (Exception ex) {
          Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        } catch (Exception ex) {
        Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    } else if (respMessage instanceof NewsMessage) {
        System.out.println("enter NewsMessage.");
        NewsMessage newsMsg = (NewsMessage) respMessage;
        resMsg = MessageUtil.newsMessageToXml(newsMsg);
        System.out.println("ResMsg:" + resMsg);
    }
    PrintWriter out = response.getWriter();
    out.print(resMsg);
    out.flush();
    out.close();
}

From source file:org.motechproject.server.outbox.web.VxmlOutboxController.java

/**
 * Handles Outbox HTTP requests and generates a VXML document based on a Velocity template and data saved in the outbox.
 * <p/>//from w w w  .jav a 2  s.  co m
 * <p/>
 * URL to request a saved VoiceXML message from outbox :
 * http://<host>:<port>/<motech-platform-server>/module/outbox/vxml/savedMessage>
 */
public ModelAndView savedMessage(HttpServletRequest request, HttpServletResponse response) {
    logger.info("Generate VXML for the next saved in the outbox message");

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    //Interim implementation. Party ID will be obtained from the Authentication context
    //String partyId = "1";
    String partyId = request.getParameter("pId");

    String language = request.getParameter(LANGUAGE_PARAM);

    String contextPath = request.getContextPath();

    ModelAndView mav = new ModelAndView();
    mav.addObject("contextPath", contextPath);
    mav.addObject("language", language);
    mav.addObject("escape", new StringEscapeUtils());

    logger.debug("Party ID: " + partyId);

    OutboundVoiceMessage voiceMessage = null;

    logger.info("Generating VXML for the next saved voice message in outbox... ");
    try {
        voiceMessage = voiceOutboxService.getNextSavedMessage(partyId);
    } catch (Exception e) {
        logger.error("Can not obtain next saved message from the outbox of the party ID: " + partyId + " "
                + e.getMessage(), e);
        logger.warn("Generating a VXML with the error message...");
        mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
        return mav;
    }

    if (voiceMessage == null) {

        logger.info("There are no more messages in the outbox of the party ID: " + partyId);
        mav.setViewName(NO_SAVED_MESSAGE_TEMPLATE_NAME);
        mav.addObject("partyId", partyId);
        return mav;
    }

    VoiceMessageType voiceMessageType = voiceMessage.getVoiceMessageType();

    if (voiceMessageType == null) {
        logger.error(
                "Invalid Outbound voice message: " + voiceMessage + " Voice message type can not be null.");
        mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
        mav.addObject("partyId", partyId);
        return mav;
    }

    String templateName = voiceMessageType.getTemplateName();
    if (templateName == null) {
        templateName = voiceMessageType.getVoiceMessageTypeName();
    }

    mav.setViewName(templateName);
    mav.addObject("message", voiceMessage);

    return mav;

}

From source file:net.mindengine.oculus.frontend.web.controllers.SimpleAjaxController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    AjaxModel model = null;//w  ww  .ja  v a2  s . co  m
    try {
        model = handleController(request);
        if (model == null)
            throw new Exception("The controller returned null model");
    } catch (Exception ex) {
        logger.error(ex, ex);
        model = new AjaxModel(ex);
    }

    OutputStream os = response.getOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(os);
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");

    JSONValue jsonValue = JSONMapper.toJSON(model);
    w.write(jsonValue.render(true));

    w.flush();
    os.flush();
    os.close();

    return null;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.json.JsonObjectProducer.java

public final void process(HttpServletResponse resp) throws IOException {
    JSONObject jsonObject = null;//from  w w  w.  j  av a 2s  .com
    String errorMessage = "";

    try {
        jsonObject = process();
    } catch (Exception e) {
        log.error("Failed to create JSON response", e);
        errorMessage = e.toString();
        resp.setStatus(500 /* HttpURLConnection.HTTP_SERVER_ERROR */);
    }

    if (jsonObject == null) {
        jsonObject = new JSONObject();
    }

    log.debug("Response to JSON request: " + jsonObject.toString());

    try {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        Writer writer = resp.getWriter();

        jsonObject.put("errorMessage", errorMessage);
        writer.write(jsonObject.toString());
    } catch (JSONException e) {
        log.error(e, e);
    }
}

From source file:seava.j4e.web.controller.ui.extjs.UiExtjsFrameController.java

/**
 * Handler to return the cached js file with the dependent translations.
 * //from  w w  w.j av a2 s. c  o  m
 * @param bundle
 * @param frame
 * @param language
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{bundle}/{language}/{frame}.js", method = RequestMethod.GET)
@ResponseBody
public String frameTrlJs(@PathVariable("bundle") String bundle, @PathVariable("frame") String frame,
        @PathVariable("language") String language, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    try {
        @SuppressWarnings("unused")
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } catch (java.lang.ClassCastException e) {
        throw new NotAuthorizedRequestException("Not authenticated");
    }

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    String fileName = frame + "-" + language + ".js";
    File f = new File(this.cacheFolder + "/" + bundle + "." + fileName);
    if (!f.exists()) {
        DependencyLoader loader = this.getDependencyLoader(request);
        loader.packFrameTrl(bundle, frame, language, f);
    }

    this.sendFile(f, response.getOutputStream());
    return null;
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationResponseServlet.java

@SuppressWarnings("unchecked")
private void doIdRes(HttpServletRequest request, HttpServletResponse response)
        throws MessageException, DiscoveryException, AssociationException, IOException, ServletException {
    LOG.debug("id_res");
    LOG.debug("request URL: " + request.getRequestURL());

    // force UTF-8 encoding
    try {/*from  w  w w. ja va 2  s .c  o  m*/
        request.setCharacterEncoding("UTF8");
        response.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new MessageException(e);
    }

    ParameterList parameterList = new ParameterList(request.getParameterMap());
    DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request URI: " + request.getRequestURI());
    String receivingUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort()
            + request.getRequestURI();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        receivingUrl += "?" + queryString;
    }
    LOG.debug("receiving url: " + receivingUrl);
    ConsumerManager consumerManager = AuthenticationRequestServlet.getConsumerManager(request);
    VerificationResult verificationResult = consumerManager.verify(receivingUrl, parameterList, discovered);
    Identifier identifier = verificationResult.getVerifiedId();
    if (null != identifier) {

        Date authenticationTime = null;
        String userId = identifier.getIdentifier();
        List<String> authnPolicies = new LinkedList<String>();
        Map<String, Object> attributeMap = new HashMap<String, Object>();
        LOG.debug("userId: " + userId);
        Message authResponse = verificationResult.getAuthResponse();

        // verify return_to nonce
        AuthSuccess authResp = AuthSuccess.createAuthSuccess(parameterList);

        String returnTo = authResp.getReturnTo();
        String requestReturnTo = (String) request.getSession()
                .getAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);
        if (null == returnTo || null == requestReturnTo) {
            showErrorPage("Insufficient args for validation of " + " \"openid.return_to\".", null, request,
                    response);
            return;
        }
        if (!consumerManager.verifyReturnTo(requestReturnTo, authResp)) {
            showErrorPage("Invalid \"return_to\" in response!", null, request, response);
            return;
        }
        // cleanup
        request.getSession().removeAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);

        // AX
        if (authResponse.hasExtension(AxMessage.OPENID_NS_AX)) {

            MessageExtension messageExtension = authResponse.getExtension(AxMessage.OPENID_NS_AX);
            if (messageExtension instanceof FetchResponse) {

                FetchResponse fetchResponse = (FetchResponse) messageExtension;

                Map<String, String> attributeTypes = fetchResponse.getAttributeTypes();
                for (Map.Entry<String, String> entry : attributeTypes.entrySet()) {
                    attributeMap.put(entry.getValue(), fetchResponse.getAttributeValue(entry.getKey()));
                }

            }

        }

        // PAPE
        if (authResponse.hasExtension(PapeResponse.OPENID_NS_PAPE)) {

            MessageExtension messageExtension = authResponse.getExtension(PapeResponse.OPENID_NS_PAPE);
            if (messageExtension instanceof PapeResponse) {

                PapeResponse papeResponse = (PapeResponse) messageExtension;

                authnPolicies = papeResponse.getAuthPoliciesList();
                authenticationTime = papeResponse.getAuthDate();

            }
        }

        OpenIDAuthenticationResponse openIDAuthenticationResponse = new OpenIDAuthenticationResponse(
                authenticationTime, userId, authnPolicies, attributeMap);
        request.getSession().setAttribute(this.responseSessionAttribute, openIDAuthenticationResponse);

        response.sendRedirect(request.getContextPath() + this.redirectPage);
    } else {
        showErrorPage("No verified identifier", null, request, response);
    }
}

From source file:cc.kune.core.server.rack.filters.rest.CORSServiceFilter.java

@Override
protected void customDoFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    final boolean cors = (Boolean) request.getAttribute("cors.isCorsRequest");

    // This part is similar to RESTServiceFilter
    final String methodName = RackHelper.getMethodName(request, pattern);
    final ParametersAdapter parameters = new ParametersAdapter(request);
    LOG.debug((cors ? "" : "NO ") + "CORS METHOD: '" + methodName + "' on: " + serviceClass.getSimpleName());

    response.setCharacterEncoding("utf-8");

    // See: http://software.dzhuvinov.com/cors-filter-tips.html
    response.setContentType("text/plain");

    final RESTResult result = transactionalFilter.doService(serviceClass, methodName, parameters,
            getInstance(serviceClass));//from ww  w. j  ava2  s .co  m
    if (result != null) {
        final Exception exception = result.getException();
        if (exception != null) {
            if (exception instanceof InvocationTargetException && ((InvocationTargetException) exception)
                    .getTargetException() instanceof ContentNotFoundException) {
                printMessage(response, HttpServletResponse.SC_NOT_FOUND, result.getException().getMessage());
            } else {
                printMessage(response, HttpServletResponse.SC_BAD_REQUEST, result.getException().getMessage());
            }
        } else {
            final String output = result.getOutput();
            if (output != null) {
                final PrintWriter writer = response.getWriter();
                writer.print(output);
                writer.flush();
            } else {
                // Is not for us!!!
            }
        }
    }
}

From source file:org.motechproject.server.outbox.web.VxmlOutboxController.java

/**
 * Handles Appointment Reminder HTTP requests and generates a VXML document based on a Velocity template.
 * The HTTP request may contain an optional 'mId' parameter with value of ID of the message for which
 * VXML document will be generated. If the "mId" parameter is not passed the next pending voice message
 * will be obtained from the outbox and a VXML document will be generated for that message
 * <p/>/*from   www.j a  va 2 s  . c  om*/
 * <p/>
 * URL to request appointment reminder VoiceXML:
 * http://<host>:<port>/<motech-platform-server>/module/outbox/vxml/outboxMessage?mId=<messageId>
 */
public ModelAndView outboxMessage(HttpServletRequest request, HttpServletResponse response) {
    logger.info("Generate appointment reminder VXML");

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    //Interim implementation. Party ID will be obtained from the Authentication context
    //String partyId = "1";
    String partyId = request.getParameter("pId");

    String messageId = request.getParameter(MESSAGE_ID_PARAM);
    String language = request.getParameter(LANGUAGE_PARAM);

    if (language == null) {
        language = "en";
    }

    String contextPath = request.getContextPath();

    ModelAndView mav = new ModelAndView();
    mav.addObject("contextPath", contextPath);
    mav.addObject("language", language);
    mav.addObject("escape", new StringEscapeUtils());

    logger.debug("Message ID: " + messageId);

    OutboundVoiceMessage voiceMessage = null;

    if (messageId != null) {
        logger.info("Generating VXML for the voice message ID: " + messageId);

        try {
            voiceMessage = voiceOutboxService.getMessageById(messageId);
        } catch (Exception e) {
            logger.error("Can not get message by ID: " + messageId + " " + e.getMessage(), e);
            logger.warn("Generating a VXML with the error message...");
            mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
            return mav;
        }
    } else {
        logger.info("Generating VXML for the next voice message in outbox... ");
        try {
            voiceMessage = voiceOutboxService.getNextPendingMessage(partyId);
        } catch (Exception e) {
            logger.error("Can not obtain next message from the outbox of the party ID: " + partyId + " "
                    + e.getMessage(), e);
            logger.warn("Generating a VXML with the error message...");
            mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
            return mav;
        }
    }

    if (voiceMessage == null) {

        logger.info("There are no more messages in the outbox of the party ID: " + partyId);
        mav.setViewName(NO_MESSAGE_TEMPLATE_NAME);
        mav.addObject("partyId", partyId);
        return mav;
    }

    VoiceMessageType voiceMessageType = voiceMessage.getVoiceMessageType();

    if (voiceMessageType == null) {
        logger.error(
                "Invalid Outbound voice message: " + voiceMessage + " Voice message type can not be null.");
        mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
        mav.addObject("partyId", partyId);
        return mav;
    }

    logger.debug(voiceMessage.toString());

    String templateName = voiceMessageType.getTemplateName();
    if (templateName == null) {
        templateName = voiceMessageType.getVoiceMessageTypeName();
    }

    mav.setViewName(templateName);
    mav.addObject("message", voiceMessage);

    try {
        //Pending message should then be "PLAYED"
        voiceOutboxService.setMessageStatus(voiceMessage.getId(), OutboundVoiceMessageStatus.PLAYED);
    } catch (Exception e) {
        logger.error("Can not mark the message with ID: " + messageId + " as PLAYED in the outbox", e);
        mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
        return mav;
    }

    return mav;

}