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.qwazr.library.freemarker.FreeMarkerTool.java

public void template(final String templatePath, final Locale locale, final Map<String, Object> dataModel,
        final HttpServletResponse response) throws TemplateException, IOException {
    if (response.getContentType() == null)
        response.setContentType(defaultContentType == null ? DEFAULT_CONTENT_TYPE : defaultContentType);
    response.setCharacterEncoding(DEFAULT_CHARSET);
    final Template template = cfg.getTemplate(templatePath, locale);
    template.process(dataModel, response.getWriter());
}

From source file:cn.vlabs.clb.server.ui.frameservice.document.handler.GetMultiDocsContentHandler.java

private void readDocuments(List<DocVersion> dvlist, String zipFileName, HttpServletRequest request,
        HttpServletResponse response) throws FileContentNotFoundException {
    DocumentFacade df = AppFacade.getDocumentFacade();
    OutputStream os = null;/*from w  w w . j  av  a 2s  . c o m*/
    InputStream is = null;
    ZipArchiveOutputStream zos = null;
    try {
        if (dvlist != null) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/zip");
            String headerValue = ResponseHeaderUtils.buildResponseHeader(request, zipFileName, true);
            response.setHeader("Content-Disposition", headerValue);
            os = response.getOutputStream();
            zos = new ZipArchiveOutputStream(os);
            zos.setEncoding("utf-8");
            Map<String, Boolean> dupMap = new HashMap<String, Boolean>();
            GridFSDBFile dbfile = null;
            int i = 1;
            for (DocVersion dv : dvlist) {
                dbfile = df.readDocContent(dv);
                if (dbfile != null) {
                    String filename = dbfile.getFilename();
                    ZipArchiveEntry entry = null;
                    if (dupMap.get(filename) != null) {
                        entry = new ZipArchiveEntry((i + 1) + "-" + filename);

                    } else {
                        entry = new ZipArchiveEntry(filename);
                    }
                    entry.setSize(dbfile.getLength());
                    zos.putArchiveEntry(entry);
                    is = dbfile.getInputStream();
                    FileCopyUtils.copy(is, zos);
                    zos.closeArchiveEntry();
                    dupMap.put(filename, true);
                }
                i++;
            }
            zos.finish();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
    }
}

From source file:mercury.BaseHandler.java

protected void returnJson(final JSONObject json, final HttpServletResponse response) {
    try {//from  ww w  . j av  a 2 s.  com
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        final PrintWriter out = response.getWriter();

        String r = json.toString();
        out.write(r.replaceAll("<", "&lt;").replace(">", "&gt;"));
        out.close();
    } catch (Exception e) {
        logError(e.getMessage(), e);
    }
}

From source file:com.investdata.common.filter.CharacterEncodingFilter.java

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
        request.setCharacterEncoding(this.encoding);//?  
        if (this.forceEncoding) {
            response.setCharacterEncoding(this.encoding);
        }//w w w.  j  ava2  s.c  o  m
    }
    filterChain.doFilter(request, response);//  

    /*
    if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
       request.setCharacterEncoding(this.encoding);
       if (this.forceEncoding && setCharacterEncodingAvailable) {
    response.setCharacterEncoding(this.encoding);
       }
    }
    filterChain.doFilter(request, response);
    */
}

From source file:edu.cornell.library.scholars.webapp.controller.api.DistributeDataApiController.java

private void runIt(HttpServletRequest req, HttpServletResponse resp, DataDistributor instance)
        throws DataDistributorException {
    try {/*w ww  .j a  va2s.c o  m*/
        instance.init(new DataDistributorContextImpl(req));
        log.debug("Distributor is " + instance);

        resp.setContentType(instance.getContentType());
        resp.setCharacterEncoding("UTF-8");
        instance.writeOutput(resp.getOutputStream());
    } catch (Exception e) {
        log.error("Failed to execute the DataDistributor", e);
        instance.close();
        throw new ActionFailedException(e);
    }
}

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

/**
 * Handle the boilerplate of getting the language file for a module
 * @param group the group of the module//from  w w  w. java 2  s.co  m
 * @param module the module itself
 * @param language the language to get
 * @param filter the filter to apply
 * @param response the response to write to
 * @throws IOException if an error occurs
 */
private void getModuleLanguage(String group, String module, String language, Filter filter,
        HttpServletResponse response) throws IOException {
    String contents = languageModuleBuilder.getModuleFile(group, module, language);
    response.setContentType(CONTENT_TYPE);
    response.setCharacterEncoding(CHARSET);
    response.getWriter().write(contents);
}

