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:org.nsesa.editor.gwt.an.amendments.server.service.HtmlExportService.java

@Override
public void export(final AmendmentContainerDTO object, final HttpServletResponse response) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".html");
    response.setCharacterEncoding("UTF8");

    final String content = object.getBody();
    final InputSource inputSource;
    inputSource = new InputSource(new StringReader(content));

    try {/* ww w .  ja  v  a2s . c  om*/
        final NodeModel model = NodeModel.parse(inputSource);
        final Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile());
        final StringWriter sw = new StringWriter();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("amendment", model);
        root.put("editorUrl", editorUrl);
        configuration.getTemplate(template.getFile().getName()).process(root, sw);
        byte[] bytes = sw.toString().getBytes("utf-8");
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.setContentLength(bytes.length);
        response.flushBuffer();

    } catch (IOException e) {
        throw new RuntimeException("Could not read file.", e);
    } catch (SAXException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (TemplateException e) {
        throw new RuntimeException("Could not load template.", e);
    }
}

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

/**
 * Writes the response in the output!.// ww  w .  ja  va  2 s .co  m
 * @param request
 * @param response
 * @param acnList
 * @return
 * @throws Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<AutocompleteNode> acnList) throws Exception {

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    // Binary output
    ServletOutputStream out = response.getOutputStream();

    if (acnList != null) {

        for (AutocompleteNode sp : acnList) {
            out.println(sp.getItemName() + "\t" + sp.getItemId());
        }
    }

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

    return null;
}

From source file:fi.hoski.web.forms.EventServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    Event event;//from  ww  w.j  a v a2s.com
    String[] eventKeys = request.getParameterValues("event");
    if (eventKeys == null) {
        log("Event parameter missing");
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id=\"eNoEvent\">Event parameter missing</div>");
        return;
    } else if (Arrays.asList(eventKeys).contains(Event.EVENT_KEY_CHOOSE)) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id='eChooseEvent'>Choose the event</div>");
        return;
    }

    int count = 1;
    try {
        for (String eventKey : eventKeys) {
            if (!eventKey.isEmpty()) {
                try {
                    event = eventManager.getEvent(eventKey);
                } catch (Exception e) {
                    log(eventKey);
                    log(e.getMessage(), e);
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event not found</div>");
                    return;
                }

                Reservation reservation = new Reservation(event);

                @SuppressWarnings("unchecked")
                Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap();

                reservation.set(Reservation.CREATOR, request.getRemoteUser());
                reservation.populate(params);
                String[] bk = params.get(Repository.VENEET_KEY);
                if (bk != null) {
                    Key boatKey = KeyFactory.stringToKey(bk[0]);
                    reservation.set(Repository.VENEID, boatKey);
                }

                eventManager.createReservation(reservation, false);
            } else {
                if (count == 1) {
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event key not found</div>");
                    return;
                }
            }
            count++;
        }
    } catch (EntityNotFoundException ex) {
        throw new ServletException(ex);
    } catch (DoubleBookingException ex) {
        if (count == 1) {
            log(ex.getMessage(), ex);
            sendError(response, HttpServletResponse.SC_CONFLICT,
                    "<div id=\"eDoubleBooking\">Double booking.</div>");
        }
    } catch (EventFullException e) {
        if (count == 1) {
            log(e.getMessage(), e);
            sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eEventFull\">Event full.</div>");
        }
    } catch (BoatNotFoundException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eBoatNotFound\">Boat not found.</div>");

    } catch (MandatoryPropertyMissingException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eMandatoryPropertyMissing\">"
                + e.getMessage() + " mandatory property missing.</div>");

    } catch (ConcurrentModificationException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT,
                "<div id=\"eConcurrentModification\">Concurrent modification.</div>");
    }
    response.setContentType("UTF-8");
    response.getWriter().write("Ilmoittautumisesi on vastaanotettu.");
}

From source file:it.drwolf.ridire.filters.TmpResourcesFilter.java

@SuppressWarnings("unchecked")
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain arg2)
        throws IOException, ServletException {
    String filename = req.getParameter("filename");
    String encoding = req.getParameter("encoding");
    String tempDir = System.getProperty("java.io.tmpdir");
    String freqList = req.getParameter("freqList");
    String tsvList = req.getParameter("tsvList");
    if (filename != null && encoding != null && filename.indexOf(tempDir) != -1) {
        try {//w w w  .  ja  v  a  2 s.c  o m
            Lifecycle.beginCall();
            if (resp instanceof HttpServletResponse) {
                HttpServletResponse response = (HttpServletResponse) resp;
                response.setContentType("text/html");
                response.setCharacterEncoding(encoding);
                response.setHeader("Expires", "0");
                response.setHeader("Date", new Date().toString());
                response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                response.setHeader("Pragma", "public");
                File file = new File(filename);
                if (file.exists() && file.canRead()) {
                    String ret = FileUtils.readFileToString(file, encoding);
                    response.getWriter().write(ret);
                    response.getWriter().flush();
                    response.getWriter().close();
                }
                // FacesContext.getCurrentInstance().responseComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Lifecycle.endCall();
        }
    } else if (freqList != null && freqList.trim().length() > 0
            || tsvList != null && tsvList.trim().length() > 0) {
        try {
            Lifecycle.beginCall();
            String contentType = "application/vnd.oasis.opendocument.spreadsheet";
            File file = null;
            if (freqList != null) {
                file = new File(TmpResourcesFilter.LF_DIR + freqList + ".ods");
                if (freqList.equals("RIDIRE_LF")) {
                    file = new File(TmpResourcesFilter.LF_DIR + freqList + ".zip");
                    contentType = "application/zip";
                }
            } else {
                String zipFileName = tsvList.replaceAll("\\s\\(TSV\\)", "");
                file = new File(TmpResourcesFilter.LF_DIR + zipFileName + ".zip");
                contentType = "application/zip";
            }
            if (file.exists() && file.canRead()) {
                if (resp instanceof HttpServletResponse) {
                    HttpServletResponse response = (HttpServletResponse) resp;
                    response.setContentType(contentType);
                    response.setHeader("Expires", "0");
                    if (freqList != null) {
                        if (freqList.equals("RIDIRE_LF")) {
                            response.addHeader("Content-disposition",
                                    "attachment; filename=\"" + freqList + ".zip\"");
                        } else {
                            response.addHeader("Content-disposition",
                                    "attachment; filename=\"" + freqList + ".ods\"");
                        }
                    } else if (tsvList != null) {
                        response.addHeader("Content-disposition",
                                "attachment; filename=\"" + tsvList + ".zip\"");
                    }
                    response.setHeader("Date", new Date().toString());
                    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                    response.setHeader("Pragma", "public");
                    byte[] lf = FileUtils.readFileToByteArray(file);
                    response.getOutputStream().write(lf);
                    response.getOutputStream().flush();
                    response.getOutputStream().close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Lifecycle.endCall();
        }
    } else {
        Map<String, String[]> pMap = req.getParameterMap();
        final Map<String, String[]> additionalParams = new HashMap<String, String[]>();
        for (String key : pMap.keySet()) {
            // if (key.equals("forma") || key.equals("lemma")
            // || key.equals("pos") || key.equals("phrase")
            // || key.startsWith("pattern")) {
            String[] values = pMap.get(key);
            if (values != null && values.length == 1) {
                byte[] bytes = values[0].getBytes("ISO-8859-1");
                additionalParams.put(key, new String[] { new String(bytes, "UTF-8") });
            }
            // }
        }
        HttpServletRequest httpServletRequest = new PrettyFacesWrappedRequest((HttpServletRequest) req,
                additionalParams);
        arg2.doFilter(httpServletRequest, resp);
    }
}

From source file:com.cognifide.aet.rest.XUnitServlet.java

@Override
protected void process(DBKey dbKey, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String correlationId = request.getParameter(Helper.CORRELATION_ID_PARAM);
    final String suiteName = request.getParameter(Helper.SUITE_PARAM);
    response.setCharacterEncoding(Charsets.UTF_8.toString());

    try {/* w  w w . java  2s  .co  m*/
        final Suite suite = getSuite(dbKey, correlationId, suiteName);
        generateXUnitAndRespondWithIt(dbKey, response, suite);
    } catch (RestServiceException e) {
        LOGGER.error("Failed to process request!", e);
        response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        response.getWriter().write(responseAsJson(e.getMessage()));
    }
}

