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.viseur.control.AddDevItems.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  www  .  j  av a2s . 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 {
    JSONObject obj = new JSONObject();
    try {
        obj.put("success", 2);
    } catch (JSONException ex) {
    }
    Enumeration<String> names = request.getParameterNames();
    String para = names.nextElement();
    String val = request.getParameter(para);
    DeveloperItems itm = new DeveloperItems();
    switch (para) {
    case "lang":
        obj = new JSONObject(itm.addProgrammingLang(val));
        break;
    case "opsys":
        obj = new JSONObject(itm.addOpSystem(val));
        break;
    case "platform":
        obj = new JSONObject(itm.addPlatform(val));
        break;
    }
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println(obj);
    }
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Handles HTTP GET and POST requests//from  ww w  . j  a v  a 2s  .  c o  m
 *  
 * @param request
 * @param response
 * @throws IOException
 */
protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");

    /* Try to prevent spidering */
    response.setHeader("X-Robots-Tag", "nofollow");
    OutputStream outputStream = response.getOutputStream();

    /* Call REST services */
    if (request.getParameter("do") != null) {
        if (request.getParameter("do").equals("clear") && request.getParameter("url") != null) {
            clearData(request.getParameter("url"), outputStream);
        } else if (request.getParameter("do").equals("load") && request.getParameter("url") != null) {
            loadData(request.getParameter("url"), outputStream);
        } else if (request.getParameter("do").equals("discover") && request.getParameter("uri") != null) {
            discoverResource(request.getParameter("uri"), outputStream);
        }
    } else if (request.getParameter("query") != null) {
        sparqlQuery(request, response,
                outputStream); /* recognize SPARQL queries using the <code>query</code> parameter */
    } else
        fresnelView(request, response); /* default to view generation */
}

From source file:com.alexkli.osgi.troubleshoot.impl.TroubleshootServlet.java

private void startActionResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    out.println("<head>");
    String appRoot = (String) request.getAttribute(WebConsoleConstants.ATTR_APP_ROOT);
    includeCSS(out, appRoot + "/res/lib/reset-min.css");
    includeCSS(out, appRoot + "/res/lib/themes/base/jquery-ui.css");
    includeCSS(out, appRoot + getBrandingPlugin().getMainStyleSheet());
    embedStyle(out, "css/action.css");
    embedScript(out, "js/action.js");
    out.println("</head>");

    out.println("<body class='ui-widget'>");

    // add padding to force immediate flushing (response.flushBuffer() alone isn't enough at the start)
    for (int i = 0; i < 100; i++) {
        out.print(" ");
    }/*from w  w  w  .  j  ava 2  s  .  com*/
}

From source file:com.viseur.control.SearchDevItems.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  ww .  j a v  a  2s .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 {
    JSONObject obj = new JSONObject();
    try {
        obj.put("success", 0);
    } catch (JSONException ex) {
    }
    Enumeration<String> names = request.getParameterNames();
    String para = names.nextElement();
    String val = request.getParameter(para);
    DeveloperItems itm = new DeveloperItems();
    switch (para) {
    case "lang":
        obj = new JSONObject(itm.getProgrammingLangs(val));
        break;
    case "opsys":
        obj = new JSONObject(itm.getOpSystems(val));
        break;
    case "platform":
        obj = new JSONObject(itm.getPlatforms(val));
        break;
    }
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println(obj);
    }
}

From source file:com.turn.splicer.SplicerServlet.java

private void doPostWork(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedReader reader = request.getReader();
    String line;/*  ww w .j  a va  2 s .  com*/

    StringBuilder builder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }

    String jsonPostRequest = builder.toString();

    TsQuery tsQuery = TsQuerySerializer.deserializeFromJson(jsonPostRequest);
    tsQuery.validateAndSetQuery();

    LOG.info("Serving query={}", tsQuery);

    LOG.info("Original TsQuery Start time={}, End time={}", Const.tsFormat(tsQuery.startTime()),
            Const.tsFormat(tsQuery.endTime()));

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

    try (RegionChecker checker = REGION_UTIL.getRegionChecker()) {

        List<TSSubQuery> subQueries = new ArrayList<>(tsQuery.getQueries());
        SplicerQueryRunner queryRunner = new SplicerQueryRunner();

        if (subQueries.size() == 1) {
            TsdbResult[] results = queryRunner.sliceAndRunQuery(tsQuery, checker);
            if (results == null || results.length == 0) {
                response.getWriter().write("[]");
            } else {
                response.getWriter().write(TsdbResult.toJson(results));
            }
            response.getWriter().flush();
        } else {
            List<TsdbResult[]> resultsFromAllSubQueries = new ArrayList<>();
            for (TSSubQuery subQuery : subQueries) {
                TsQuery tsQueryCopy = TsQuery.validCopyOf(tsQuery);
                tsQueryCopy.addSubQuery(subQuery);
                TsdbResult[] results = queryRunner.sliceAndRunQuery(tsQueryCopy, checker);
                resultsFromAllSubQueries.add(results);
            }
            response.getWriter().write(TsdbResult.toJson(SplicerUtils.flatten(resultsFromAllSubQueries)));
        }
    }
}

