List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding
public String getCharacterEncoding();
From source file:com.bstek.dorado.idesupport.resolver.RobotResolver.java
@Override public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception { DoradoContext context = DoradoContext.getCurrent(); Document document = null;//from w w w.j a va2 s. c om List<Element> resultElements = null; Exception error = null; String robotName = getRobotName(request); Assert.notEmpty(robotName, "\"robotName\" undefined."); Robot robot = robotRegistry.getRobot(robotName); if (robot == null) { throw new IllegalArgumentException("Unknown robotName \"" + robotName + "\"."); } ServletInputStream in = request.getInputStream(); try { String charset = request.getCharacterEncoding(); document = getXmlDocumentBuilder(context) .loadDocument(new InputStreamResource(in, request.getRequestURI()), charset); } catch (Exception e) { logger.error(e, e); error = e; } finally { in.close(); } Element documentElement = document.getDocumentElement(); Element contentElement = DomUtils.getChildByTagName(documentElement, "Content"); List<Element> elements = DomUtils.getChildElements(contentElement); Properties properties = null; Element propertiesElement = DomUtils.getChildByTagName(documentElement, "Properties"); if (propertiesElement != null) { List<Element> propertieElements = DomUtils.getChildElements(propertiesElement); if (!propertieElements.isEmpty()) { properties = new Properties(); for (Element propertyElement : propertieElements) { properties.setProperty(propertyElement.getAttribute("name"), DomUtils.getTextContent(propertyElement)); } } } resultElements = new ArrayList<Element>(); for (Element element : elements) { resultElements.add((Element) robot.execute(element, properties)); } // Output document = getXmlDocumentBuilder(context).newDocument(); Element responseElement = document.createElement("Response"); document.appendChild(responseElement); if (error == null) { assembleContent(document, responseElement, resultElements); } else { responseElement.setAttribute("failed", "true"); assembleError(document, responseElement, error); } PrintWriter writer = null; TransformerFactory transFactory = TransformerFactory.newInstance(); try { Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty("encoding", Constants.DEFAULT_CHARSET); transformer.setOutputProperty("indent", "yes"); DOMSource source = new DOMSource(document); writer = getWriter(request, response); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } finally { if (writer != null) { writer.flush(); writer.close(); } } }
From source file:org.apache.tuscany.sca.binding.jsonrpc.provider.JsonRpcServlet.java
private void handleJsonRpcInvocation(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException, ServletException { // Decode using the charset in the request if it exists otherwise // use UTF-8 as this is what all browser implementations use. // The JSON-RPC-Java JavaScript client is ASCII clean so it // although here we can correctly handle data from other clients // that do not escape non ASCII data String charset = request.getCharacterEncoding(); if (charset == null) { charset = "UTF-8"; }//from ww w . j a v a2 s. c o m JsonNode root = null; if (request.getMethod().equals("GET")) { // if using GET Support (see http://groups.google.com/group/json-rpc/web/json-rpc-over-http) //parse the GET QueryString try { String params = new String( Base64.decodeBase64(URLDecoder.decode(request.getParameter("params"), charset).getBytes())); StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("\"method\": \"" + request.getParameter("method") + "\","); sb.append("\"params\": " + params + ","); sb.append("\"id\":" + request.getParameter("id")); sb.append("}"); root = JacksonHelper.MAPPER.readTree(sb.toString()); } catch (Throwable e) { JsonRpc10Response error = new JsonRpc10Response( JsonNodeFactory.instance.textNode(request.getParameter("id")), e); error.write(response.getWriter()); return; } } else { root = JacksonHelper.MAPPER.readTree(request.getReader()); } try { if (root.isArray()) { ArrayNode input = (ArrayNode) root; JsonRpc20BatchRequest batchReq = new JsonRpc20BatchRequest(input); for (int i = 0; i < batchReq.getRequests().size(); i++) { JsonRpcResponse result = batchReq.getBatchResponse().getResponses().get(i); if (result == null) { result = invoke(batchReq.getRequests().get(i)); batchReq.getBatchResponse().getResponses().set(i, result); } } ArrayNode responses = batchReq.getBatchResponse().toJSONArray(); JacksonHelper.MAPPER.writeValue(response.getWriter(), responses); } else { if (root.has("jsonrpc")) { JsonRpc20Request jsonReq = new JsonRpc20Request((ObjectNode) root); JsonRpcResponse jsonResult = invoke(jsonReq); if (jsonResult != null) { jsonResult.write(response.getWriter()); } } else { JsonRpc10Request jsonReq = new JsonRpc10Request((ObjectNode) root); JsonRpc10Response jsonResult = invoke(jsonReq); if (jsonResult != null) { jsonResult.write(response.getWriter()); } } } } catch (Throwable e) { throw new ServletException(e); } }
From source file:org.geowebcache.service.wms.WMSGetCapabilities.java
protected WMSGetCapabilities(TileLayerDispatcher tld, HttpServletRequest servReq, String baseUrl, String contextPath, URLMangler urlMangler) { this.tld = tld; urlStr = urlMangler.buildURL(baseUrl, contextPath, WMSService.SERVICE_PATH) + "?SERVICE=WMS&"; String[] tiledKey = { "TILED" }; Map<String, String> tiledValue = ServletUtils.selectedStringsFromMap(servReq.getParameterMap(), servReq.getCharacterEncoding(), tiledKey); if (tiledValue != null && tiledValue.size() > 0) { includeVendorSpecific = Boolean.parseBoolean(tiledValue.get("TILED")); }/* ww w . j av a 2 s . c o m*/ }
From source file:org.alfresco.module.vti.web.actions.VtiBaseAction.java
/** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*w w w. j av a 2 s . c om*/ protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VtiFpRequest vtiRequest = new VtiFpRequest(request); VtiFpResponse vtiResponse = new VtiFpResponse(response); if ("application/x-vermeer-urlencoded".equals(request.getContentType()) && request.getContentLength() > 0) { StringBuffer formString = new StringBuffer(); InputStream inputStream = request.getInputStream(); char c = '\n'; do { c = (char) inputStream.read(); formString.append(c); } while (c != '\n'); String encoding = request.getCharacterEncoding(); if (encoding == null || encoding.trim().length() == 0) { encoding = "UTF-8"; } String[] paramValues = formString.toString().split("&"); for (String string : paramValues) { String[] paramValue = string.split("="); String decodedParamName = URLDecoder.decode(paramValue[0], encoding); String decodedParamValue = null; if (paramValue.length > 1) { decodedParamValue = URLDecoder.decode(paramValue[1], encoding); } else { decodedParamValue = new String(); } vtiRequest.setParameter(decodedParamName, decodedParamValue); } } doPost(vtiRequest, vtiResponse); }
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 www .j a 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:org.rhq.enterprise.gui.common.upload.UploadRenderer.java
public void decode(FacesContext context, UIComponent component) { ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); String clientId = component.getClientId(context); FileItem item = (FileItem) request.getAttribute(clientId); Object newValue;//from w w w .ja v a 2s . c om ValueExpression valueExpression = component.getValueExpression("value"); if (valueExpression != null) { Class valueType = valueExpression.getType(context.getELContext()); if (valueType == byte[].class) { newValue = item.get(); } else if (valueType == InputStream.class) { try { newValue = item.getInputStream(); } catch (IOException ex) { throw new FacesException(ex); } } else { String encoding = request.getCharacterEncoding(); if (encoding != null) { try { newValue = item.getString(encoding); } catch (UnsupportedEncodingException ex) { newValue = item.getString(); } } else { newValue = item.getString(); } } ((EditableValueHolder) component).setSubmittedValue(newValue); ((EditableValueHolder) component).setValid(true); } Object target = component.getAttributes().get("target"); if (target != null) { File file; if (target instanceof File) { file = (File) target; } else { ServletContext servletContext = (ServletContext) external.getContext(); String realPath = servletContext.getRealPath(target.toString()); file = new File(realPath); } try { item.write(file); } catch (Exception ex) { throw new FacesException(ex); } } }
From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java
/** * Sets the http request data.//from w ww. j a v a 2 s.co m * * @param request the request * @param requestContainer the request container */ private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) { requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType()); requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding()); requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength())); requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType()); requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath()); requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod()); requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo()); requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated()); requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol()); requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString()); requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr()); requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost()); requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser()); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId()); requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI()); requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme()); requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName()); requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort())); requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath()); if (request.getUserPrincipal() != null) requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal()); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE, String.valueOf(request.isRequestedSessionIdFromCookie())); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL, String.valueOf(request.isRequestedSessionIdFromURL())); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID, String.valueOf(request.isRequestedSessionIdValid())); requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure())); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); String headerValue = request.getHeader(headerName); requestContainer.setAttribute(headerName, headerValue); } // while (headerNames.hasMoreElements()) requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId()); requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE"); }
From source file:org.apache.manifoldcf.ui.multipart.MultipartWrapper.java
/** Constructor. *//*from w w w. ja v a 2 s . co m*/ public MultipartWrapper(HttpServletRequest request, AdminProfile adminProfile) throws ManifoldCFException { this.adminProfile = adminProfile; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { this.request = request; return; } // It is multipart! // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { characterEncoding = request.getCharacterEncoding(); // Handle broken tomcat; characterEncoding always comes back null for tomcat4 if (characterEncoding == null) characterEncoding = "utf8"; List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String name = item.getFieldName(); ArrayList list = (ArrayList) variableMap.get(name); if (list == null) { list = new ArrayList(); variableMap.put(name, list); } else { if (((FileItem) list.get(0)).isFormField() != item.isFormField()) throw new ManifoldCFException( "Illegal form data; posted form has the same name for different data types ('" + name + "')!"); } list.add(item); } } catch (FileUploadException e) { throw new ManifoldCFException("Problem uploading file: " + e.getMessage(), e); } }
From source file:org.more.webui.components.upload.Upload.java
public void onEvent(Event event, UIComponent component, ViewContext viewContext) throws Throwable { Upload swfUpload = (Upload) component; HttpServletRequest httpRequest = viewContext.getHttpRequest(); ServletContext servletContext = httpRequest.getSession(true).getServletContext(); if (ServletFileUpload.isMultipartContent(httpRequest) == false) return;// ??multipart?? try {//from w w w . j a v a 2 s . com //1. DiskFileItemFactory factory = new DiskFileItemFactory();// DiskFileItemFactory??????List ServletFileUpload upload = new ServletFileUpload(factory); String charset = httpRequest.getCharacterEncoding(); if (charset != null) upload.setHeaderEncoding(charset); factory.setSizeThreshold(swfUpload.getUploadSizeThreshold()); File uploadTempDir = new File(servletContext.getRealPath(swfUpload.getUploadTempDir())); if (uploadTempDir.exists() == false) uploadTempDir.mkdirs(); factory.setRepository(uploadTempDir); //2.? List<FileItem> itemList = upload.parseRequest(httpRequest); List<FileItem> finalList = new ArrayList<FileItem>(); Map<String, String> finalParam = new HashMap<String, String>(); for (FileItem item : itemList) if (item.isFormField() == false) finalList.add(item); else finalParam.put(new String(item.getFieldName().getBytes("iso-8859-1")), new String(item.getString().getBytes("iso-8859-1"))); //3. Object returnData = null; MethodExpression onBizActionExp = swfUpload.getOnBizActionExpression(); if (onBizActionExp != null) { HashMap<String, Object> upObject = new HashMap<String, Object>(); upObject.put("files", finalList); upObject.put("params", finalParam); HashMap<String, Object> upParam = new HashMap<String, Object>(); upParam.put("up", upObject); returnData = onBizActionExp.execute(component, viewContext, upParam); } //4.?? for (FileItem item : itemList) try { item.delete(); } catch (Exception e) { } //5. viewContext.sendObject(returnData); } catch (Exception e) { viewContext.sendError(e); } }
From source file:org.cerberus.servlet.crud.countryenvironment.UpdateApplicationObject.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w.j a v a 2 s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException { JSONObject jsonResponse = new JSONObject(); ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); Answer ans = new Answer(); MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "")); ans.setResultMessage(msg); String charset = request.getCharacterEncoding(); response.setContentType("application/json"); // Calling Servlet Transversal Util. ServletUtil.servletStart(request); Map<String, String> fileData = new HashMap<String, String>(); FileItem file = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { fileData.put(fileItem.getFieldName(), ParameterParserUtil .parseStringParamAndDecode(fileItem.getString("UTF-8"), null, charset)); } else { file = fileItem; } } } catch (FileUploadException e) { e.printStackTrace(); } /** * Parsing and securing all required parameters. */ // Parameter that are already controled by GUI (no need to decode) --> We SECURE them // Parameter that needs to be secured --> We SECURE+DECODE them String application = fileData.get("application"); String object = fileData.get("object"); String value = fileData.get("value"); String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset); String datemodif = new Timestamp(new java.util.Date().getTime()).toString(); // Parameter that we cannot secure as we need the html --> We DECODE them // Getting list of application from JSON Call // Prepare the final answer. MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK); Answer finalAnswer = new Answer(msg1); /** * Checking all constrains before calling the services. */ if (StringUtil.isNullOrEmpty(application)) { msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED); msg.setDescription( msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update") .replace("%REASON%", "Application name (applicationobject) is missing.")); ans.setResultMessage(msg); } else if (StringUtil.isNullOrEmpty(object)) { msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED); msg.setDescription( msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update") .replace("%REASON%", "Object name (applicationobject) is missing.")); ans.setResultMessage(msg); } else { /** * All data seems cleans so we can call the services. */ IApplicationObjectService applicationObjectService = appContext .getBean(IApplicationObjectService.class); AnswerItem resp = applicationObjectService.readByKey(application, object); if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) { /** * Object could not be found. We stop here and report the error. */ finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp); } else { /** * The service was able to perform the query and confirm the * object exist, then we can update it. */ ApplicationObject applicationData = (ApplicationObject) resp.getItem(); String fileName = applicationData.getScreenShotFileName(); if (file != null) { ans = applicationObjectService.uploadFile(applicationData.getID(), file); if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) { fileName = file.getName(); } } applicationData.setValue(value); applicationData.setScreenShotFileName(fileName); applicationData.setUsrModif(usrmodif); applicationData.setDateModif(datemodif); ans = applicationObjectService.update(applicationData); finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans); if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) { /** * Update was succesfull. Adding Log entry. */ ILogEventService logEventService = appContext.getBean(LogEventService.class); logEventService.createPrivateCalls("/UpdateApplication", "UPDATE", "Updated Application : ['" + application + "']", request); } finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans); } } /** * Formating and returning the json result. */ jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString()); jsonResponse.put("message", finalAnswer.getResultMessage().getDescription()); response.getWriter().print(jsonResponse); response.getWriter().flush(); }