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:de.ingrid.server.opensearch.servlet.OpensearchServerServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///  w ww . j  ava2 s . c o m
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    IngridHits hits = null;
    long overallStartTime = 0;

    if (log.isDebugEnabled()) {
        overallStartTime = System.currentTimeMillis();
    }

    final RequestWrapper reqWrapper = new RequestWrapper(request);

    // set content Type
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");

    OSSearcher osSearcher = OSSearcher.getInstance();

    if (osSearcher == null) {
        // redirect or show error page or empty result
        final PrintWriter pout = response.getWriter();
        pout.write("Error: no index file found");
        return;
    }

    int page = reqWrapper.getRequestedPage();
    final int hitsPerPage = reqWrapper.getHitsPerPage();
    if (page <= 0) {
        page = 1;
    }
    final int startHit = (page - 1) * hitsPerPage;

    try {
        // Hits also need Details which has title and summary!!!
        hits = osSearcher.searchAndDetails(reqWrapper.getQuery(), startHit, reqWrapper.getHitsPerPage());
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // transform hits into target format
    final OpensearchMapper mapper = (new SpringUtil("spring/spring.xml")).getBean("mapper",
            OpensearchMapper.class);
    final HashMap<String, Object> parameter = new HashMap<String, Object>();
    parameter.put(OpensearchMapper.REQUEST_WRAPPER, reqWrapper);

    final Document doc = mapper.mapToXML(hits, parameter);

    // write target format
    final PrintWriter pout = response.getWriter();

    pout.write(doc.asXML());
    pout.close();
    request.getInputStream().close();
    doc.clearContent();

    if (log.isDebugEnabled()) {
        log.debug("Time for complete search: " + (System.currentTimeMillis() - overallStartTime) + " ms");
    }
}

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

public ModelAndView messageMenu(HttpServletRequest request, HttpServletResponse response) {
    logger.info("Generating the message menu VXML...");

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

    ModelAndView mav = new ModelAndView();

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

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

    if (messageId == null) {
        logger.error("Invalid request - missing parameter: " + MESSAGE_ID_PARAM);
        mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
        return mav;
    }/*  ww  w. ja v  a  2 s  .  c  om*/

    OutboundVoiceMessage voiceMessage;

    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;
    }

    if (voiceMessage == null) {

        logger.error("Can not get message by ID: " + messageId + "service returned null");
        logger.warn("Generating a VXML with the error message...");
        mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME);
        return mav;
    }

    if (voiceMessage.getStatus() == OutboundVoiceMessageStatus.SAVED) {

        mav.setViewName(SAVED_MESSAGE_MENU_TEMPLATE_NAME);
    } else {
        try {
            voiceOutboxService.setMessageStatus(messageId, OutboundVoiceMessageStatus.PLAYED);
        } catch (Exception e) {
            logger.error("Can not set message status to " + OutboundVoiceMessageStatus.PLAYED
                    + " to the message ID: " + messageId, e);
        }
        mav.setViewName(MESSAGE_MENU_TEMPLATE_NAME);
    }

    String contextPath = request.getContextPath();

    logger.debug(voiceMessage.toString());
    logger.debug(mav.getViewName());

    mav.addObject("contextPath", contextPath);
    mav.addObject("message", voiceMessage);
    mav.addObject("language", language);
    mav.addObject("escape", new StringEscapeUtils());
    return mav;

}

From source file:com.cognifide.aet.executor.SuiteStatusServlet.java

