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.linuxbox.enkive.web.search.SearchFolderServlet.java

@SuppressWarnings("unused")
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.setCharacterEncoding("UTF-8");
    try {/*from  ww w  .j  a  va 2s.c o m*/

        String searchFolderId = WebScriptUtils.cleanGetParameter(req, "id");
        String action = WebScriptUtils.cleanGetParameter(req, "action");

        if (searchFolderId == null || searchFolderId.isEmpty())
            searchFolderId = "unimplemented";
        /*            searchFolderId = workspaceService.getActiveWorkspace(
          getPermissionService().getCurrentUsername())
          .getSearchFolderID();*/
        if (action == null || action.isEmpty())
            action = VIEW_SEARCH_FOLDER;

        WebPageInfo pageInfo = new WebPageInfo(WebScriptUtils.cleanGetParameter(req, PAGE_POSITION_PARAMETER),
                WebScriptUtils.cleanGetParameter(req, PAGE_SIZE_PARAMETER));

        JSONObject dataJSON = new JSONObject();
        JSONObject jsonResult = new JSONObject();
        dataJSON.put(SEARCH_ID_TAG, searchFolderId);

        if (LOGGER.isInfoEnabled())
            LOGGER.info("Loading " + searchFolderId);

        /*         SearchFolder searchFolder = workspaceService
                       .getSearchFolder(searchFolderId);*/
        SearchFolder searchFolder = null;

        JSONArray resultsJson = new JSONArray();

        if (searchFolder == null) {
            // No search folder
        } else if (action.equalsIgnoreCase(ADD_SEARCH_FOLDER_MESSAGE)) {
            String searchResultId = WebScriptUtils.cleanGetParameter(req, "searchResultId");
            String messageidlist = WebScriptUtils.cleanGetParameter(req, "messageids");
            Collection<String> messageIds = new HashSet<String>(Arrays.asList(messageidlist.split(",")));
            addSearchFolderMessages(searchFolder, searchResultId, messageIds);
        } else if (action.equalsIgnoreCase(EXPORT_SEARCH_FOLDER)) {
            res.setContentType("application/x-gzip; charset=ISO-8859-1");
            exportSearchFolder(searchFolder, res.getOutputStream());
        } else if (action.equalsIgnoreCase(REMOVE_SEARCH_FOLDER_MESSAGE)) {
            String messageidlist = WebScriptUtils.cleanGetParameter(req, "messageids");
            Collection<String> messageIds = new HashSet<String>(Arrays.asList(messageidlist.split(",")));
            removeSearchFolderMessages(searchFolder, messageIds);
        } else if (action.equalsIgnoreCase(VIEW_SEARCH_FOLDER)) {
            resultsJson = viewSearchFolder(searchFolder, pageInfo);
            dataJSON.put(ITEM_TOTAL_TAG, pageInfo.getItemTotal());

            dataJSON.put(RESULTS_TAG, resultsJson);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Returning search folder messages for folder id " + searchFolderId);

            jsonResult.put(DATA_TAG, dataJSON);
            jsonResult.put(PAGING_LABEL, pageInfo.getPageJSON());
            res.getWriter().write(jsonResult.toString());
        }

    } catch (WorkspaceException e) {
        respondError(HttpServletResponse.SC_UNAUTHORIZED, null, res);
        throw new EnkiveServletException("Could not login to repository to retrieve search", e);
    } catch (JSONException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to serialize JSON", e);
    } catch (CannotRetrieveException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to retrieve search folder messages", e);
    } finally {

    }
}

