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:be.bittich.quote.security.CustomAccessDeniedHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {

    String respJSON = jsonifyMap(ImmutableMap.of("error", "Access forbidden."));
    response.setStatus(403);//from  ww  w  .j av a 2 s . com
    response.setCharacterEncoding(ENCODING_UTF8);
    response.getWriter().printf(respJSON).flush();
    response.getWriter().close();

}

From source file:org.jamwiki.servlets.ExportServlet.java

/**
 *
 *//*from  w ww .j  a v a2 s. c  om*/
private void renderXml(HttpServletResponse response, File file, boolean download) throws IOException {
    response.setContentType("application/xml");
    response.setCharacterEncoding("UTF-8");
    if (download) {
        // download instead of displaying in a browser window
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
    }
    PrintWriter out = response.getWriter();
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {
        fileReader = new FileReader(file);
        bufferedReader = new BufferedReader(fileReader);
        String s;
        while ((s = bufferedReader.readLine()) != null) {
            out.println(s);
        }
    } finally {
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(fileReader);
    }
    out.close();
}

From source file:cn.vlabs.clb.server.ui.frameservice.image.handler.GetImageContentHandler.java

private void writeFileContentToResponse(GridFSDBFile dbfile, HttpServletRequest request,
        HttpServletResponse response) {
    OutputStream os = null;//from  w  ww.  j  a  v a 2 s  . co m
    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();
        }
        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 image content using stream mode for image [" + dbfile.getId() + "], 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.telefonica.iot.perseo.EventsServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w w .ja v a  2  s.c o  m
 * @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 {
    Utils.putCorrelatorAndTrans(request);
    logger.debug("events doPost");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        StringBuilder sb = new StringBuilder();
        String eventText = Utils.getBodyAsString(request);
        logger.info("incoming event:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> eventMap = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + eventMap);
        epService.getEPRuntime().sendEvent(eventMap, Constants.IOT_EVENT);
        logger.debug("event was sent: " + eventMap);
    } catch (JSONException je) {
        logger.error("error: " + je);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:com.ibm.BestSellerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///ww  w  .  j  a v a  2s. c om
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/json");
    response.setCharacterEncoding("UTF-8");

    OutputStream stream = response.getOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");

    String listName = request.getParameter("list");
    String date = request.getParameter("date");

    logger.debug("Requested list {} and requested date {}", listName, date);

    NewYorkTimes times = new NewYorkTimes(listName, date);

    try {
        BestSellerList bestSellers = times.getList();
        ObjectMapper mapper = new ObjectMapper();

        String listContents = mapper.writeValueAsString(bestSellers.getBooks());
        logger.debug("Booklist is {}", listContents);
        writer.write(listContents);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        logger.error("New York times list unavailable");
        throw new IOException("Could not get book list from ny times");
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.MenuManagementEdit.java

private void sendReorderResponse(String errorMessage, HttpServletResponse resp) {
    try {//from   ww w. j  av a  2s  .  c  o m
        JSONObject rObj = new JSONObject();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        if (errorMessage != null && !errorMessage.isEmpty()) {
            rObj.put("errorMessage", errorMessage);
            resp.setStatus(500 /*HttpURLConnection.HTTP_SERVER_ERROR*/);
        } else {
            rObj.put("errorMessage", "");
        }
        Writer writer = resp.getWriter();
        writer.write(rObj.toString());
    } catch (Exception ex) {
        log.error("Error creating JSON object for response", ex);
    }
}

From source file:se.acrend.christopher.server.web.control.BillingController.java

@RequestMapping(value = "/billing/getProductList")
public void getProductList(final HttpServletResponse response) throws IOException {
    try {/*from   w ww .  j  a  v a  2s  .  c  o m*/
        ProductList result = billingService.getProductList();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        Gson gson = ParserFactory.createParser();
        gson.toJson(result, response.getWriter());
    } catch (Exception e) {
        log.error("Kunde inte hmta prenumeration.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.inbio.ait.web.ajax.controller.TableController.java

/**
 * Return the XML with the results//from   w  w w  .  ja v a 2  s  .co  m
 * @param request
 * @param response
 * @param species
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response, Long[][] matrix,
        List<SpeciesNode> species) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    ServletOutputStream out = response.getOutputStream();

    StringBuilder result = new StringBuilder();
    result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
    result.append("<speciesList>");
    for (SpeciesNode sp : species) {
        result.append("<species>" + sp.getName() + "</species>");
    }
    result.append("</speciesList>");
    if (matrix.length > 0) {
        int rows = matrix.length;
        int columns = matrix[0].length;
        for (int i = 0; i < rows; i++) {
            result.append("<row>");
            for (int j = 0; j < columns; j++) {
                result.append("<column>" + matrix[i][j] + "</column>");
            }
            result.append("</row>");
        }
    }
    result.append("</response>");

    out.println(result.toString());
    out.flush();
    out.close();

    return null;
}

From source file:com.graphhopper.http.GHBaseServlet.java

protected void writeJson(HttpServletRequest req, HttpServletResponse res, JSONObject json)
        throws JSONException, IOException {
    String type = getParam(req, "type", "json");
    res.setCharacterEncoding("UTF-8");
    boolean debug = getBooleanParam(req, "debug", false) || getBooleanParam(req, "pretty", false);
    if ("jsonp".equals(type)) {
        res.setContentType("application/javascript");
        if (!jsonpAllowed) {
            res.sendError(SC_INTERNAL_SERVER_ERROR, "Server is not configured to allow jsonp!");
            return;
        }//from ww w.  ja v  a2s.  c o  m

        String callbackName = getParam(req, "callback", null);
        if (callbackName == null) {
            res.sendError(SC_BAD_REQUEST, "No callback provided, necessary if type=jsonp");
            return;
        }

        if (debug) {
            writeResponse(res, callbackName + "(" + json.toString(2) + ")");
        } else {
            writeResponse(res, callbackName + "(" + json.toString() + ")");
        }
    } else {
        res.setContentType("application/json");
        if (debug) {
            writeResponse(res, json.toString(2));
        } else {
            writeResponse(res, json.toString());
        }
    }
}

From source file:se.acrend.christopher.server.web.control.BillingController.java

@RequestMapping(value = "/billing/getSubscription")
public void getSubscription(final HttpServletResponse response) throws IOException {
    try {/*from   ww  w  .j  ava  2  s  . co  m*/
        SubscriptionInfo result = billingService.getSubscription();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        Gson gson = ParserFactory.createParser();
        gson.toJson(result, response.getWriter());
    } catch (Exception e) {
        log.error("Kunde inte hmta prenumeration.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}