From source file:cz.muni.fi.webmias.ProcessServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w  ww  . j  av a2 s . co m*/
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");

    HttpSession session = request.getSession(true);

    int page = Integer.parseInt(request.getParameter("n"));
    String query = request.getParameter(QUERY_PARAMETER);
    boolean debug = request.getParameter("debug") != null;
    boolean extractSubformulae = request.getParameter("extractSubformulae") != null;
    boolean reduceWeighting = request.getParameter("reduceWeighting") != null;
    String indexNo = request.getParameter("index");
    int indexNumber = 0;
    if (indexNo != null) {
        indexNumber = Integer.parseInt(indexNo);
    }
    String qc = request.getParameter("qc");
    String variant = request.getParameter("variant");
    MathMLType mmlType = getType(variant);

    IndexDef currentIndexDef = Indexes.getIndexDef(indexNumber);
    IndexSearcher searcher = currentIndexDef.getIndexSearcher();
    request.setAttribute("index", indexNumber);
    request.setAttribute(QUERY_PARAMETER, query);
    request.setAttribute("debug", debug);
    request.setAttribute("extractSubformulae", extractSubformulae);
    request.setAttribute("reduceWeighting", reduceWeighting);
    request.setAttribute("qc", qc);
    request.setAttribute("variant", variant);
    request.setAttribute("forbidden", forbidden);

    request.setAttribute("indexes", Indexes.getIndexNames());

    if (query != null && !query.isEmpty()) {
        logQuery(request, query);
        String[] sep = MathSeparator.separate(query, "");
        query = sep[1];
        if (sep[0] != null && !sep[0].isEmpty()) {
            query += " " + TeXConverter.convertTexLatexML(sep[0]);
        }

        s = new Searching(searcher, currentIndexDef.getStorage());
        page = page == 0 ? page : page - 1;
        SearchResult searchResult = s.search(query, false, page * resPerPage, resPerPage, debug, mmlType,
                extractSubformulae, reduceWeighting);
        int totalResults = searchResult.getTotalResults();
        request.setAttribute("processedQuery", searchResult.getProcessedQuery());
        request.setAttribute("luceneQuery", searchResult.getLuceneQuery());
        request.setAttribute("total", searchResult.getTotalResults());
        request.setAttribute("coreTime", searchResult.getCoreSearchTime());
        request.setAttribute("totalTime", searchResult.getTotalSearchTime());
        request.setAttribute("resPerPage", resPerPage);
        totalResults = Math.min(totalResults, Settings.getMaxResults());
        if (totalResults > 0 && page >= 0) {
            List<Integer> pages = new ArrayList<>();
            for (int i = 0; i < (totalResults / resPerPage) + 1; i++) {
                pages.add(i + 1);
            }
            request.setAttribute("pages", pages);
            request.setAttribute("n", page);
            for (Result r : searchResult.getResults()) {
                r.setInfo(r.getInfo().replaceAll("\n", "<br/>"));
            }
            request.setAttribute("results", searchResult.getResults());
        } else if (page == -1) {
            session.invalidate();
        } else {
            request.setAttribute("nores", "No results.");
        }
    }
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

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

