List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java
@Override protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta) throws ServletException, IOException { String tipo = requisicao.getContentType(); if (tipo == null || tipo.isEmpty()) tipo = "text/plain"; String codificacao = requisicao.getCharacterEncoding(); if (codificacao == null || codificacao.isEmpty()) codificacao = "UTF-8"; resposta.setCharacterEncoding(codificacao); PrintWriter saida = resposta.getWriter(); try {/*from ww w.j a v a 2 s .c o m*/ JSON json; if (tipo.contains("json")) { json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao)); } else { json = new JSON(); } Enumeration<String> parametros = requisicao.getParameterNames(); while (parametros.hasMoreElements()) { String chave = parametros.nextElement(); String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao); json.put(chave, valor); } if (tipo.contains("multipart")) { Collection<Part> arquivos = requisicao.getParts(); if (!arquivos.isEmpty()) { File diretorio = new File(uxiAmarelo.getDiretorio()); if (!diretorio.isAbsolute()) { diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator + uxiAmarelo.getDiretorio()); } if (!diretorio.exists()) diretorio.mkdirs(); String diretorioStr = diretorio.getAbsolutePath(); String url = uxiAmarelo.getDiretorioURL(); if (uxiAmarelo.isDiretorioURLRelativo()) { String url_esquema = requisicao.getScheme(); String url_servidor = requisicao.getServerName(); int url_porta = requisicao.getServerPort(); String url_contexto = requisicao.getContextPath(); url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url; } if (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 1); } Map<String, List<JSON>> mapa_arquivos = new HashMap<>(); for (Part arquivo : arquivos) { String chave = arquivo.getName(); String nome_original = getNome(arquivo, codificacao); String nome = nome_original; if (nome == null || nome.isEmpty()) { try (InputStream is = arquivo.getInputStream()) { String valor = IOUtils.toString(is, codificacao); valor = URLDecoder.decode(valor, codificacao); json.put(chave, valor); continue; } } if (uxiAmarelo.getArquivoNome().equals("uuid")) { nome = UUID.randomUUID().toString(); } while (new File(diretorioStr + File.separator + nome).exists()) { nome = UUID.randomUUID().toString(); } arquivo.write(diretorioStr + File.separator + nome); List<JSON> lista = mapa_arquivos.get(chave); if (lista == null) { lista = new LinkedList<>(); mapa_arquivos.put(chave, lista); } lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome)); } for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) { List<JSON> lista = entrada.getValue(); if (lista.size() > 1) { json.put(entrada.getKey(), lista); } else { json.put(entrada.getKey(), lista.get(0)); } } } } String copaiba = (String) json.remove("copaiba"); if (StringUtil.tamanho(copaiba) == 0) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String[] copaibaParam = copaiba.split("@"); if (copaibaParam.length != 3) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String comando = (String) json.remove("uxicmd"); if (StringUtil.tamanho(comando) == 0) comando = null; if (uxiAmarelo.isCookieEnviar()) { Cookie[] cookies = requisicao.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String nome = cookie.getName(); if (uxiAmarelo.cookieBloqueado(nome)) continue; if (!json.has(nome)) { try { json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { json.put(nome, cookie.getValue()); } } } } } if (uxiAmarelo.isEncapsulamentoAutomatico()) { final String sepstr = uxiAmarelo.getEncapsulamentoSeparador(); final char sep0 = sepstr.charAt(0); for (String chave : new HashSet<>(json.keySet())) { if (chave.indexOf(sep0) == -1) continue; String[] caminho = chave.split(sepstr); if (caminho.length > 1) { Util.encapsular(caminho, json.remove(chave), json); } } } String resultado; if (comando == null) { try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) { resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]); if (resultado == null) resultado = ""; } } else if (comando.equals("voltar")) { resultado = json.toString(); comando = null; } else { resultado = ""; } if (comando == null) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("application/json"); saida.write(resultado); } else if (comando.startsWith("redirecionar")) { resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado)); } else if (comando.startsWith("base64")) { String url = comando.substring("base64.".length()); resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8"))); } else if (comando.startsWith("html_url")) { HttpURLConnection con = (HttpURLConnection) new URL( Util.obterStringDeJSON("html_url", comando, resultado)).openConnection(); con.setRequestProperty("User-Agent", "Uxi-amarelo"); if (con.getResponseCode() != HttpServletResponse.SC_OK) throw new IOException("HTTP = " + con.getResponseCode()); resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); try (InputStream is = con.getInputStream()) { saida.write(IOUtils.toString(is)); } con.disconnect(); } else if (comando.startsWith("html")) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); saida.write(Util.obterStringDeJSON("html", comando, resultado)); } else { throw new IllegalArgumentException(comando); } } catch (Exception e) { resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resposta.setContentType("application/json"); saida.write(Util.gerarRespostaErro(e).toString()); } saida.flush(); }
From source file:net.sourceforge.subsonic.controller.JAXBWriter.java
public void writeResponse(HttpServletRequest request, HttpServletResponse httpResponse, Response jaxbResponse) throws Exception { String format = getStringParameter(request, "f", "xml"); String jsonpCallback = request.getParameter("callback"); boolean json = "json".equals(format); boolean jsonp = "jsonp".equals(format) && jsonpCallback != null; Marshaller marshaller;//from w ww. j a va2 s .c o m if (json) { marshaller = createJsonMarshaller(); httpResponse.setContentType("application/json"); } else if (jsonp) { marshaller = createJsonMarshaller(); httpResponse.setContentType("text/javascript"); } else { marshaller = createXmlMarshaller(); httpResponse.setContentType("text/xml"); } httpResponse.setCharacterEncoding(StringUtil.ENCODING_UTF8); try { StringWriter writer = new StringWriter(); if (jsonp) { writer.append(jsonpCallback).append('('); } marshaller.marshal(new ObjectFactory().createSubsonicResponse(jaxbResponse), writer); if (jsonp) { writer.append(");"); } httpResponse.getWriter().append(writer.getBuffer()); } catch (Exception x) { LOG.error("Failed to marshal JAXB", x); throw x; } }
From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java
public void writeBodyResponseAsJson(HttpServletResponse response, org.json.JSONObject data, Map<String, String> errors) { try {// w w w .ja v a 2s. c o m 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:io.getlime.security.powerauth.app.server.service.controller.RESTResponseExceptionResolver.java
@Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { try {//from w ww . ja va 2 s . com // Build the error list RESTErrorModel error = new RESTErrorModel(); error.setCode("ERR_SPRING_JAVA"); error.setMessage(exception.getMessage()); error.setLocalizedMessage(exception.getLocalizedMessage()); List<RESTErrorModel> errorList = new LinkedList<>(); errorList.add(error); // Prepare the response RESTResponseWrapper<List<RESTErrorModel>> errorResponse = new RESTResponseWrapper<>("ERROR", errorList); // Write the response in JSON and send it ObjectMapper mapper = new ObjectMapper(); String responseString = mapper.writeValueAsString(errorResponse); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getOutputStream().print(responseString); response.flushBuffer(); } catch (IOException e) { // Response object does have an output stream here } return new ModelAndView(); }
From source file:com.zb.app.common.interceptor.ExportFileAnnotationInterceptor.java
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (handler == null || response == null) { return;/*from w ww . ja v a2 s .c o m*/ } HandlerMethod hm = (HandlerMethod) handler; ExportWordFile exportWordFile = hm.getMethodAnnotation(ExportWordFile.class); // word, if (exportWordFile != null) { String wordName = exportWordFile.value(); if (StringUtils.isEmpty(wordName)) { return; } wordName = new String(wordName.getBytes(), "ISO8859-1"); String contentDis = "attachment;filename=" + wordName + ".doc"; response.setHeader("content-disposition", contentDis); response.setContentType("application/msword;"); response.setCharacterEncoding("UTF-8"); } ExportExcelFile exportExcelFile = hm.getMethodAnnotation(ExportExcelFile.class); // excel, if (exportExcelFile != null) { String xlsName = exportExcelFile.value(); if (StringUtils.isEmpty(xlsName)) { return; } xlsName = new String(xlsName.getBytes(), "UTF-8"); List<?> list = (List<?>) modelAndView.getModel().get("list"); String[] head = (String[]) modelAndView.getModel().get("head"); modelAndView.clear(); HSSFWorkbook workbook = ExcelUtils.defBuildExcel(list, xlsName, head); if (workbook == null) { try { response.getOutputStream().print("Not conform to the requirements of data"); } catch (IOException e) { logger.error(e.getMessage(), e); } return; } response.setHeader("content-disposition", "attachment;filename=" + xlsName + ".xls"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("UTF-8"); // response OutputStream os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); } }
From source file:com.googlesource.gerrit.plugins.github.velocity.VelocityViewServlet.java
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String servletPath = req.getPathInfo(); NextPage nextPage = (NextPage) req.getAttribute("destUrl"); String destUrl = null;// www. j a v a2s .c o m if (nextPage != null && !nextPage.uri.startsWith("/")) { destUrl = servletPath.substring(0, servletPath.lastIndexOf("/")) + "/" + nextPage.uri; } String pathInfo = Objects.firstNonNull(destUrl, servletPath); if (!pathInfo.startsWith(STATIC_PREFIX)) { resp.sendError(HttpStatus.SC_NOT_FOUND); } try { Template template = velocityRuntime.getTemplate(pathInfo, "UTF-8"); VelocityContext context = initVelocityModel(req).getContext(); context.put("request", req); resp.setHeader("content-type", "text/html"); resp.setCharacterEncoding(StandardCharsets.UTF_8.name()); template.merge(context, resp.getWriter()); } catch (ResourceNotFoundException e) { log.error("Cannot load velocity template " + pathInfo, e); resp.sendError(HttpStatus.SC_NOT_FOUND); } catch (Exception e) { log.error("Error executing velocity template " + pathInfo, e); resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage()); } }
From source file:com.azaptree.services.command.http.handler.WebXmlRequestCommandServiceHandler.java
private void generateCommandXSD(final String target, final HttpServletResponse response) throws IOException { final CommandKey commandKey = targetUriCommandKeyMap.get(toCommandUriTarget(target)); final CommandCatalog catalog = commandService.getCommandCatalog(commandKey.getCatalogName()); @SuppressWarnings("rawtypes") final WebXmlRequestCommand command = (WebXmlRequestCommand) catalog.getCommand(commandKey.getCommandName()); if (!command.hasXmlSchema()) { response.setStatus(HttpStatus.NO_CONTENT_204); return;/*from w w w . j a v a 2 s . c om*/ } response.setStatus(HttpStatus.OK_200); response.setContentType("application/xml"); response.setCharacterEncoding("UTF-8"); command.generateSchema(response.getOutputStream()); }
From source file:com.panet.imeta.www.GetTransStatusServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!request.getContextPath().equals(CONTEXT_PATH)) return;//from w ww . j ava2 s . c o m if (log.isDebug()) log.logDebug(toString(), Messages.getString("TransStatusServlet.Log.TransStatusRequested")); String transName = request.getParameter("name"); boolean useXML = "Y".equalsIgnoreCase(request.getParameter("xml")); response.setStatus(HttpServletResponse.SC_OK); if (useXML) { response.setContentType("text/xml"); response.setCharacterEncoding(Const.XML_ENCODING); } else { response.setContentType("text/html"); } PrintWriter out = response.getWriter(); Trans trans = transformationMap.getTransformation(transName); if (trans != null) { String status = trans.getStatus(); if (useXML) { response.setContentType("text/xml"); response.setCharacterEncoding(Const.XML_ENCODING); out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING)); SlaveServerTransStatus transStatus = new SlaveServerTransStatus(transName, status); for (int i = 0; i < trans.nrSteps(); i++) { BaseStep baseStep = trans.getRunThread(i); if ((baseStep.isAlive()) || baseStep.getStatus() != StepDataInterface.STATUS_EMPTY) { StepStatus stepStatus = new StepStatus(baseStep); transStatus.getStepStatusList().add(stepStatus); } } Log4jStringAppender appender = (Log4jStringAppender) transformationMap.getAppender(transName); if (appender != null) { // The log can be quite large at times, we are going to put a base64 encoding around a compressed stream // of bytes to handle this one. ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); gzos.write(appender.getBuffer().toString().getBytes()); gzos.close(); String loggingString = new String(Base64.encodeBase64(baos.toByteArray())); transStatus.setLoggingString(loggingString); } // Also set the result object... // transStatus.setResult(trans.getResult()); // Is the transformation paused? // transStatus.setPaused(trans.isPaused()); // Send the result back as XML // out.println(transStatus.getXML()); } else { response.setContentType("text/html"); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>" + Messages.getString("TransStatusServlet.KettleTransStatus") + "</TITLE>"); out.println("<META http-equiv=\"Refresh\" content=\"10;url=/kettle/transStatus?name=" + URLEncoder.encode(transName, "UTF-8") + "\">"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>" + Messages.getString("TransStatusServlet.TopTransStatus", transName) + "</H1>"); try { out.println("<table border=\"1\">"); out.print("<tr> <th>" + Messages.getString("TransStatusServlet.TransName") + "</th> <th>" + Messages.getString("TransStatusServlet.TransStatus") + "</th> </tr>"); out.print("<tr>"); out.print("<td>" + transName + "</td>"); out.print("<td>" + status + "</td>"); out.print("</tr>"); out.print("</table>"); out.print("<p>"); if ((trans.isFinished() && trans.isRunning()) || (!trans.isRunning() && !trans.isPreparing() && !trans.isInitializing())) { out.print("<a href=\"/kettle/startTrans?name=" + URLEncoder.encode(transName, "UTF-8") + "\">" + Messages.getString("TransStatusServlet.StartTrans") + "</a>"); out.print("<p>"); out.print("<a href=\"/kettle/prepareExec?name=" + URLEncoder.encode(transName, "UTF-8") + "\">" + Messages.getString("TransStatusServlet.PrepareTrans") + "</a><br>"); //out.print("<a href=\"/kettle/startExec?name="+URLEncoder.encode(transName, "UTF-8")+"\">" + Messages.getString("TransStatusServlet.StartTrans") + "</a><p>"); } else if (trans.isRunning()) { out.print("<a href=\"/kettle/pauseTrans?name=" + URLEncoder.encode(transName, "UTF-8") + "\">" + Messages.getString("PauseStatusServlet.PauseResumeTrans") + "</a><br>"); out.print("<a href=\"/kettle/stopTrans?name=" + URLEncoder.encode(transName, "UTF-8") + "\">" + Messages.getString("TransStatusServlet.StopTrans") + "</a>"); out.print("<p>"); } out.print("<a href=\"/kettle/cleanupTrans?name=" + URLEncoder.encode(transName, "UTF-8") + "\">" + Messages.getString("TransStatusServlet.CleanupTrans") + "</a>"); out.print("<p>"); out.println("<table border=\"1\">"); out.print("<tr> <th>" + Messages.getString("TransStatusServlet.Stepname") + "</th> <th>" + Messages.getString("TransStatusServlet.CopyNr") + "</th> <th>" + Messages.getString("TransStatusServlet.Read") + "</th> <th>" + Messages.getString("TransStatusServlet.Written") + "</th> <th>" + Messages.getString("TransStatusServlet.Input") + "</th> <th>" + Messages.getString("TransStatusServlet.Output") + "</th> " + "<th>" + Messages.getString("TransStatusServlet.Updated") + "</th> <th>" + Messages.getString("TransStatusServlet.Rejected") + "</th> <th>" + Messages.getString("TransStatusServlet.Errors") + "</th> <th>" + Messages.getString("TransStatusServlet.Active") + "</th> <th>" + Messages.getString("TransStatusServlet.Time") + "</th> " + "<th>" + Messages.getString("TransStatusServlet.Speed") + "</th> <th>" + Messages.getString("TransStatusServlet.prinout") + "</th> </tr>"); for (int i = 0; i < trans.nrSteps(); i++) { BaseStep baseStep = trans.getRunThread(i); if ((baseStep.isAlive()) || baseStep.getStatus() != StepDataInterface.STATUS_EMPTY) { StepStatus stepStatus = new StepStatus(baseStep); out.print(stepStatus.getHTMLTableRow()); } } out.println("</table>"); out.println("<p>"); out.print("<a href=\"/kettle/transStatus/?name=" + URLEncoder.encode(transName, "UTF-8") + "&xml=y\">" + Messages.getString("TransStatusServlet.ShowAsXml") + "</a><br>"); out.print("<a href=\"/kettle/status\">" + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><br>"); out.print("<p><a href=\"/kettle/transStatus?name=" + URLEncoder.encode(transName, "UTF-8") + "\">" + Messages.getString("TransStatusServlet.Refresh") + "</a>"); // Put the logging below that. Log4jStringAppender appender = (Log4jStringAppender) transformationMap.getAppender(transName); if (appender != null) { out.println("<p>"); /* out.println("<pre>"); out.println(appender.getBuffer().toString()); out.println("</pre>"); */ out.println( "<textarea id=\"translog\" cols=\"120\" rows=\"20\" wrap=\"off\" name=\"Transformation log\" readonly=\"readonly\">" + appender.getBuffer().toString() + "</textarea>"); out.println("<script type=\"text/javascript\"> "); out.println(" translog.scrollTop=translog.scrollHeight; "); out.println("</script> "); out.println("<p>"); } } catch (Exception ex) { out.println("<p>"); out.println("<pre>"); ex.printStackTrace(out); out.println("</pre>"); } out.println("<p>"); out.println("</BODY>"); out.println("</HTML>"); } } else { if (useXML) { out.println(new WebResult(WebResult.STRING_ERROR, Messages.getString("TransStatusServlet.Log.CoundNotFindSpecTrans", transName))); } else { out.println("<H1>" + Messages.getString("TransStatusServlet.Log.CoundNotFindTrans", transName) + "</H1>"); out.println("<a href=\"/kettle/status\">" + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><p>"); } } }
From source file:cn.webwheel.DefaultMain.java
/** * Wrap exception to a json object and return it to client. * <p>/*from ww w .j a v a2 s . c om*/ * <b>json object format:</b><br/> * <p><blockquote><pre> * { * "msg": "the exception's message", * "stackTrace":[ * "exception's stack trace1", * "exception's stack trace2", * "exception's stack trace3", * .... * ] * } * </pre></blockquote></p> */ public Object executeActionError(WebContext ctx, ActionInfo ai, Object action, Throwable e) throws Throwable { if (e instanceof LogicException) { return ((LogicException) e).getResult(); } Logger.getLogger(DefaultMain.class.getName()).log(Level.SEVERE, "action execution error", e); StringBuilder sb = new StringBuilder(); sb.append("{\n"); String s; try { s = JsonResult.objectMapper.writeValueAsString(e.toString()); } catch (IOException e1) { s = "\"" + e.toString().replace("\"", "'") + "\""; } sb.append(" \"msg\" : " + s + ",\n"); sb.append(" \"stackTrace\" : ["); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String[] ss = sw.toString().split("\r\n"); for (int i = 1; i < ss.length; i++) { if (sb.charAt(sb.length() - 1) != '[') { sb.append(','); } sb.append("\n ").append(JsonResult.objectMapper.writeValueAsString(ss[i])); } sb.append("\n ]\n"); sb.append("}"); HttpServletResponse response = ctx.getResponse(); if (JsonResult.defWrapMultipart && ServletFileUpload.isMultipartContent(ctx.getRequest()) && !"XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))) { response.setContentType("text/html"); sb.insert(0, "<textarea>\n"); sb.append("\n</textarea>"); } else { response.setContentType("application/json"); } response.setCharacterEncoding("utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "-1"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(sb.toString()); return EmptyResult.inst; }