From source file:application.controllers.admin.EmotionList.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setCharacterEncoding("UTF-8");
    response.addHeader("Content-Type", "text/html");
    String groupId = request.getParameter("groupId");

    View view = new View("admin", "EmotionList.xtm");
    View codeJSView = new View("assets", "JSEmotionList.xtm");

    //set groupId cho code js emotion
    codeJSView.setVariable("groupIdJS", groupId);
    View layout = new View("Index.xtm");
    view.setVariable("host", Registry.get("Host"));
    view.setVariable("groupId", groupId);
    EmotionBOImpl emotionImpl = new EmotionBOImpl();
    List<EmotionPOJO> listEmotionInGroup = emotionImpl.getEmotionWithGroup(groupId);
    Memcached.set("listEmotionInGroup" + groupId, 3600, listEmotionInGroup);

    //set  table list emotion
    TemplateDataDictionary listEmotionView = view.addSection("listEmotion");
    for (int i = 0; i < listEmotionInGroup.size(); i++) {
        TemplateDataDictionary emotionItem = listEmotionView.addSection("emotionItem");
        //            emotionItem.setVariable("imageId", Integer.toString(i + 1));
        emotionItem.setVariable("imageId", Integer.toString(listEmotionInGroup.get(i).emotionId));
        //lay link trong database set cho image 
        //            emotionItem.setVariable("imageLink", Registry.get("Host") + "/" + listEmotionInGroup.get(i).linkImage);
        emotionItem.setVariable("imageLink", listEmotionInGroup.get(i).linkImage);
        emotionItem.setVariable("description", listEmotionInGroup.get(i).description);
        emotionItem.setVariable("emotionId", Integer.toString(listEmotionInGroup.get(i).emotionId));
        emotionItem.setVariable("emotionIndexInGroup", Integer.toString(i));
        emotionItem.setVariable("groupId", groupId);

    }/*  www. j  ava 2  s .  c  o m*/
    String resourceHost = "";
    resourceHost += Registry.get("Host");
    resourceHost = resourceHost + "/resources";
    layout.setVariable("hostResource", resourceHost);

    //show view
    String content = view.render();
    String codeJS = codeJSView.render();
    layout.setVariable("content", content);
    layout.setVariable("codejs", codeJS);
    //Tao view

    String mainView = layout.render();
    response.getWriter().write(mainView);

}

From source file:com.zuoxiaolong.blog.web.controller.AbstractWebController.java

/**
 * // w w  w.j a va 2s  .co m
 *
 * @param string
 * @return
 */
protected void renderText(String string, String type) {
    try {
        HttpServletResponse response = getResponse();
        response.reset();
        response.setContentType(type);
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(string);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.dfox.junit.http.JUnitHttpServlet.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    response.setCharacterEncoding(UTF_8);

    final String[] pathComponents = parsePath(request);

    if (pathComponents.length < 2) {
        response.setStatus(NOT_FOUND_STATUS);
    } else {//from  ww w .  j  a va 2 s .  c o  m
        final String path = joinPathAfterPrefix(pathComponents);
        switch (pathComponents[0]) {
        case TESTS_PREFIX:
            runTest(path, response);
            break;
        case FIXTURES_PREFIX:
            runFixture(path, response);
            break;
        default:
            response.setStatus(NOT_FOUND_STATUS);
            break;
        }
    }
}

From source file:io.dfox.junit.http.JUnitHttpServlet.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    response.setCharacterEncoding(UTF_8);

    final String[] pathComponents = parsePath(request);

    if (pathComponents.length < 2 || !pathComponents[0].equals(DATA_PREFIX)) {
        response.setStatus(NOT_FOUND_STATUS);
    } else {//from  ww  w  . ja v  a  2  s.com
        final String path = joinPathAfterPrefix(pathComponents);
        final JsonNode data = application.getData(path);

        try (PrintWriter writer = response.getWriter()) {
            if (data == null) {
                response.setStatus(NOT_FOUND_STATUS);
                writer.append("Data not found: " + path);
            } else {
                response.setStatus(SUCCESS_STATUS);
                response.setHeader(CONTENT_TYPE, APPLICATION_JSON);

                JSON_MAPPER.writeValue(writer, data);
            }
        }
    }
}

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

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

        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.SpeciesController.java

/**
 * Return the XML with the results/*w  w w .j a v a  2 s. com*/
 * @param request
 * @param response
 * @param species
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<String> species, List<Node> matchesByPolygon) throws Exception {

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

    if (matchesByPolygon == null) { //If there is not geographical criteria
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response><speciesList>");
        for (String s : species) {
            result.append("<species>" + s + "</species>");
        }
        result.append("</speciesList><polygons></polygons></response>");
        out.println(result.toString());
    } else { //If there is gegraphical criteria
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
        result.append("<speciesList></speciesList>");
        result.append("<polygons>");
        for (Node node : matchesByPolygon) {

            result.append("<polygon>");
            result.append("<abs>" + node.getValue1() + "</abs>");
            result.append("<per>" + node.getValue2() + "</per>");
            for (String sp : node.getValue3()) {
                result.append("<sp>" + sp + "</sp>");
            }
            result.append("</polygon>");
        }
        result.append("</polygons></response>");
        out.println(result.toString());
    }

    out.flush();
    out.close();

    return null;
}

From source file:com.web.vehiclerouting.graphhopper.http.GraphHopperServlet.java