private void writeGPX(HttpServletRequest req, HttpServletResponse res, GHResponse rsp) throws Exception {
    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());
    if (rsp.hasErrors())
        writeResponse(res, errorsToXML(rsp.getErrors()));
    else/*from  w  ww.  jav a 2 s . co  m*/
        writeResponse(res, rsp.getInstructions().createGPX(trackName, time, timeZone, includeElevation));
}

From source file:uk.co.grahamcox.yui.YuiController.java

/**
 * Get the YUI configuration/* w  w  w  .ja  v a2  s . c o  m*/
 * @param response the response to write to
 * @throws IOException if an error occurs
 */
@RequestMapping("/config.js")
public void getYuiConfig(HttpServletResponse response) throws IOException {
    response.setContentType(CONTENT_TYPE);
    response.setCharacterEncoding(CHARSET);
    JsonNode config = yuiConfigurer.buildLoaderConfig(groups);
    response.getWriter().write("YUI_config = " + config.toString() + ";");
}

From source file:com.thinkberg.webdav.LockHandler.java

private void sendLockAcquiredResponse(HttpServletResponse response, Lock lock) throws IOException {
    if (!lock.getObject().exists()) {
        response.setStatus(SC_CREATED);/*www .ja va  2 s  .  c o  m*/
    }
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.setHeader(HEADER_LOCK_TOKEN, "<" + lock.getToken() + ">");

    Document propDoc = DocumentHelper.createDocument();
    Element propEl = propDoc.addElement(TAG_PROP, "DAV:");
    Element lockdiscoveryEl = propEl.addElement(TAG_LOCKDISCOVERY);

    lock.serializeToXml(lockdiscoveryEl);

    XMLWriter xmlWriter = new XMLWriter(response.getWriter());
    xmlWriter.write(propDoc);

    logXml(propDoc);
}

From source file:feedme.controller.OrderCompleteServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// www. j av  a2  s.c om
 *
 * @param request servlet request
 * @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");
}