List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { response.setCharacterEncoding("UTF-8"); String htmlEscapedUri = HtmlQuoting.quoteHtmlChars(request.getRequestURI()); if (htmlEscapedUri == null) { htmlEscapedUri = "/"; }/*from ww w .ja v a 2 s . c o m*/ String uriWithQueryString = htmlEscapedUri; String htmlEscapedUriWithQueryString = htmlEscapedUri; String queryString = request.getQueryString(); if (queryString != null && !queryString.isEmpty()) { String reqEncoding = request.getCharacterEncoding(); if (reqEncoding == null || reqEncoding.isEmpty()) { reqEncoding = "ISO-8859-1"; } Charset encoding = Charset.forName(reqEncoding); List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding); String urlEncodedQueryString = URLEncodedUtils.format(params, encoding); uriWithQueryString += "?" + urlEncodedQueryString; htmlEscapedUriWithQueryString = HtmlQuoting .quoteHtmlChars(request.getRequestURI() + "?" + urlEncodedQueryString); } RMWebApp rmWebApp = injector.getInstance(RMWebApp.class); rmWebApp.checkIfStandbyRM(); if (rmWebApp.isStandby() && shouldRedirect(rmWebApp, htmlEscapedUri)) { String redirectPath = rmWebApp.getRedirectPath(); if (redirectPath != null && !redirectPath.isEmpty()) { redirectPath += uriWithQueryString; String redirectMsg = "This is standby RM. The redirect url is: " + htmlEscapedUriWithQueryString; PrintWriter out = response.getWriter(); out.println(redirectMsg); response.setHeader("Location", redirectPath); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); return; } else { boolean doRetry = true; String retryIntervalStr = request.getParameter(YarnWebParams.NEXT_REFRESH_INTERVAL); int retryInterval = 0; if (retryIntervalStr != null) { try { retryInterval = Integer.parseInt(retryIntervalStr.trim()); } catch (NumberFormatException ex) { doRetry = false; } } int next = calculateExponentialTime(retryInterval); String redirectUrl = appendOrReplaceParamter(path + uriWithQueryString, YarnWebParams.NEXT_REFRESH_INTERVAL + "=" + (retryInterval + 1)); if (redirectUrl == null || next > MAX_SLEEP_TIME) { doRetry = false; } String redirectMsg = doRetry ? "Can not find any active RM. Will retry in next " + next + " seconds." : "There is no active RM right now."; redirectMsg += "\nHA Zookeeper Connection State: " + rmWebApp.getHAZookeeperConnectionState(); PrintWriter out = response.getWriter(); out.println(redirectMsg); if (doRetry) { response.setHeader("Refresh", next + ";url=" + redirectUrl); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } } return; } else if (ahsEnabled) { String ahsRedirectUrl = ahsRedirectPath(uriWithQueryString, rmWebApp); if (ahsRedirectUrl != null) { response.setHeader("Location", ahsRedirectUrl); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); return; } } super.doFilter(request, response, chain); }
From source file:de.hska.ld.core.config.security.AjaxAuthenticationSuccessHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String userJson = null;// w w w .j a v a 2s . c om try { userJson = mapper.writeValueAsString(authentication.getPrincipal()); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage()); } if (userJson != null) { response.setCharacterEncoding("UTF-8"); response.getWriter().write(userJson); response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.inbio.ait.web.ajax.controller.QueryController.java
/** * Write the XML to be parsed on the analysis view * Case: three parameters (1)//from w w w .j a v a 2s . c o m * @param request * @param response * @param totalMatch * @param matchesByPolygon * @return * @throws java.lang.Exception */ private ModelAndView writeReponse1(HttpServletRequest request, HttpServletResponse response, List<Node> matchesByPolygon, List<Node> matchesByIndicator, Long totalMatches, Long totalPercentage) throws Exception { response.setCharacterEncoding("ISO-8859-1"); response.setContentType("text/xml"); ServletOutputStream out = response.getOutputStream(); StringBuilder result = new StringBuilder(); result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>"); result.append("<type>1</type>"); result.append("<total>" + totalMatches + "</total>"); result.append("<totalp>" + totalPercentage + "</totalp>"); for (Node mp : matchesByPolygon) { result.append("<bypolygon>"); result.append("<abs>" + mp.getValue1() + "</abs>"); result.append("<per>" + mp.getValue2() + "</per>"); result.append("</bypolygon>"); } for (Node mi : matchesByIndicator) { result.append("<byindicator>"); result.append("<abs>" + mi.getValue1() + "</abs>"); result.append("<per>" + mi.getValue2() + "</per>"); result.append("</byindicator>"); } result.append("</response>"); out.println(result.toString()); out.flush(); out.close(); return null; }
From source file:com.thoughtworks.go.server.newsecurity.filters.AccessTokenAuthenticationFilter.java
private void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, String errorMessage) throws IOException { response.setStatus(SC_UNAUTHORIZED); ContentTypeAwareResponse contentTypeAwareResponse = new ContentTypeNegotiationMessageRenderer() .getResponse(request);/*w w w.j ava 2 s . com*/ response.setCharacterEncoding("utf-8"); response.setContentType(contentTypeAwareResponse.getContentType().toString()); response.getOutputStream().print(contentTypeAwareResponse.getFormattedMessage(errorMessage)); }
From source file:fi.aluesarjat.prototype.AreasServlet.java
@Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince >= LAST_MODIFIED) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return;/*from w w w .j av a 2 s . co m*/ } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setDateHeader("Last-Modified", System.currentTimeMillis()); response.setHeader("Cache-Control", "max-age=86400"); String level = request.getParameter("level"); String content; if (level == null) { content = areas; } else if ("1".equals(level)) { content = areas1; } else if ("2".equals(level)) { content = areas2; } else if ("3".equals(level)) { content = areas3; } else if ("4".equals(level)) { content = areas4; } else { throw new IllegalArgumentException("Illegal level " + level); } response.getWriter().append(content); response.getWriter().flush(); }
From source file:ch.rasc.extclassgenerator.ModelGenerator.java
public static void writeModel(HttpServletRequest request, HttpServletResponse response, ModelBean model, OutputConfig outputConfig) throws IOException { byte[] data = generateJavascript(model, outputConfig).getBytes(UTF8_CHARSET); String ifNoneMatch = request.getHeader("If-None-Match"); String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\""; if (etag.equals(ifNoneMatch)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return;// w w w. j a va 2 s . c om } response.setContentType("application/javascript"); response.setCharacterEncoding(UTF8_CHARSET.name()); response.setContentLength(data.length); response.setHeader("ETag", etag); @SuppressWarnings("resource") ServletOutputStream out = response.getOutputStream(); out.write(data); out.flush(); }
From source file:com.twosigma.beaker.core.module.elfinder.impl.commands.FileCommand.java
@Override public void execute(FsService fsService, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) throws Exception { String target = request.getParameter("target"); boolean download = "1".equals(request.getParameter("download")); FsItemEx fsi = super.findItem(fsService, target); String mime = fsi.getMimeType(); response.setCharacterEncoding("utf-8"); response.setContentType(mime);/*from www. j a v a 2s . co m*/ //String fileUrl = getFileUrl(fileTarget); //String fileUrlRelative = getFileUrl(fileTarget); String fileName = fsi.getName(); //fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1"); if (download || MimeTypesUtils.isUnknownType(mime)) { response.setHeader("Content-Disposition", "attachments; " + getAttachementFileName(fileName, request.getHeader("USER-AGENT"))); //response.setHeader("Content-Location", fileUrlRelative); response.setHeader("Content-Transfer-Encoding", "binary"); } OutputStream out = response.getOutputStream(); InputStream is = null; response.setContentLength((int) fsi.getSize()); try { // serve file is = fsi.openInputStream(); IOUtils.copy(is, out); out.flush(); out.close(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.google.wave.api.AbstractRobotServlet.java
public void serializeOperations(String json, HttpServletResponse resp) { try {/*from w w w . ja va 2 s .co m*/ log("Outgoing operations from compjure: " + json); resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); resp.getWriter().write(json); resp.setStatus(200); } catch (IOException iox) { iox.printStackTrace(); resp.setStatus(500); } catch (Exception mx) { mx.printStackTrace(); resp.setStatus(500); } }
From source file:com.mirth.connect.server.servlets.ConfigurationServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // MIRTH-1745 response.setCharacterEncoding("UTF-8"); try {// w w w .j a v a 2 s . c o m PrintWriter out = response.getWriter(); Operation operation = Operations.getOperation(request.getParameter("op")); if (operation.equals(Operations.CONFIGURATION_STATUS_GET)) { response.setContentType(TEXT_PLAIN); out.println(ControllerFactory.getFactory().createConfigurationController().getStatus()); } else if (!isUserLoggedIn(request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { ConfigurationController configurationController = ControllerFactory.getFactory() .createConfigurationController(); ScriptController scriptController = ControllerFactory.getFactory().createScriptController(); ObjectXMLSerializer serializer = new ObjectXMLSerializer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (operation.equals(Operations.CONFIGURATION_CHARSET_ENCODINGS_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(APPLICATION_XML); serializer.toXML(configurationController.getAvaiableCharsetEncodings(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_SERVER_SETTINGS_GET)) { response.setContentType(APPLICATION_XML); if (isUserAuthorized(request, null)) { serializer.toXML(configurationController.getServerSettings(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_SERVER_SETTINGS_SET)) { String settings = request.getParameter("data"); parameterMap.put("settings", settings); if (isUserAuthorized(request, parameterMap)) { configurationController.setServerSettings((ServerSettings) serializer.fromXML(settings)); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_UPDATE_SETTINGS_GET)) { response.setContentType(APPLICATION_XML); if (isUserAuthorized(request, null)) { serializer.toXML(configurationController.getUpdateSettings(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_UPDATE_SETTINGS_SET)) { String settings = request.getParameter("data"); parameterMap.put("settings", settings); if (isUserAuthorized(request, parameterMap)) { configurationController.setUpdateSettings((UpdateSettings) serializer.fromXML(settings)); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_ENCRYPTION_SETTINGS_GET)) { response.setContentType(APPLICATION_XML); if (isUserAuthorized(request, null)) { serializer.toXML(configurationController.getEncryptionSettings(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_GUID_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(TEXT_PLAIN); out.print(configurationController.generateGuid()); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_DATABASE_DRIVERS_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(APPLICATION_XML); serializer.toXML(configurationController.getDatabaseDrivers(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_VERSION_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(TEXT_PLAIN); out.print(configurationController.getServerVersion()); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_BUILD_DATE_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(TEXT_PLAIN); out.print(configurationController.getBuildDate()); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.SERVER_CONFIGURATION_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(APPLICATION_XML); serializer.toXML(configurationController.getServerConfiguration(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.SERVER_CONFIGURATION_SET)) { String serverConfiguration = request.getParameter("data"); parameterMap.put("data", serverConfiguration); if (isUserAuthorized(request, parameterMap)) { configurationController.setServerConfiguration( (ServerConfiguration) serializer.fromXML(serverConfiguration)); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_SERVER_ID_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(APPLICATION_XML); out.println(configurationController.getServerId()); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_SERVER_TIMEZONE_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(APPLICATION_XML); out.println(configurationController.getServerTimezone(request.getLocale())); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.GLOBAL_SCRIPT_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(APPLICATION_XML); serializer.toXML(scriptController.getGlobalScripts(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.GLOBAL_SCRIPT_SET)) { String scripts = request.getParameter("scripts"); parameterMap.put("scripts", scripts); if (isUserAuthorized(request, parameterMap)) { scriptController.setGlobalScripts((Map<String, String>) serializer.fromXML(scripts)); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONFIGURATION_PASSWORD_REQUIREMENTS_GET)) { if (isUserAuthorized(request, null)) { response.setContentType(APPLICATION_XML); serializer.toXML(configurationController.getPasswordRequirements(), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } } } catch (RuntimeIOException rio) { logger.debug(rio); } catch (Throwable t) { logger.error(ExceptionUtils.getStackTrace(t)); throw new ServletException(t); } }
From source file:uk.co.grahamcox.yui.YuiController.java
/** * Handle the boilerplate of getting the contents of a module * @param group the group of the module/* w w w .ja v a2 s. c o m*/ * @param module the module itself * @param filter the filter to apply * @param response the response to write to * @throws IOException if an error occurs */ private void getModule(String group, String module, Filter filter, HttpServletResponse response) throws IOException { String contents = moduleBuilder.getModuleFile(group, module); response.setContentType(CONTENT_TYPE); response.setCharacterEncoding(CHARSET); response.getWriter().write(contents); }