List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:net.duckling.ddl.web.controller.UploadImgController.java
@RequestMapping public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException { Site site = VWBContext.findSite(request); FileVersion attachItem = new FileVersion(); response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); ////ww w . j ava 2 s . c o m String url = request.getParameter("url"); HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(url); String fakeReferer = getFakeReferer(url);//?? if (fakeReferer != null) { String thisReferer = request.getHeader("Referer"); if (thisReferer.contains(fakeReferer)) {//???? response.getWriter().write(getReturnXml(site, 0, "??", attachItem)); response.flushBuffer(); return; } getMethod.setRequestHeader("Referer", fakeReferer); } client.executeMethod(getMethod); //? try { attachItem = uploadImg(getMethod, request); } catch (NoEnoughSpaceException e) { JSONObject j = new JSONObject(); j.put("result", false); j.put("message", e.getMessage()); j.put("error", e.getMessage()); JsonUtil.writeJSONObject(response, j); return; } // response.getWriter().write(""); response.getWriter().write(getReturnXml(site, 1, "????", attachItem)); response.flushBuffer(); }
From source file:com.flaptor.indextank.api.resources.Search.java
/** * @see java.lang.Runnable#run()/*w ww.j a v a 2 s. c o m*/ */ public void run() { IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api"); HttpServletResponse res = res(); String characterEncoding = api.getCharacterEncoding(); try { req().setCharacterEncoding(characterEncoding); res.setCharacterEncoding(characterEncoding); res.setContentType("application/json"); } catch (UnsupportedEncodingException ignored) { } String q = params("q"); String fetchVariables = params("fetch_variables"); String fetchCategories = params("fetch_categories"); String fetch = params("fetch"); String snippet = params("snippet"); int start = QueryHelper.parseIntParam(params("start"), 0); int len = QueryHelper.parseIntParam(params("len"), 10); int function = QueryHelper.parseIntParam(params("function"), 0); Map<Integer, Double> vars = Maps.newHashMap(); List<CategoryFilter> facetFilters = Lists.newArrayList(); List<RangeFilter> variableRangeFilters = Lists.newArrayList(); List<RangeFilter> functionRangeFilters = Lists.newArrayList(); Map<String, String> extras = createExtraParameters(fetch, snippet, fetchVariables, fetchCategories); try { long t0 = System.currentTimeMillis(); SearchResults results = api.search(q, start, len, function, vars, facetFilters, variableRangeFilters, functionRangeFilters, extras); long t1 = System.currentTimeMillis(); double searchTime = (t1 - t0) / 1000; int matches = results.getMatches(); Map<String, Map<String, Integer>> facets = toFacets(results.getFacets()); String didYouMean = results.getDidYouMean(); JSONArray ja = new JSONArray(); for (SearchResult result : results.getResults()) { addResult(ja, result); } JSONObject jo = createResponse(q, searchTime, ja, matches, facets, didYouMean); print(jo.toJSONString()); return; } catch (IndexEngineApiException e) { e.printStackTrace(); } res.setStatus(503); print("Service unavailable"); // TODO: descriptive error msg }
From source file:com.enonic.cms.web.filter.CharacterEncodingFilter.java
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (request.getCharacterEncoding() == null) { request.setCharacterEncoding(encoding); }/*from ww w. j av a 2s. com*/ final String forcedCharset = request.getParameter("_charset"); if (!StringUtils.isBlank(forcedCharset)) { response.setCharacterEncoding(forcedCharset); } else { response.setCharacterEncoding(encoding); } filterChain.doFilter(request, response); }
From source file:in.raster.oviyam.servlet.Validator.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); /*AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal(); String loginId=principal.getName();*/ /*??*///from w w w . java 2 s . co m String pid = (String) request.getParameter("PatientID").trim(); if (pid == null || "".equals(pid)) { out.println("??!"); out.close(); return; } /*?????*/ String r = dataAccess.getReportAddress(pid); /*?dcmpacs?*/ //String r=dataAccess.addDicom("x"); /*?*/ Boolean a = dataAccess.checsIsExist(pid); if (!a) { out.println("?!"); out.close(); return; } /*????*/ //boolean b=dataAccess.checkCheckId(loginId,pid); //if(!b)return; /**/ /*PacsQueryLogModel pqlm = new PacsQueryLogModel(); pqlm.setApplicationId(pid); pqlm.setDoctorId(loginId); dataAccess.addPacsLog(pqlm);*/ AE ae; ServletContext servletContext = getServletContext(); ServerConfiguration serverConfiguration; EchoService echoService; String agree = request.getParameter("agree"); if (agree != null && agree.equals("agree")) { Cookie agreeCookie = new Cookie("agree", "agree"); agreeCookie.setMaxAge(60 * 60 * 24 * 365); response.addCookie(agreeCookie); } try { ae = new AE(); //assigns the serverConfiguration instance. serverConfiguration = ae.getServerConfiguration(); /* * writes the serverConfiguration instance in the servletContext (application scope). * So all the SERVLET classes and JSP pages can access the serverConfig attribute. * User can use either <jsp:useBean> tag or ${applicationScope.serverConfig} EL * to access the serverConfig attribute. From SERVLET classes the User can use * the getServletContext().getAttribute("serverConfig") to access the serverConfiguration attribute. */ servletContext.setAttribute("serverConfig", serverConfiguration); echoService = new EchoService(); echoService.checkEcho(); /*If the status of EchoService is failed then the request will be forwarded to * EchoFailed.jsp. Otherwise, request is forwarded to oviyam7.jsp * */ if (echoService.getStatus().equals("Echo failed")) { /* * writes the echoURL(dcmProtocol://aeTitle@hostName:port) attribute in request instance. * and forwards the request and response object to EchoFailed.jsp . * echoFailed attribute can be accessed through either ${request.echoURL} or * <% request.getAttribute("echoURL")%> */ request.setAttribute("echoURL", ae.toString()); request.getRequestDispatcher("EchoFailed.jsp").forward(request, response); } else { // forwards the request and response to oviyam7.jsp String studyUID = request.getParameter("studyUID"); String seriesUID = request.getParameter("seriesUID"); String patientID = request.getParameter("patientID"); if (studyUID != null && studyUID.length() <= 0) { request.setAttribute("param", "studyUID"); request.getRequestDispatcher("InvalidParam.jsp").forward(request, response); log.error("Invalid studyUID parameter for Oviyam."); } else if (seriesUID != null && seriesUID.length() <= 0) { request.setAttribute("param", "seriesUID"); request.getRequestDispatcher("InvalidParam.jsp").forward(request, response); log.error("Invalid seriesUID parameter for Oviyam."); } else if (patientID != null && patientID.length() <= 0) { request.setAttribute("param", "patientID"); request.getRequestDispatcher("InvalidParam.jsp").forward(request, response); log.error("Invalid patientID parameter for Oviyam."); } else { request.getRequestDispatcher("oviyam7.jsp").forward(request, response); } } } catch (Exception e) { log.error(e.getMessage()); } }
From source file:org.primeframework.mvc.action.result.JSONResultTest.java
@Test(dataProvider = "httpMethod") public void all(HTTPMethod httpMethod) throws IOException, ServletException { UserField userField = new UserField(); userField.addresses.put("work", new AddressField()); userField.addresses.get("work").age = 100; userField.addresses.get("work").city = "Denver"; userField.addresses.get("work").state = "Colorado"; userField.addresses.get("work").zipcode = "80202"; userField.addresses.put("home", new AddressField()); userField.addresses.get("home").age = 100; userField.addresses.get("home").city = "Broomfield"; userField.addresses.get("home").state = "Colorado"; userField.addresses.get("home").zipcode = "80023"; userField.active = true;//from w w w .j av a 2s .c o m userField.age = 37; userField.favoriteMonth = 5; userField.favoriteYear = 1976; userField.ids.put(0, 1); userField.ids.put(1, 2); userField.lifeStory = "Hello world"; userField.locale = Locale.US; userField.securityQuestions = new String[] { "one", "two", "three", "four" }; userField.siblings.add(new UserField("Brett")); userField.siblings.add(new UserField("Beth")); userField.type = UserType.COOL; Post action = new Post(); ExpressionEvaluator ee = createStrictMock(ExpressionEvaluator.class); expect(ee.getValue("user", action)).andReturn(userField); replay(ee); MockServletOutputStream sos = new MockServletOutputStream(); HttpServletResponse response = createStrictMock(HttpServletResponse.class); response.setStatus(200); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.setContentLength(462); if (httpMethod == HTTPMethod.GET) { expect(response.getOutputStream()).andReturn(sos); } replay(response); Map<Class<?>, Object> additionalConfiguration = new HashMap<>(); additionalConfiguration.put(JacksonActionConfiguration.class, new JacksonActionConfiguration(null, null, "user")); ActionConfiguration config = new ActionConfiguration(Post.class, null, null, null, null, null, null, null, null, null, null, null, null, additionalConfiguration, null); ActionInvocationStore store = createStrictMock(ActionInvocationStore.class); expect(store.getCurrent()).andReturn(new ActionInvocation(action, new ExecuteMethodConfiguration(httpMethod, null, null), "/foo", "", config)); replay(store); MessageStore messageStore = createStrictMock(MessageStore.class); expect(messageStore.get(MessageScope.REQUEST)).andReturn(new ArrayList<>()); replay(messageStore); JSON annotation = new JSONResultTest.JSONImpl("success", 200); JSONResult result = new JSONResult(ee, store, messageStore, objectMapper, response); result.execute(annotation); String expected = "{" + " \"active\":true," + " \"addresses\":{" + " \"home\":{" + " \"age\":100," + " \"city\":\"Broomfield\"," + " \"state\":\"Colorado\"," + " \"zipcode\":\"80023\"" + " }," + " \"work\":{" + " \"age\":100," + " \"city\":\"Denver\"," + " \"state\":\"Colorado\"," + " \"zipcode\":\"80202\"" + " }" + " }," + " \"age\":37," + " \"bar\":false," + " \"favoriteMonth\":5," + " \"favoriteYear\":1976," + " \"ids\":{" + " \"0\":1," + " \"1\":2" + " }," + " \"lifeStory\":\"Hello world\"," + " \"locale\":\"en_US\"," + " \"securityQuestions\":[\"one\",\"two\",\"three\",\"four\"]," + " \"siblings\":[{" + " \"active\":false," + " \"bar\":false," + " \"name\":\"Brett\"" + " },{" + " \"active\":false," + " \"bar\":false," + " \"name\":\"Beth\"" + " }]," + " \"type\":\"COOL\"" + "}"; assertEquals(sos.toString(), httpMethod == HTTPMethod.GET ? expected.replace(" ", "") : ""); // Un-indent verify(ee, messageStore, response); }
From source file:controller.servlet.PostServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request// w w w. j a va 2s.co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String action = request.getParameter(Constants.ACTION); if (action != null) { switch (action) { case "new-topic": requestNewPost(request, response); break; } } }
From source file:com.google.code.pathlet.web.PathletAjaxProcessor.java
private void setCharset(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { request.setCharacterEncoding(requestCharset); if (responseSetCharacterEncodingAvailable) { response.setCharacterEncoding(responseCharset); }//from w w w. j a va 2 s .co m }
From source file:com.mirth.connect.server.servlets.ExtensionServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // MIRTH-1745 response.setCharacterEncoding("UTF-8"); if (!isUserLoggedIn(request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else {//from w ww . j av a 2s . co m try { ExtensionController extensionController = ControllerFactory.getFactory() .createExtensionController(); ObjectXMLSerializer serializer = new ObjectXMLSerializer(); PrintWriter out = response.getWriter(); FileItem multiPartFileItem = null; Operation operation = null; Map<String, Object> parameterMap = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(request)) { Map<String, String> multipartParameters = new HashMap<String, String>(); File installTempDir = new File(ExtensionController.getExtensionsPath(), "install_temp"); if (!installTempDir.exists()) { installTempDir.mkdir(); } // we need to load properties from the multipart data DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(installTempDir); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { multipartParameters.put(item.getFieldName(), item.getString()); } else { // only supports a single file multiPartFileItem = item; } } operation = Operations.getOperation(multipartParameters.get("op")); } else { operation = Operations.getOperation(request.getParameter("op")); } if (operation.equals(Operations.PLUGIN_PROPERTIES_GET)) { String pluginName = request.getParameter("name"); if (isUserAuthorizedForExtension(request, pluginName, operation.getName(), null)) { response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.getPluginProperties(pluginName), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.PLUGIN_PROPERTIES_SET)) { String pluginName = request.getParameter("name"); if (isUserAuthorizedForExtension(request, pluginName, operation.getName(), null)) { Properties properties = (Properties) serializer.fromXML(request.getParameter("properties")); extensionController.setPluginProperties(pluginName, properties); extensionController.updatePluginProperties(pluginName, properties); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.PLUGIN_METADATA_GET)) { response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.getPluginMetaData(), out); } else if (operation.equals(Operations.EXTENSION_SET_ENABLED)) { String pluginName = request.getParameter("name"); boolean enabled = BooleanUtils.toBoolean(request.getParameter("enabled")); parameterMap.put("extension", pluginName); parameterMap.put("enabled", enabled); if (isUserAuthorized(request, parameterMap)) { extensionController.setExtensionEnabled(pluginName, enabled); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONNECTOR_METADATA_GET)) { response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.getConnectorMetaData(), out); } else if (operation.equals(Operations.EXTENSION_IS_ENABLED)) { String extensionName = request.getParameter("name"); response.setContentType(TEXT_PLAIN); out.print(extensionController.isExtensionEnabled(extensionName)); } else if (operation.equals(Operations.PLUGIN_SERVICE_INVOKE)) { String pluginName = request.getParameter("name"); String method = request.getParameter("method"); Object object = serializer.fromXML(request.getParameter("object")); String sessionId = request.getSession().getId(); if (isUserAuthorizedForExtension(request, pluginName, method, null)) { serializer.toXML( extensionController.invokePluginService(pluginName, method, object, sessionId), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONNECTOR_SERVICE_INVOKE)) { String name = request.getParameter("name"); String method = request.getParameter("method"); Object object = serializer.fromXML(request.getParameter("object")); String sessionId = request.getSession().getId(); response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.invokeConnectorService(name, method, object, sessionId), out); } else if (operation.equals(Operations.EXTENSION_UNINSTALL)) { String packageName = request.getParameter("packageName"); parameterMap.put("packageName", packageName); if (isUserAuthorized(request, parameterMap)) { extensionController.prepareExtensionForUninstallation(packageName); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.EXTENSION_INSTALL)) { if (isUserAuthorized(request, null)) { /* * This is a multi-part method, so we need our * parameters from the new map */ extensionController.extractExtension(multiPartFileItem); } 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:org.geowe.server.upload.FileUploadZipServlet.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final ServletFileUpload upload = new ServletFileUpload(); response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_FILE_SIZE);// w ww.j av a 2s . c om try { final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); ZipFile zipFile = createZipFile(item); final String content = readZipFile(zipFile); if (EMPTY.equals(content)) { response.setStatus(HttpStatus.SC_NO_CONTENT); response.getWriter().printf(HttpStatus.SC_NO_CONTENT + ":" + content); } else if (BAD_FORMAT.equals(content)) { response.setStatus(HttpStatus.SC_NOT_ACCEPTABLE); response.getWriter().printf(HttpStatus.SC_NOT_ACCEPTABLE + ":" + content); } else { response.setStatus(HttpStatus.SC_OK); response.getWriter().printf(content); } } } catch (SizeLimitExceededException e) { response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG); response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage()); LOG.error(e.getMessage()); } catch (Exception e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong."); LOG.error(e.getMessage()); } }
From source file:jease.cms.web.servlet.JeaseController.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String uri = request.getRequestURI(); // Strip jsessionid from URI. int jsessionidIndex = uri.indexOf(";jsessionid="); if (jsessionidIndex != -1) { uri = uri.substring(0, jsessionidIndex); }/*from w ww.j ava 2s . c om*/ // Process internal context prefix int tilde = uri.indexOf("~"); if (tilde != -1) { String path = uri.substring(tilde + 1); response.sendRedirect(response .encodeRedirectURL(buildURI(request.getContextPath() + path, request.getQueryString()))); return; } // Try to resolve node from URI (without context path). String nodePath = uri.substring(request.getContextPath().length()); Node node = Nodes.getByPath(nodePath); // Process redirect rules if (node == null && !servlets.matcher(nodePath).matches()) { String sourceURI = buildURI(nodePath, request.getQueryString()); String targetURI = rewriteURI(sourceURI); if (!targetURI.equals(sourceURI)) { if (targetURI.contains("://")) { response.sendRedirect(response.encodeRedirectURL(targetURI)); } else { response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + targetURI)); } return; } } // Save "virtual" root node. Per default it is the absolute root of the // instance. // If a node with the server name exists, this node is used as virtual // root. if (request.getAttribute("Root") == null) { String server = Servlets.getServerName(request).replaceFirst("www.", ""); Node root = Nodes.getRoot() != null ? Nodes.getRoot().getChild(server) : null; if (root == null) { root = Nodes.getRoot(); } if (node != null) { if (node.getParent() == root && locales.contains(node.getId())) { root = node; } else { for (Node parent : node.getParents()) { if (parent.getParent() == root && locales.contains(parent.getId())) { root = parent; break; } } } } request.setAttribute("Root", root); if (node != null && root.getParent() == node) { response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + root.getPath())); return; } } // If no node is found, process filter chain. if (node == null) { chain.doFilter(request, response); return; } // Redirect if trailing slash is missing for containers. if (node.isContainer() && !uri.endsWith("/")) { response.sendRedirect(response.encodeRedirectURL(buildURI(uri + "/", request.getQueryString()))); } else { // Set node into request scope and forward to dispatcher request.setAttribute(Node.class.getSimpleName(), node); request.setAttribute(Names.JEASE_SITE_DISPATCHER, dispatcher); Function<String, String> rewriter = StringUtils.isNotBlank( Registry.getParameter(Names.JEASE_SITE_REWRITER)) ? Database.query(rewriterSupplier) : null; request.getRequestDispatcher(dispatcher).forward(request, rewriter != null ? new ResponseRewriter(response, rewriter) : response); } }