/**
 * Returns JSON with suite status defined by {@link SuiteStatusResult} for a given correlation ID.
 *
 * @param request/*from   ww w.j a  va2 s  .c o m*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String correlationId = StringUtils.substringAfter(request.getRequestURI(), SERVLET_PATH).replace("/", "");
    SuiteStatusResult suiteStatusResult = suiteExecutor.getExecutionStatus(correlationId);

    if (suiteStatusResult != null) {
        Gson gson = new Gson();
        String responseBody = gson.toJson(suiteStatusResult);

        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(responseBody);
    } else {
        response.sendError(404, "Suite status not found");
    }
}

From source file:com.amalto.core.servlet.LogViewerServlet.java

private void writeLogFileChunk(long position, int maxLines, HttpServletResponse response) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

    FileChunkLoader loader = new FileChunkLoader(file);
    FileChunkInfo chunkInfo = loader.loadChunkTo(bufferedOutputStream, position, maxLines);
    bufferedOutputStream.close();/*  w  w w  .j  a v a  2s . c  om*/

    response.setContentType("text/plain;charset=" + charset); //$NON-NLS-1$
    response.setCharacterEncoding(charset);
    response.setHeader("X-Log-Position", String.valueOf(chunkInfo.nextPosition)); //$NON-NLS-1$
    response.setHeader("X-Log-Lines", String.valueOf(chunkInfo.lines)); //$NON-NLS-1$

    OutputStream responseOutputStream = response.getOutputStream();
    outputStream.writeTo(responseOutputStream);
    responseOutputStream.close();
}

From source file:ai.susi.server.api.cms.Sitemap.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);
    // String siteurl = request.getRequestURL().toString();
    // String baseurl = siteurl.substring(0, siteurl.length() -
    // request.getRequestURI().length()) + request.getContextPath() + "/";
    String baseurl = "http://loklak.org/";
    JSONObject TopMenuJsonObject = new TopMenuService().serviceImpl(post, null, null, null);
    JSONArray sitesarr = TopMenuJsonObject.getJSONArray("items");
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    sos.print(sitemaphead + "\n");
    for (int i = 0; i < sitesarr.length(); i++) {
        JSONObject sitesobj = sitesarr.getJSONObject(i);
        Iterator<String> sites = sitesobj.keys();
        sos.print("<url>\n<loc>" + baseurl + sitesobj.getString(sites.next().toString()) + "/</loc>\n"
                + "<changefreq>weekly</changefreq>\n</url>\n");
    }// ww  w  .j ava  2 s.  co  m
    sos.print("</urlset>");
    sos.println();
    post.finalize();
}

From source file:mercury.JsonController.java

/**
 *
 *//*from  ww  w . ja  v  a2 s.  co  m*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    this.log.debug("processRequest start: " + this.getMemoryInfo());

    String submitButton = null;
    String thisPage = null;
    HttpSession session = request.getSession();
    JSONObject jsonResponse = null;
    Integer status = null;

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

    try {
        submitButton = request.getParameter("submitButton");
        thisPage = request.getParameter("thisPage");

        AuthorizationPoints atps = (AuthorizationPoints) request.getSession().getAttribute("LOGGED_USER_ATPS");
        if (atps == null) {
            atps = new AuthorizationPoints(null);
            request.getSession().setAttribute("LOGGED_USER_ATPS", atps);
        }

        AuthorizationBO authBO = new AuthorizationBO();
        String handlerName = JsonController.targetJsonHandlers.getProperty(thisPage);

        if (thisPage.equals("ping") && submitButton.equals("ping")) {
            jsonResponse = new SuccessDTO("OK")
                    .toJSONObject(BaseHandler.getI18nProperties(session, "biblivre3"));

        } else if (authBO.authorize(atps, handlerName, submitButton)) {
            RootJsonHandler handler = (RootJsonHandler) Class.forName(handlerName).newInstance();
            jsonResponse = handler.process(request, response);

        } else {
            if (atps == null) {
                status = 403;
            }

            jsonResponse = this.jsonFailure(session, "warning", "ERROR_NO_PERMISSION");
        }

    } catch (ClassNotFoundException e) {
        System.out.println("====== [mercury.Controller.processRequest()] Exception 1: " + e);
        jsonResponse = this.jsonFailure(session, "error", "DIALOG_VOID");

    } catch (ExceptionUser e) {
        System.out.println("====== [mercury.Controller.processRequest()] Exception 2: " + e.getKeyText());
        jsonResponse = this.jsonFailure(session, "error", e.getKeyText());

    } catch (Exception e) {
        System.out.println("====== [mercury.Controller.processRequest()] Exception 3: " + e);
        e.printStackTrace();
        jsonResponse = this.jsonFailure(session, "error", "DIALOG_VOID");

    } finally {
        // Print response to browser
        if (status != null) {
            response.setStatus(status);
        }

        if (jsonResponse != null) {
            try {
                jsonResponse.putOnce("success", true); // Only put success on response if not already present.
            } catch (JSONException e) {
            }
            response.getWriter().print(jsonResponse.toString());
        }
    }
}

From source file:cn.vlabs.umt.ui.servlet.UMTPublicKeyServiceServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    UMTCredential cred = (UMTCredential) factory.getBean("UMTCredUtil");
    PublicKeyEnvelope opublickey = new PublicKeyEnvelope();
    opublickey.setAppId(cred.getUMTId());
    Date month = DateUtils.addMonths(new Date(cred.getCreateTime()), 1);
    opublickey.setValidTime(DateFormatUtils.format(month, "yyyy-MM-dd hh:mm:ss"));
    opublickey.setPublicKey(HexUtil.toHexString(cred.getUMTKey().getRSAPublic().getEncoded()));
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    out.write(opublickey.toXML());/*from w w  w.  j  a v  a  2  s .c o  m*/
    out.flush();
    out.close();

}

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