private void writeGPX(HttpServletRequest req, HttpServletResponse res, GHResponse rsp) {
    boolean includeElevation = getBooleanParam(req, "elevation", false);
    res.setCharacterEncoding("UTF-8");
    res.setContentType("application/xml");
    String trackName = getParam(req, "track", "GraphHopper Track");
    res.setHeader("Content-Disposition", "attachment;filename=" + "GraphHopper.gpx");
    String timeZone = getParam(req, "timezone", "GMT");
    long time = getLongParam(req, "millis", System.currentTimeMillis());
    writeResponse(res, rsp.getInstructions().createGPX(trackName, time, timeZone, includeElevation));
}

From source file:org.geowe.server.upload.FileUploadServlet.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ServletFileUpload upload = new ServletFileUpload();
    response.setContentType("text/plain; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_FILE_SIZE);//from ww  w  .  j  a v  a 2  s.  c  o  m

    try {
        final FileItemIterator iter = upload.getItemIterator(request);
        final StringWriter writer = new StringWriter();
        while (iter.hasNext()) {
            final FileItemStream item = iter.next();
            IOUtils.copy(item.openStream(), writer, "UTF-8");
            final String content = writer.toString();
            response.setStatus(HttpStatus.SC_OK);
            response.getWriter().printf(content);
        }
    } catch (SizeLimitExceededException e) {
        response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG);
        response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage());
        LOG.error(e.getMessage());
    } catch (Exception e) {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong.");
        LOG.error(e.getMessage());
    }
}

From source file:com.linuxbox.enkive.web.search.ViewSavedResultsServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String sortBy = null;/* www.  j ava2 s. c o  m*/
    int sortDir = 1;
    res.setCharacterEncoding("UTF-8");
    try {
        String searchId = WebScriptUtils.cleanGetParameter(req, "id");
        sortBy = WebScriptUtils.cleanGetParameter(req, PAGE_SORT_BY_PARAMETER);
        String sortDirString = WebScriptUtils.cleanGetParameter(req, PAGE_SORT_DIR_PARAMETER);
        if (sortDirString != null)
            sortDir = Integer.parseInt(sortDirString);

        WebPageInfo pageInfo = new WebPageInfo(WebScriptUtils.cleanGetParameter(req, PAGE_POSITION_PARAMETER),
                WebScriptUtils.cleanGetParameter(req, PAGE_SIZE_PARAMETER));

        JSONObject dataJSON = new JSONObject();
        JSONObject jsonResult = new JSONObject();
        dataJSON.put(SEARCH_ID_TAG, searchId);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Loading " + searchId);

        SearchQuery query = workspaceService.getSearch(searchId);

        /* Query */
        try {
            dataJSON.put(QUERY_TAG, query.toJson());
        } catch (JSONException e) {
            LOGGER.error("could not return search criteria for search " + searchId, e);
        }

        /* Message Result List */

        try {
            SearchResult result = query.getResult();
            List<String> messageIds = result.getPage(sortBy, sortDir, pageInfo.getPagePos(),
                    pageInfo.getPageSize());

            List<MessageSummary> messageSummaries = archiveService.retrieveSummary(messageIds);
            pageInfo.setItemTotal(result.getCount());
            dataJSON.put(WebConstants.STATUS_ID_TAG, query.getStatus());

            JSONArray jsonMessageSummaryList = SearchResultsBuilder
                    .getMessageListJSON((Collection<MessageSummary>) messageSummaries);

            dataJSON.put(ITEM_TOTAL_TAG, pageInfo.getItemTotal());

            dataJSON.put(RESULTS_TAG, jsonMessageSummaryList);
        } catch (CannotRetrieveException e) {
            LOGGER.error("Could not access result message list", e);
            // throw new WebScriptException(
            // "Could not access query result message list", e);
        } catch (ResultPageException e) {
            LOGGER.error("Could not get page of results", e);
            this.addError(dataJSON, e.toString());
        }
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Returning saved search results for search id " + searchId);

        jsonResult.put(DATA_TAG, dataJSON);
        jsonResult.put(PAGING_LABEL, pageInfo.getPageJSON());
        jsonResult.write(res.getWriter());
    } catch (WorkspaceException e) {
        respondError(HttpServletResponse.SC_UNAUTHORIZED, null, res);
        throw new EnkiveServletException("Could not login to repository to retrieve search", e);
    } catch (JSONException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to serialize JSON", e);
    } finally {

    }
}