From source file:io.getlime.security.powerauth.app.server.WebSecurityConfig.java

@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    return new AuthenticationEntryPoint() {
        @Override/*from w w w. j a v a  2s .c  o m*/
        public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                AuthenticationException e) throws IOException, ServletException {
            RESTResponseWrapper<String> errorResponse = new RESTResponseWrapper<>("ERROR",
                    "Authentication failed");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpServletResponse.getOutputStream().println(new ObjectMapper().writeValueAsString(errorResponse));
            httpServletResponse.getOutputStream().flush();
        }
    };
}

From source file:com.rmn.qa.servlet.BmpServlet.java

/**
 * /*from w  w  w . j a v  a  2s .  co  m*/
 * {@inheritDoc}
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(200);

    StringBuilder builder = new StringBuilder();

    builder.append("<html>");
    builder.append("<head>");

    builder.append("<title>BrowserMobProxy instances</title>");

    builder.append("</head>");

    builder.append("<body>");
    builder.append("<H1>Grid Hub ");
    builder.append(coreVersion).append(coreRevision);
    builder.append("</H1>");
    Map<String, ProxyHolder> proxyMap = BmpProxyRegistry.getInstance().getProxyMap();
    DateFormat df = DateFormat.getDateTimeInstance();
    if (proxyMap.isEmpty()) {
        builder.append("No BrowserMobProxy instances currently running.");
    } else {
        for (Entry<String, ProxyHolder> entry : proxyMap.entrySet()) {
            StringBuilder localBuilder = new StringBuilder();
            ProxyHolder holder = entry.getValue();
            String uuid = entry.getKey();
            localBuilder.append("<fieldset>");
            localBuilder.append("<legend>BrowserMobProxy for test id ").append(uuid).append("</legend>");
            localBuilder.append("listening on ").append(holder.getProxy().getPort()).append("<br/>");
            localBuilder.append("started at ").append(df.format(new Date(holder.getCreated()))).append("<br/>");
            localBuilder.append("</fieldset>");
            builder.append(localBuilder.toString());
        }
    }
    try (InputStream in = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));) {
        ByteStreams.copy(in, response.getOutputStream());
    } finally {
        response.flushBuffer();
    }
}

From source file:edu.lafayette.metadb.web.controlledvocab.ShowVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///  www.  j  a v a2  s .  co m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    String vocabName = request.getParameter("vocab-name");
    //MetaDbHelper.note("Vocab Name in Servlet: "+vocabName);
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    response.setCharacterEncoding("utf-8");
    request.setCharacterEncoding("utf-8");
    JSONArray vocab = new JSONArray();
    try {
        Set<String> vocabList = ControlledVocabDAO.getControlledVocab(vocabName);
        Iterator<String> itr = vocabList.iterator();
        String[] term = request.getParameterValues("term");

        boolean autocomplete = term != null && !(term[0].equals(""));
        while (itr.hasNext()) {
            String entry = itr.next();
            if (autocomplete) {
                //MetaDbHelper.note("Entry: "+entry+", query: "+term[0]);
                if (entry.toLowerCase().startsWith(term[0].toLowerCase()))
                    vocab.put(entry);
            } else
                vocab.put(entry);
        }
        out.print(vocab);
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    out.flush();
}

From source file:com.netcracker.tss.web.servlet.customer.CustomerOrderTaxiEditDeleteServlet.java

private void redirectToEdit(HttpServletRequest req, HttpServletResponse resp, String error)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");
    DateFormat format = new SimpleDateFormat("HH:mm, dd MM yyyy", Locale.ENGLISH);
    UserBeanLocal userBeanLocal = getUserBean(req);
    req.setAttribute("personal_addr", userBeanLocal.toPersonalAddress(UserUtils.findCurrentUser()));
    TaxiOrder taxiOrder = getTaxiOrderBean(req).getOrderById(taxiOrderId);
    TaxiOrderHistory toh = getTaxiOrderBean(req).getOrderForEdit(taxiOrder);
    req.setAttribute("orderTime", format.format(toh.getOrderTime()));
    req.setAttribute("toh", toh);
    req.setAttribute("errorMessage", error);
    req.setAttribute("pageContent", "content/editTaxiOrder.jsp");
    req.setAttribute("pageType", "editpage");
    req.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(req, resp);
}