List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String encodedProjectName = req.getRequestURI().substring(req.getRequestURI().lastIndexOf('/') + 1); String projectName = encodedProjectName.replace("%2F", "/"); //Always send 200 status and handle errors in ProjectScreenSettings res.setStatus(200);//from w ww . j a v a 2s.co m res.setContentType("application/json"); res.setCharacterEncoding("UTF-8"); //When an error occurs, this returns an error message to ProjectScreenSettings to warn the user. if (!safetyCheck(getResponseCode(projectName), res, projectName)) return; try { JenkinsServerConfiguration jsc = ConfigFileUtils .getJenkinsConfigFromFile(new File(sitePaths.etc_dir, "gerrit-ci.config")); ArrayList<String> jobNames = ConfigFileUtils.getJobsFromFile(new File(sitePaths.etc_dir, projectName)); Map<String, JsonArray> jobs = new HashMap<String, JsonArray>(); for (String jobName : jobNames) { String jobType = getTypeFromName(jobName); JsonArray params = JenkinsJobParser.parseJenkinsJob(jobName, jobType, jsc); jobs.put(jobName, params); } JsonObject returnObj = makeJSonRequest(jobs); res.getWriter().write(returnObj.toString()); } catch (Exception e) { logger.error("Error checking job from Jenkins:", e); JsonObject errorMsg = makeErrorJobObject(connectionError); res.getWriter().write(errorMsg.toString()); } }
From source file:de.ifgi.mosia.wpswfs.handler.ProxyRequestHandler.java
protected void writeResponse(String filteredContent, String enc, Header contentType, int statusCode, HttpServletResponse resp) throws IOException { if (enc == null) { enc = "UTF-8"; }//from w w w . ja v a2 s . com byte[] bytes; if (statusCode == HttpStatus.SC_NO_CONTENT) { bytes = new byte[0]; } else if (filteredContent == null) { /* * recursive call end exit */ writeResponse(new ExceptionReportWrapper(new IOException("Proxy server issue")).toXML(), "UTF-8", new BasicHeader("Content-Type", "application/xml"), HttpStatus.SC_INTERNAL_SERVER_ERROR, resp); return; } else { bytes = filteredContent.getBytes(enc); } resp.setContentType(contentType == null ? "application/xml" : contentType.getValue()); resp.setCharacterEncoding(enc); resp.setContentLength(bytes.length); resp.setStatus(statusCode); resp.getOutputStream().write(bytes); resp.getOutputStream().flush(); }
From source file:com.jsmartframework.web.manager.FilterControl.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; httpRequest.setCharacterEncoding(ENCODING); httpResponse.setCharacterEncoding(ENCODING); // Initiate bean context based on current thread instance WebContext.initCurrentInstance(httpRequest, httpResponse); // Instantiate request scoped authentication bean HANDLER.instantiateAuthBean(httpRequest); // Instantiate web security for request extra validation HANDLER.instantiateWebSecurity(httpRequest); // Anonymous subclass to wrap HTTP response to print output WebFilterResponseWrapper responseWrapper = new WebFilterResponseWrapper(httpResponse); Throwable throwable = null;/*from w ww . j av a2 s. c o m*/ try { filterChain.doFilter(request, responseWrapper); } catch (Throwable thrown) { throwable = thrown; thrown.printStackTrace(); } // Finalize request scoped web and auth beans HANDLER.finalizeBeans(httpRequest, responseWrapper); // Check if response was written before closing the WebContext boolean responseWritten = WebContext.isResponseWritten(); // Close bean context based on current thread instance WebContext.closeCurrentInstance(); // Case AsyncBean or RequestPath process was started it cannot proceed because it will not provide HTML via framework if (httpRequest.isAsyncStarted() || responseWritten) { // Generate response value after flushing the response wrapper buffer responseWrapper.flushBuffer(); String responseVal = responseWrapper.toString(); // Close current outputStream on responseWrapper responseWrapper.close(); // Write the response value on real response object if (!httpResponse.isCommitted()) { httpResponse.getWriter().write(responseVal); } // Case internal server error if (throwable != null) { if (throwable instanceof IOException) { throw new IOException(throwable); } throw new ServletException(throwable); } return; } // Add Ajax headers to control redirect and reset addAjaxHeaders(httpRequest, responseWrapper); // Generate HTML after flushing the response wrapper buffer responseWrapper.flushBuffer(); String html = completeHtml(httpRequest, responseWrapper); // Close current outputStream on responseWrapper responseWrapper.close(); // Case internal server error if (throwable != null) { responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (throwable instanceof IOException) { throw new IOException(throwable); } throw new ServletException(throwable); } if (StringUtils.isBlank(html)) { return; } if (CONFIG.getContent().isPrintHtml()) { LOGGER.log(Level.INFO, html); } // Compress html to better load performance HtmlCompress compressHtml = CONFIG.getContent().getCompressHtml(); if (compressHtml.isCompressHtml()) { HtmlCompressor compressor = new HtmlCompressor(); compressor.setRemoveComments(!compressHtml.isSkipComments()); html = compressor.compress(html); } // Write our modified text to the real response if (!httpResponse.isCommitted()) { httpResponse.setContentLength(html.getBytes().length); httpResponse.getWriter().write(html); } }
From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java
public void writeBodyResponseAsJson(HttpServletResponse response, String data, Map<String, String> errors) { try {// w w w. ja v a2s . com org.json.JSONObject jsonResponse = new org.json.JSONObject(); org.json.JSONObject jsonErrors = new org.json.JSONObject(); if (errors == null || errors.keySet().size() == 0) { jsonResponse.put("status", "OK"); } else { jsonResponse.put("status", "FAIL"); for (String key : errors.keySet()) { jsonErrors.put(key, errors.get(key)); } } jsonResponse.put("errors", jsonErrors); jsonResponse.put("payload", data); String jsonString = jsonResponse.toString(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ServletOutputStream writer = response.getOutputStream(); byte[] utf8bytes = jsonString.getBytes("UTF-8"); writer.write(utf8bytes); response.setContentLength(utf8bytes.length); writer.flush(); } catch (Exception e) { try { String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}"; ServletOutputStream writer = response.getOutputStream(); response.setContentType("application/json"); byte[] utf8bytes = errorResponse.getBytes("UTF-8"); response.setContentLength(utf8bytes.length); writer.write(utf8bytes); writer.flush(); } catch (IOException ioe) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:com.cognifide.aet.executor.SuiteServlet.java
/** * Starts processing of the test suite defined in the XML file provided in post body. Overrides * domain specified in the suite file if one has been provided in post body. Returns JSON defined * by {@link SuiteExecutionResult}. The request's content type must be 'multipart/form-data'. * * @param request/* w w w. j a va 2 s. c om*/ * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) { Map<String, String> requestData = getRequestData(request); String suite = requestData.get(SUITE_PARAM); String domain = requestData.get(DOMAIN_PARAM); if (StringUtils.isNotBlank(suite)) { SuiteExecutionResult suiteExecutionResult = suiteExecutor.execute(suite, domain); Gson gson = new Gson(); String responseBody = gson.toJson(suiteExecutionResult); if (suiteExecutionResult.getErrorMessage() == null) { response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding(CharEncoding.UTF_8); response.getWriter().write(responseBody); } else { response.sendError(500, suiteExecutionResult.getErrorMessage()); } } else { response.sendError(400, "Request does not contain the test suite"); } } else { response.sendError(400, "Request content is incorrect"); } }
From source file:com.haulmont.cuba.restapi.DataServiceController.java
@RequestMapping(value = "/api/printDomain", method = RequestMethod.GET) public void printDomain(@RequestParam(value = "s") String sessionId, HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, NoSuchMethodException, IllegalAccessException, TemplateException { if (!connect(sessionId, response)) return;// ww w.ja v a2 s .c om try { response.setContentType("text/html"); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); response.setLocale(userSessionSource.getLocale()); String domainDescription = domainDescriptionService.getDomainDescription(); response.getWriter().write(domainDescription); } catch (Throwable e) { sendError(request, response, e); } finally { authentication.end(); } }
From source file:com.globalsight.connector.blaise.BlaiseCreateJobHandler.java
@Override public void beforeAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, EnvoyServletException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); }
From source file:com.browseengine.bobo.servlet.BrowseServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SolrParams params = new BoboHttpRequestParam(req); String qstring = params.get(CommonParams.Q); String df = params.get(CommonParams.DF); String sortString = params.get(CommonParams.SORT); BoboDefaultQueryBuilder qbuilder = new BoboDefaultQueryBuilder(); Query query = qbuilder.parseQuery(qstring, df); Sort sort = qbuilder.parseSort(sortString); BrowseRequest br = null;// w ww .jav a2 s .com try { br = BoboRequestBuilder.buildRequest(params, query, sort); logger.info("REQ: " + BrowseProtobufConverter.toProtoBufString(br)); BrowseResult result = _svc.browse(br); res.setCharacterEncoding("UTF-8"); Writer writer = res.getWriter(); String outputFormat = req.getParameter("output"); if ("json".equals(outputFormat)) { try { String val = BrowseJSONSerializer.serialize(result); writer.write(val); } catch (JSONException je) { throw new IOException(je.getMessage()); } } else { XStream xstream = XStreamDispenser.getXMLXStream(); writer.write(xstream.toXML(result)); } } catch (BrowseException e) { throw new ServletException(e.getMessage(), e); } }
From source file:com.ewcms.plugin.vote.manager.web.ResultServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletOutputStream out = null;//from www. j a va 2s. c o m StringBuffer output = new StringBuffer(); try { String id = req.getParameter("id"); if (!id.equals("") && StringUtils.isNumeric(id)) { Long questionnaireId = new Long(id); ServletContext application = getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application); VoteFacable voteFac = (VoteFacable) wac.getBean("voteFac"); String ipAddr = req.getRemoteAddr(); output = voteFac.getQuestionnaireResultClientToHtml(questionnaireId, getServletContext().getContextPath(), ipAddr); } out = resp.getOutputStream(); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); out.write(output.toString().getBytes("UTF-8")); out.flush(); } finally { if (out != null) { out.close(); out = null; } } }