List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:com.flaptor.indextank.api.resources.Docs.java
/** * @see java.lang.Runnable#run()//from www.j a v a2 s .co m */ public void run() { IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api"); HttpServletResponse res = res(); HttpServletRequest req = req(); String characterEncoding = api.getCharacterEncoding(); try { req.setCharacterEncoding(characterEncoding); res.setCharacterEncoding(characterEncoding); res.setContentType("application/json"); } catch (UnsupportedEncodingException ignored) { } try { Object parse = JSONValue.parseWithException(req.getReader()); if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503 JSONObject jo = (JSONObject) parse; try { putDocument(api, jo); res.setStatus(200); return; } catch (Exception e) { e.printStackTrace(); if (LOG_ENABLED) LOG.severe(e.getMessage()); res.setStatus(400); print("Invalid or missing argument"); // TODO: descriptive error msg return; } } else if (parse instanceof JSONArray) { JSONArray statuses = new JSONArray(); JSONArray ja = (JSONArray) parse; if (!validateDocuments(ja)) { res.setStatus(400); print("Invalid or missing argument"); // TODO: descriptive error msg return; } boolean hasError = false; for (Object o : ja) { JSONObject jo = (JSONObject) o; JSONObject status = new JSONObject(); try { putDocument(api, jo); status.put("added", true); } catch (Exception e) { status.put("added", false); status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg hasError = true; } statuses.add(status); } print(statuses.toJSONString()); return; } } catch (IOException e) { if (LOG_ENABLED) LOG.severe("PUT doc, parse input " + e.getMessage()); } catch (ParseException e) { if (LOG_ENABLED) LOG.severe("PUT doc, parse input " + e.getMessage()); } catch (Exception e) { if (LOG_ENABLED) LOG.severe("PUT doc " + e.getMessage()); } res.setStatus(503); print("Service unavailable"); // TODO: descriptive error msg }
From source file:org.nsesa.editor.gwt.an.amendments.server.service.WordExportService.java
@Override public void export(AmendmentContainerDTO object, HttpServletResponse response) throws IOException { response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-Disposition", "attachment;filename=" + object.getAmendmentContainerID() + ".docx"); response.setCharacterEncoding("UTF8"); final String content = object.getBody(); final InputSource inputSource; inputSource = new InputSource(new StringReader(content)); try {//from www . j a v a2 s. com 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); configuration.getTemplate(template.getFile().getName()).process(root, sw); byte[] bytes = sw.toString().getBytes("utf-8"); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); response.setContentLength(sw.toString().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:de.unirostock.sems.cbarchive.web.servlet.DownloadServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set charset response.setCharacterEncoding(Fields.CHARSET); request.setCharacterEncoding(Fields.CHARSET); // login stuff UserManager user = null;/*from w w w.j a v a2 s .c o m*/ try { user = Tools.doLogin(request, response, false); } catch (CombineArchiveWebCriticalException e) { LOGGER.error(e, "Exception while getting User"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); } catch (CombineArchiveWebException e) { LOGGER.warn(e, "Exception while getting User"); response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } // splitting request URL String[] requestUrl = request.getRequestURI().substring(request.getContextPath().length()).split("/"); // check entry points if (requestUrl.length >= 5 && requestUrl[2].equals("archive")) { // request to download an archive from *any* workspace // without necessarily obtained this workspace before UserManager targetUser = null; if (requestUrl[3] != null && !requestUrl[3].isEmpty()) targetUser = new UserManager(requestUrl[3]); else return; if (requestUrl[4] != null && !requestUrl[4].isEmpty() && targetUser != null) downloadArchive(request, response, targetUser, URLDecoder.decode(requestUrl[4], Fields.CHARSET)); } else if (requestUrl.length >= 4 && requestUrl[2].equals("archive")) { // request to download an archive from the workspace if (requestUrl[3] != null && !requestUrl[3].isEmpty()) downloadArchive(request, response, user, URLDecoder.decode(requestUrl[3], Fields.CHARSET)); } else if (requestUrl.length >= 5 && requestUrl[2].equals("file")) { String archive = null; String file = null; if (requestUrl[3] != null && !requestUrl[3].isEmpty()) archive = URLDecoder.decode(requestUrl[3], Fields.CHARSET); else return; StringBuilder filePath = new StringBuilder(); for (int i = 4; i < requestUrl.length; i++) { if (requestUrl[i] != null && !requestUrl[i].isEmpty()) { filePath.append("/"); filePath.append(requestUrl[i]); } } // decode the name file = URLDecoder.decode(filePath.toString(), Fields.CHARSET); if (archive != null && !archive.isEmpty() && file != null && !file.isEmpty()) downloadFile(request, response, user, archive, file); } }
From source file:com.google.ie.web.view.GsonView.java
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { String jsonResult = getJsonString(filterModel(model)); // Write the result to response response.setContentType(contentType); response.setStatus(statusCode);/*w ww .j av a2 s . c o m*/ response.setCharacterEncoding(characterEncoding); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "0"); response.setHeader("Pragma", "No-cache"); if (isGzipInRequest(request)) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream out = null; try { out = new GZIPOutputStream(response.getOutputStream()); out.write(jsonResult.getBytes(characterEncoding)); } finally { if (out != null) { out.finish(); out.close(); } } } else { response.getWriter().print(jsonResult); } }
From source file:de.codecentric.boot.admin.zuul.filters.post.SendResponseFilter.java
private void writeResponse() throws Exception { RequestContext context = RequestContext.getCurrentContext(); // there is no body to send if (context.getResponseBody() == null && context.getResponseDataStream() == null) { return;// w w w .j ava 2 s . c om } HttpServletResponse servletResponse = context.getResponse(); if (servletResponse.getCharacterEncoding() == null) { // only set if not set servletResponse.setCharacterEncoding("UTF-8"); } OutputStream outStream = servletResponse.getOutputStream(); InputStream is = null; try { if (RequestContext.getCurrentContext().getResponseBody() != null) { String body = RequestContext.getCurrentContext().getResponseBody(); writeResponse(new ByteArrayInputStream(body.getBytes(servletResponse.getCharacterEncoding())), outStream); return; } boolean isGzipRequested = false; final String requestEncoding = context.getRequest().getHeader(ZuulHeaders.ACCEPT_ENCODING); if (requestEncoding != null && HTTPRequestUtils.getInstance().isGzipped(requestEncoding)) { isGzipRequested = true; } is = context.getResponseDataStream(); InputStream inputStream = is; if (is != null) { if (context.sendZuulResponse()) { // if origin response is gzipped, and client has not requested gzip, // decompress stream // before sending to client // else, stream gzip directly to client if (context.getResponseGZipped() && !isGzipRequested) { // If origin tell it's GZipped but the content is ZERO bytes, // don't try to uncompress final Long len = context.getOriginContentLength(); if (len == null || len > 0) { try { inputStream = new GZIPInputStream(is); } catch (java.util.zip.ZipException ex) { log.debug("gzip expected but not " + "received assuming unencoded response " + RequestContext.getCurrentContext().getRequest().getRequestURL() .toString()); inputStream = is; } } else { // Already done : inputStream = is; } } else if (context.getResponseGZipped() && isGzipRequested) { servletResponse.setHeader(ZuulHeaders.CONTENT_ENCODING, "gzip"); } writeResponse(inputStream, outStream); } } } finally { try { Object zuulResponse = RequestContext.getCurrentContext().get("zuulResponse"); if (zuulResponse instanceof Closeable) { ((Closeable) zuulResponse).close(); } outStream.flush(); // The container will close the stream for us } catch (IOException ex) { } } }
From source file:net.felsing.client_cert.GetCountries.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Locale defaultLanguage = Locale.ENGLISH; String bestLanguage = null;/* w ww . j a v a 2s .c o m*/ resp.setContentType("application/json; charset=UTF-8"); resp.setCharacterEncoding("UTF-8"); final String acceptLanguage = StringEscapeUtils.escapeJava(req.getHeader("Accept-Language")); List<Locale.LanguageRange> languageRanges = Locale.LanguageRange.parse(acceptLanguage); for (Locale.LanguageRange l : languageRanges) { try { if (bestLanguage == null) { Locale locale = new Locale(l.getRange().split("-")[0]); bestLanguage = locale.getISO3Language(); logger.debug("bestLanguage: " + bestLanguage); usedLocale = locale; } } catch (Exception e) { // do nothing } } if (bestLanguage == null) { logger.debug("No sufficient language found for " + acceptLanguage); bestLanguage = defaultLanguage.getISO3Language(); usedLocale = Locale.ENGLISH; } logger.debug("usedLocale: " + usedLocale.getISO3Language()); PrintWriter pw = resp.getWriter(); loadFromJson(context); List<Country> countriesList = new ArrayList<>(); for (JsonElement jsonElement : countries) { String cca2 = jsonElement.getAsJsonObject().get("cca2").toString().replaceAll("\\\"", ""); cca2 = cca2.replaceAll("\\\\", ""); Country countryItem = new Country(); try { countryItem.name = jsonElement.getAsJsonObject().get("name").getAsJsonObject().get(bestLanguage) .getAsJsonObject().get("common").getAsString(); } catch (NullPointerException e) { countryItem.name = jsonElement.getAsJsonObject().get("name_").getAsString(); } countryItem.cca2 = cca2; countriesList.add(countryItem); } Collator coll = Collator.getInstance(usedLocale); coll.setStrength(Collator.PRIMARY); Collections.sort(countriesList); pw.print(new Gson().toJson(countriesList)); pw.flush(); }
From source file:org.piraso.server.spring.web.PirasoServlet.java
private void writeResponse(HttpServletResponse response, String contentType, String str) throws IOException { PrintWriter out = response.getWriter(); try {//from w w w. j a va2 s . c om response.setContentType(contentType); response.setCharacterEncoding(ENCODING_UTF_8); out.write(str); out.flush(); } finally { out.close(); } }
From source file:org.springsource.ide.eclipse.boot.maven.analyzer.server.AetherialController.java
@RequestMapping(value = "/boot/mdgraph/{version:.*}"/*, produces = {"text/plain; charset=UTF-8"}*/) public void getManagedDependencyGraph(@PathVariable("version") String bootVersion, HttpServletResponse resp) throws Exception { Artifact parentPom = Defaults.parentPom(bootVersion); CollectResult dgraphResult = aether.getManagedDependencyGraph(parentPom); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); OutputStream out = resp.getOutputStream(); PrintStream pout = new PrintStream(out, true, "UTF-8"); ConsoleDependencyGraphDumper dgraphDumper = new ConsoleDependencyGraphDumper(pout); dgraphResult.getRoot().accept(dgraphDumper); }
From source file:controller.productServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String proimage = ""; String nameProduct = ""; double priceProduct = 0; String desProduct = ""; String colorProduct = ""; int years = 0; int catId = 0; int proid = 0; String command = ""; if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();/*from w w w .j a va2 s . com*/ return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { proimage = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + proimage; File storeFile = new File(filePath); System.out.println(proimage); item.write(storeFile); } else if (item.getFieldName().equals("name")) { nameProduct = item.getString(); } else if (item.getFieldName().equals("price")) { priceProduct = Double.parseDouble(item.getString()); } else if (item.getFieldName().equals("description")) { desProduct = item.getString(); System.out.println(desProduct); } else if (item.getFieldName().equals("color")) { colorProduct = item.getString(); } else if (item.getFieldName().equals("years")) { years = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("catogory_name")) { catId = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("command")) { command = item.getString(); } else if (item.getFieldName().equals("proid")) { proid = Integer.parseInt(item.getString()); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String url = "", error = ""; if (nameProduct.equals("")) { error = "Vui lng nhp tn danh mc!"; request.setAttribute("error", error); } try { if (error.length() == 0) { ProductEntity p = new ProductEntity(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years); switch (command) { case "insert": prod.insertProduct(p); url = "/java/admin/ql-product.jsp"; break; case "update": prod.updateProduct(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years, proid); url = "/java/admin/ql-product.jsp"; break; } } else { url = "/java/admin/add-product.jsp"; } } catch (Exception e) { } response.sendRedirect(url); }
From source file:net.duckling.ddl.web.controller.pan.WopiController.java
public void sendPreviewDoc(String skey, HttpServletRequest request, HttpServletResponse response) { OutputStream os = null;//w ww .j av a 2s.c o m long p0 = System.currentTimeMillis(); try { FileInfo info = (FileInfo) cacheService.get(skey); response.setCharacterEncoding("utf-8"); response.setContentLength((int) info.getSize()); response.setContentType("application/x-download"); String headerValue = ResponseHeaderUtils.buildResponseHeader(request, info.getFileName(), true); response.setHeader("Content-Disposition", headerValue); response.setHeader("Content-Length", info.getSize() + ""); os = response.getOutputStream(); if (StringUtils.isEmpty(info.getPanAcl().getUmtToken())) { //pan??? panService.getShareContent(info.getRemotePath(), null, os); } else { panService.download(info.getPanAcl(), info.getRemotePath(), info.getVersion(), os); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MeePoException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(os); long p1 = System.currentTimeMillis(); System.out.println("Send document use time " + (p1 - p0)); } }