/**
 * Handler to return the cached js file with the dependent components.
 * /*from   ww  w  .  java 2 s. c o m*/
 * @param bundle
 * @param frame
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{bundle}/{frame}.js", method = RequestMethod.GET)
@ResponseBody
public String frameCmpJs(@PathVariable("bundle") String bundle, @PathVariable("frame") String frame,
        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 + ".js";
    File f = new File(this.cacheFolder + "/" + bundle + "." + fileName);

    if (!f.exists()) {
        DependencyLoader loader = this.getDependencyLoader(request);
        loader.packFrameCmp(bundle, frame, f);
    }

    this.sendFile(f, response.getOutputStream());

    return null;
}

From source file:com.epam.wilma.test.server.ExampleHandler.java

private void generateBadResponses(String path, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, Request baseRequest) throws IOException {
    if (PATH_SEND_BAD_FIS.equals(path)) {
        byte[] responseBodyAsBytes;
        if (httpServletRequest.getHeader(ACCEPT_HEADER).contains(FASTINFOSET_TYPE)) {
            InputStream xml = getXmlFromFile(EXAMPLE_XML);
            httpServletResponse.setContentType("application/fastinfoset");
            httpServletResponse.setCharacterEncoding("UTF-8");
            responseBodyAsBytes = IOUtils.toByteArray(xml, xml.available());

            //Encodes response body with gzip if client accepts gzip encoding
            if (httpServletRequest.getHeader(ACCEPT_ENCODING) != null
                    && httpServletRequest.getHeader(ACCEPT_ENCODING).contains(GZIP_TYPE)) {
                ByteArrayOutputStream gzipped = gzipCompressor
                        .compress(new ByteArrayInputStream(responseBodyAsBytes));
                responseBodyAsBytes = gzipped.toByteArray();
                httpServletResponse.addHeader(CONTENT_ENCODING, GZIP_TYPE);
            }/*from   w  ww .  ja va 2s.co  m*/

            httpServletResponse.getOutputStream().write(responseBodyAsBytes);
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    }
}

From source file:cn.mk.ndms.modules.lease.web.controller.LeaseController.java

@RequestMapping("download")
public String download(String fileName, HttpServletRequest request, HttpServletResponse response) {
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
    try {// ww w .ja  v  a 2  s .  c o m
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "file";//downloadclasses
        InputStream inputStream = new FileInputStream(new File(path + File.separator + fileName));

        OutputStream os = response.getOutputStream();
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        // ?
        os.close();
        inputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //  ???????
    //java+getOutputStream() has already been called for this response
    return null;
}