From source file:com.thinkberg.moxo.dav.PropPatchHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {//from w  w  w .j a  v  a2s.c o  m
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        //      log(propDoc);

        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(SC_MULTI_STATUS);

        if (object.exists()) {
            Document resultDoc = DocumentHelper.createDocument();
            Element multiStatusResponse = resultDoc.addElement("multistatus", "DAV:");
            Element responseEl = multiStatusResponse.addElement("response");
            try {
                URL url = new URL(getBaseUrl(request), URLEncoder.encode(object.getName().getPath(), "UTF-8"));
                log("!! " + url);
                responseEl.addElement("href").addText(url.toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Element propstatEl = responseEl.addElement("propstat");
            Element propEl = propstatEl.addElement("prop");

            Element propertyUpdateEl = propDoc.getRootElement();
            for (Object elObject : propertyUpdateEl.elements()) {
                Element el = (Element) elObject;
                if ("set".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        setProperty(propEl, object, (Element) propObject);
                    }
                } else if ("remove".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        removeProperty(propEl, object, (Element) propObject);
                    }
                }
            }
            propstatEl.addElement("status").addText(DavResource.STATUS_403);

            //        log(resultDoc);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(resultDoc);
            writer.flush();
            writer.close();
        } else {
            log("!! " + object.getName().getPath() + " NOT FOUND");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (DocumentException e) {
        log("!! inavlid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from  w ww  . j a v  a 2s . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

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

    if (action == null) {
        response.sendRedirect("indexParticular.jsp");
    } else {
        switch (action) {
        case "create":
            create(request, response);
            break;

        case "create2":
            create2(request, response);
            break;

        case "read":
            read(request, response);
            break;

        case "readNumero":
            readNumero(request, response);
            break;

        case "update":
            update(request, response);
            break;

        case "demandasHechas":
            demandasHechas(request, response);
            break;

        case "demandasRecibidas":
            demandasRecibidas(request, response);
            break;

        case "agregarDocumentos":
            agregarDocumentos(request, response);
            break;

        case "agregarDocumentosD":
            agregarDocumentosD(request, response);
            break;

        case "readRecibida":
            readRecibida(request, response);
            break;

        case "apelarDemanda":
            apelarDemanda(request, response);
            break;

        case "form":
            form(request, response);
            break;

        default:
            response.sendRedirect("indexParticular.jsp");
            break;
        }
    }
}

From source file:io.fabric8.apiman.ui.ConfigurationServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * Grabs the authToken from the user's sessions and sticks it in the config.js using
 * a token replacement of the token '@token@'.
 *///from  www . j a v a 2  s .co  m
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String authToken = (String) request.getSession().getAttribute(LinkServlet.AUTH_TOKEN);
    log.info("AuthToken = " + authToken);
    InputStream is = null;
    String configFile = null;
    if (authToken == null) {
        log.debug("No authToken in the user's session with id " + request.getSession().getId());
        is = getClass().getResourceAsStream("/apimanui/apiman/f8-config-bkwrds-compatible.js");
        configFile = IOUtils.toString(is);
    } else {
        is = getClass().getResourceAsStream("/apimanui/apiman/f8-config.js");
        configFile = IOUtils.toString(is);
        configFile = configFile.replace("@token@", authToken);
    }
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/javascript");
        response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
        response.setDateHeader("Expires", 0);
        response.getOutputStream().write(configFile.getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.sparql.GetAllClasses.java

/**
 * The doGet method of the servlet. <br>
 * /*from   ww  w.  j av a 2  s .  c om*/
 * This method is called when a form has its tag value method equals to get.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.USE_MISCELLANEOUS_PAGES.ACTION)) {
        return;
    }

    VitroRequest vreq = new VitroRequest(request);

    // EditProcessObject epo = super.createEpo(request);

    List classGroups = vreq.getUnfilteredWebappDaoFactory().getVClassGroupDao()
            .getPublicGroupsWithVClasses(true, true, false); // order by
    // displayRank,
    // include
    // uninstantiated
    // classes,
    // don't get
    // the
    // counts of
    // individuals

    Iterator classGroupIt = classGroups.iterator();

    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String respo = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    respo += "<options>";

    while (classGroupIt.hasNext()) {
        VClassGroup group = (VClassGroup) classGroupIt.next();
        List classes = group.getVitroClassList();
        Iterator classIt = classes.iterator();
        while (classIt.hasNext()) {
            VClass clazz = (VClass) classIt.next();
            respo += "<option>" + "<key>" + clazz.getPickListName() + "</key>" + "<value>" + clazz.getURI()
                    + "</value>" + "</option>";
        }
    }
    respo += "</options>";
    out.println(respo);
    out.flush();
    out.close();
}

From source file:com.google.sampling.experiential.server.EventServlet.java

private void setCharacterEncoding(HttpServletRequest req, HttpServletResponse resp)
        throws UnsupportedEncodingException {
    req.setCharacterEncoding(Charsets.UTF_8.name());
    resp.setCharacterEncoding(Charsets.UTF_8.name());
}