List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding
public String getCharacterEncoding();
From source file:presentation.ui.ExtendedMultiPartRequestHandler.java
/** * Parses the input stream and partitions the parsed items into a set of * form fields and a set of file items. In the process, the parsed items are * translated from Commons FileUpload <code>FileItem</code> instances to * Struts <code>FormFile</code> instances. * //from ww w . ja v a2 s. c o m * @param request * The multipart request to be processed. * * @throws ServletException * if an unrecoverable error occurs. */ public void handleRequest(HttpServletRequest request) throws ServletException { // Get the app config for the current request. ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); // ---------------------------------------------------------- // Changed this section of code, that is it. // ----------------------------------------------------------- if (logger.isDebugEnabled()) logger.debug("Handling the request.."); UploadListener listener = new UploadListener(request, 1); if (logger.isDebugEnabled()) logger.debug("uploading file with optional monitoring.."); // Create a factory for disk-based file items FileItemFactory factory = new MonitoredDiskFileItemFactory(listener); if (logger.isDebugEnabled()) logger.debug("got the factory now get the ServletFileUpload"); ServletFileUpload upload = new ServletFileUpload(factory); if (logger.isDebugEnabled()) logger.debug("Should have the ServletFileUpload by now."); // The following line is to support an "EncodingFilter" // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255 upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. try { upload.setSizeMax(maxFileSize(request, getSizeMax(ac))); } catch (BusinessException e) { finish(); listener.error(e.getMessage()); // WebInfoHelper.getInstance().setWebError(request, e); throw new ServletException(e); } // ---------------------------------------------------------------- // Create the hash tables to be populated. elementsText = new Hashtable<String, String[]>(); elementsFile = new Hashtable<String, FormFile>(); elementsAll = new Hashtable<String, Object>(); // Parse the request into file items. List<?> items = null; try { items = upload.parseRequest(request); } catch (SizeLimitExceededException e) { // Special handling for uploads that are too big. listener.error(e.getMessage()); request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); return; } catch (FileUploadException e) { // WebInfoHelper.getInstance().setWebError(request, e); throw new ServletException(e); } // Partition the items into form fields and files. Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { addTextParameter(request, item); } else { addFileParameter(item); } } }
From source file:com.bruce.gogo.utils.JakartaMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param servletRequest the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. *///from w w w. j a v a 2 s. co m public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { DiskFileItemFactory fac = new DiskFileItemFactory(); // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } // Parse the request try { ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); ProgressListener myProgressListener = new MyProgressListener(servletRequest); upload.setProgressListener(myProgressListener); List items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (LOG.isDebugEnabled()) LOG.debug("Found item " + item.getFieldName()); if (item.isFormField()) { LOG.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } // note: see http://jira.opensymphony.com/browse/WW-633 // basically, in some cases the charset may be null, so // we're just going to try to "other" method (no idea if this // will work) String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { LOG.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { LOG.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (FileUploadException e) { LOG.error("Unable to parse request", e); errors.add(e.getMessage()); } }
From source file:org.nunux.poc.portal.ProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same content POST data * (JSON, XML, etc.) as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the POST data to be sent via the {@link PostMethod} *///from w ww.j a v a 2 s .c om private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException, ServletException { StringBuilder content = new StringBuilder(); BufferedReader reader = httpServletRequest.getReader(); for (;;) { String line = reader.readLine(); if (line == null) { break; } content.append(line); } String contentType = httpServletRequest.getContentType(); String postContent = content.toString(); if (contentType.startsWith("text/x-gwt-rpc")) { String clientHost = httpServletRequest.getLocalName(); if (clientHost.equals("127.0.0.1")) { clientHost = "localhost"; } int clientPort = httpServletRequest.getLocalPort(); String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : ""); String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "") + httpServletRequest.getServletPath(); //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")"); postContent = postContent.replace(clientUrl, serverUrl); } String encoding = httpServletRequest.getCharacterEncoding(); debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent); StringRequestEntity entity; try { entity = new StringRequestEntity(postContent, contentType, encoding); } catch (UnsupportedEncodingException e) { throw new ServletException(e); } // Set the proxy request POST data postMethodProxyRequest.setRequestEntity(entity); }
From source file:org.apache.axis2.builder.MultipartFormDataBuilder.java
/** * @return Returns the document element. *//* w w w . jav a 2s . co m*/ public OMElement processDocument(InputStream inputStream, String contentType, MessageContext messageContext) throws AxisFault { MultipleEntryHashMap parameterMap; HttpServletRequest request = (HttpServletRequest) messageContext .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); // TODO: Do check ContentLength for the max size, // but it can't be configured anywhere. // I think that it cant be configured at web.xml or axis2.xml. /** * When we are building a request context without the use of Servlets, we require charset encoding and content length * parameters to be set in the transports. */ String charSetEncoding = (String) messageContext .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING); Integer contentLength = 0; Map<String, String> transportHeaders = (Map) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS); String contentLengthValue = (String) transportHeaders.get(HTTPConstants.HEADER_CONTENT_LENGTH); if (contentLengthValue != null) { try { contentLength = new Integer(contentLengthValue); } catch (NumberFormatException e) { // TODO handle this better in case we cannot find the contentLength } } RequestContextImpl nRequest; if (request == null) { // on regular transport if (charSetEncoding == null || contentLength == null) { throw new AxisFault( "multipart/form-data builder could not find charset encoding or content length in messageContext TRANSPORT_HEADERS. Please set these in the respective transport in use."); } nRequest = new RequestContextImpl(inputStream, contentType, charSetEncoding, contentLength); } else { // from servlet transport nRequest = new RequestContextImpl(inputStream, request.getContentType(), request.getCharacterEncoding(), request.getContentLength()); } try { parameterMap = getParameterMap(nRequest, charSetEncoding); return BuilderUtil.buildsoapMessage(messageContext, parameterMap, OMAbstractFactory.getSOAP12Factory()); } catch (FileUploadException e) { throw AxisFault.makeFault(e); } }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same standard * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are * configuring to send a standard request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the data to be sent via the {@link EntityEnclosingMethod} *//* w ww .j a va2s.c om*/ @SuppressWarnings("unchecked") private void handleEntity(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws IOException { // Get the client POST data as a Map Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap(); // Create a List to hold the NameValuePairs to be passed to the PostMethod List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>(); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParamterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue); listNameValuePairs.add(nameValuePair); } } RequestEntity entity = null; String contentType = httpServletRequest.getContentType(); if (contentType != null) { contentType = contentType.toLowerCase(); if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application") || contentType.contains("text")) { String body = IOHelpers.readFully(httpServletRequest.getReader()); entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding()); entityEnclosingMethod.setRequestEntity(entity); } } NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[] {}); if (entity != null) { // TODO add as URL parameters? //postMethodProxyRequest.addParameters(parameters); } else { // Set the proxy request POST data if (entityEnclosingMethod instanceof PostMethod) { ((PostMethod) entityEnclosingMethod).setRequestBody(parameters); } } }
From source file:com.metaparadigm.jsonrpc.JSONRPCServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassCastException { // Find the JSONRPCBridge for this session or create one // if it doesn't exist HttpSession session = request.getSession(); JSONRPCBridge json_bridge = null;/*from w w w .ja va 2s .c om*/ json_bridge = (JSONRPCBridge) session.getAttribute("JSONRPCBridge"); if (json_bridge == null) { // Only create a new bridge if not disabled in config if (!auto_session_bridge) { // Use the global bridge only, and don't set on session. json_bridge = JSONRPCBridge.getGlobalBridge(); if (json_bridge.isDebug()) log.info("Using global bridge."); } else { json_bridge = new JSONRPCBridge(); session.setAttribute("JSONRPCBridge", json_bridge); if (json_bridge.isDebug()) log.info("Created a bridge for this session."); } } // Encode using UTF-8, although We are actually ASCII clean as // all unicode data is JSON escaped using backslash u. This is // less data efficient for foreign character sets but it is // needed to support naughty browsers such as Konqueror and Safari // which do not honour the charset set in the response response.setContentType("text/plain;charset=utf-8"); OutputStream out = response.getOutputStream(); // 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"; BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset)); // Read the request CharArrayWriter data = new CharArrayWriter(); char buf[] = new char[buf_size]; int ret; while ((ret = in.read(buf, 0, buf_size)) != -1) data.write(buf, 0, ret); if (json_bridge.isDebug()) log.fine("recieve: " + data.toString()); // Process the request JSONObject json_req = null; JSONRPCResult json_res = null; try { json_req = new JSONObject(data.toString()); json_res = json_bridge.call(new Object[] { request }, json_req); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // Write the response if (json_bridge.isDebug()) log.fine("send: " + json_res.toString()); byte[] bout = json_res.toString().getBytes("UTF-8"); if (keepalive) { response.setIntHeader("Content-Length", bout.length); } out.write(bout); out.flush(); out.close(); }
From source file:mapbuilder.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Get request// w w w . ja va 2 s . co m */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { if (log.isDebugEnabled()) { Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getHeader(name); log.debug("request header:" + name + ":" + value); } } // Transfer bytes from in to out log.debug("HTTP GET: transferring..."); //execute the GET String serverUrl = request.getParameter("url"); if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { log.info("GET param serverUrl:" + serverUrl); HttpClient client = new HttpClient(); GetMethod httpget = new GetMethod(serverUrl); client.executeMethod(httpget); if (log.isDebugEnabled()) { Header[] respHeaders = httpget.getResponseHeaders(); for (int i = 0; i < respHeaders.length; ++i) { String headerName = respHeaders[i].getName(); String headerValue = respHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } //dump response to out if (httpget.getStatusCode() == HttpStatus.SC_OK) { //force the response to have XML content type (WMS servers generally don't) response.setContentType("text/xml"); String responseBody = httpget.getResponseBodyAsString().trim(); // use encoding of the request or UTF8 String encoding = request.getCharacterEncoding(); if (encoding == null) encoding = "UTF-8"; response.setCharacterEncoding(encoding); log.info("responseEncoding:" + encoding); // do not set a content-length of the response (string length might not match the response byte size) //response.setContentLength(responseBody.length()); log.info("responseBody:" + responseBody); PrintWriter out = response.getWriter(); out.print(responseBody); response.flushBuffer(); } else { log.error("Unexpected failure: " + httpget.getStatusLine().toString()); } httpget.releaseConnection(); } else { throw new ServletException("only HTTP(S) protocol supported"); } } catch (Throwable e) { throw new ServletException(e); } }
From source file:org.opensubsystems.core.util.servlet.WebUtils.java
/** * Create debug string containing all parameter names and their values from * the request, all attributes, all cookies and other data characterizing the * request.// w ww. j av a2 s . c o m * * @param hsrqRequest - the servlet request. * @return String - debug string containing all parameter names and their * values from the request */ public static String debug(HttpServletRequest hsrqRequest) { Enumeration enumNames; Enumeration enumValues; Iterator iterValues; String strName; String[] arValues; Cookie[] arCookies; int iIndex; Map<String, String[]> mpParamMap; StringBuilder sbfReturn = new StringBuilder(); sbfReturn.append("HttpServletRequest=["); sbfReturn.append("\nRemoteAddress="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr())); sbfReturn.append(";"); sbfReturn.append("\nRemotePort="); sbfReturn.append(hsrqRequest.getRemotePort()); sbfReturn.append(";"); sbfReturn.append("\nRemoteHost="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost())); sbfReturn.append(";"); sbfReturn.append("\nRemoteUser="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser())); sbfReturn.append(";"); sbfReturn.append("\nFullURL="); sbfReturn.append(getFullRequestURL(hsrqRequest)); sbfReturn.append(";"); sbfReturn.append("\nContextPath="); sbfReturn.append(hsrqRequest.getContextPath()); sbfReturn.append(";"); sbfReturn.append("\nServletPath="); sbfReturn.append(hsrqRequest.getServletPath()); sbfReturn.append(";"); sbfReturn.append("\nPathInfo ="); sbfReturn.append(hsrqRequest.getPathInfo()); sbfReturn.append(";"); sbfReturn.append("\nRequestURI="); sbfReturn.append(hsrqRequest.getRequestURI()); sbfReturn.append(";"); sbfReturn.append("\nRequestURL="); sbfReturn.append(hsrqRequest.getRequestURL()); sbfReturn.append(";"); sbfReturn.append("\nMethod="); sbfReturn.append(hsrqRequest.getMethod()); sbfReturn.append(";"); sbfReturn.append("\nAuthenticationType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType())); sbfReturn.append(";"); sbfReturn.append("\nCharacterEncoding="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding())); sbfReturn.append(";"); sbfReturn.append("\nContentType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType())); sbfReturn.append(";"); sbfReturn.append("\nMultiPart="); sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest)); sbfReturn.append(";"); // Parameters //////////////////////////////////////////////////////////// try { Map.Entry<String, String[]> entry; // Use getParameterMap rather than request.getParameterNames since it // correctly handles multipart requests mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest); for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) { entry = (Map.Entry<String, String[]>) iterValues.next(); strName = entry.getKey(); arValues = entry.getValue(); sbfReturn.append("\nParam="); sbfReturn.append(strName); sbfReturn.append(" values="); for (iIndex = 0; iIndex < arValues.length; iIndex++) { sbfReturn.append(arValues[iIndex]); if (iIndex < (arValues.length - 1)) { sbfReturn.append(";"); } } if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access parameter map of the request>"); s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex); } // Uploaded files //////////////////////////////////////////////////////// if (ServletFileUpload.isMultipartContent(hsrqRequest)) { try { FileItem item; Map<String, FileItem> mpFiles; TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params; params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest); mpFiles = params.getSecond(); for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) { item = (FileItem) iterValues.next(); sbfReturn.append("\nUpload="); sbfReturn.append(item.getName()); sbfReturn.append(" field="); sbfReturn.append(item.getFieldName()); sbfReturn.append(" contentType="); sbfReturn.append(item.getContentType()); sbfReturn.append(" isInMemory="); sbfReturn.append(item.isInMemory()); sbfReturn.append(" sizeInBytes="); sbfReturn.append(item.getSize()); if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access list of multipart parameters>"); s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex); } } // Headers /////////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nHeader="); sbfReturn.append(strName); sbfReturn.append(" values="); for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) { sbfReturn.append(enumValues.nextElement()); if (enumValues.hasMoreElements()) { sbfReturn.append(";"); } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Cookies /////////////////////////////////////////////////////////////// arCookies = hsrqRequest.getCookies(); if (arCookies != null) { Cookie cookie; for (iIndex = 0; iIndex < arCookies.length; iIndex++) { cookie = arCookies[iIndex]; sbfReturn.append("\nCookie="); sbfReturn.append(cookie.getName()); sbfReturn.append(" path="); sbfReturn.append(cookie.getPath()); sbfReturn.append(" path="); sbfReturn.append(cookie.getDomain()); sbfReturn.append(" maxage="); sbfReturn.append(cookie.getMaxAge()); sbfReturn.append(" version="); sbfReturn.append(cookie.getVersion()); sbfReturn.append(" secure="); sbfReturn.append(cookie.getSecure()); sbfReturn.append(" value="); sbfReturn.append(cookie.getValue()); sbfReturn.append(" comment="); sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment())); if (iIndex < (arCookies.length - 1)) { sbfReturn.append(";"); } } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } // Attributes //////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nAttribute="); sbfReturn.append(strName); sbfReturn.append(" value="); sbfReturn.append(hsrqRequest.getAttribute(strName)); if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Content /////////////////////////////////////////////////////////////// sbfReturn.append("\nContent="); try { sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true)); } catch (IOException ex) { sbfReturn.append("<Cannot access input stream of the request>"); s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex); } sbfReturn.append(";"); return sbfReturn.toString(); }
From source file:org.aludratest.cloud.impl.request.ClientRequestServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from ww w .ja v a2s . co m*/ requestSeparator.enter(); } catch (InterruptedException e) { return; } LOG.debug("doPost() enter"); try { // small protection against DoS attacks if (req.getContentLength() > MAX_CONTENT_LENGTH) { LOG.debug("Detected request larger than max content length. Sending BAD_REQUEST."); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // must be /resource // TODO should be removed; is subject to Application container to register Servlet whereever needed String uri = req.getServletPath(); if (!"/resource".equals(uri)) { LOG.debug("Detected request to other path than /resource. Sending NOT_FOUND."); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } User user = BasicAuthUtil.authenticate(req, resp); if (user == null) { LOG.debug("No or invalid user information in request. Aborting."); return; } // request must be JSON String contentType = req.getContentType(); if (contentType != null && contentType.contains(";")) { contentType = contentType.substring(0, contentType.indexOf(';')); } if (CONTENT_TYPE_CHECK_ENABLED && !JSON_CONTENT_TYPE.equals(contentType)) { LOG.debug("Invalid content type detected. Sending BAD_REQUEST."); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // encoding must be UTF-8 if (req.getCharacterEncoding() != null && !"UTF-8".equalsIgnoreCase(req.getCharacterEncoding())) { LOG.debug("Invalid character encoding detected. Sending BAD_REQUEST."); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // extract JSON payload InputStream data = req.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(data, baos); data.close(); String jsonSource = new String(baos.toByteArray(), "UTF-8"); try { JSONObject requestObject = new JSONObject(jsonSource); waitingRequests.incrementAndGet(); JSONObject resultObject = requestHandler.handleResourceRequest(user, requestObject); waitingRequests.decrementAndGet(); // send it to response StringWriter writer = new StringWriter(); resultObject.write(writer); resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType(JSON_CONTENT_TYPE); byte[] resultData = writer.toString().getBytes("UTF-8"); resp.setContentLength(resultData.length); try { OutputStream os = resp.getOutputStream(); os.write(resultData); os.close(); } catch (IOException e) { // client closed connection during wait if (resultObject.has("requestId")) { requestHandler.abortWaitingRequest(resultObject.getString("requestId")); } } } catch (JSONException e) { LOG.debug("JSON exception occurred. Sending BAD_REQUEST."); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } } finally { LOG.debug("doPost() leave"); } }
From source file:com.sinosoft.one.mvc.web.RequestPath.java
public RequestPath(HttpServletRequest request) { // method//from w w w . j a v a2 s. c o m setMethod(parseMethod(request)); // ctxpath setCtxpath(request.getContextPath()); String invocationCtxpath = null; // includeinvocationCtxPathincludectxpath // dispather, uri, ctxpath String uri; if (WebUtils.isIncludeRequest(request)) { setDispatcher(Dispatcher.INCLUDE); uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE); invocationCtxpath = ((String) request.getAttribute(WebUtils.INCLUDE_CONTEXT_PATH_ATTRIBUTE)); setMvcPath((String) request.getAttribute(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE)); } else { if (request.getAttribute(MvcConstants.WINDOW_REQUEST_URI) != null) { uri = (String) request.getAttribute(MvcConstants.WINDOW_REQUEST_URI); request.removeAttribute(MvcConstants.WINDOW_REQUEST_URI); request.setAttribute(MvcConstants.IS_WINDOW_REQUEST, "1"); } else { uri = request.getRequestURI(); request.removeAttribute(MvcConstants.IS_WINDOW_REQUEST); } this.setMvcPath(request.getServletPath()); if (request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) == null) { this.setDispatcher(Dispatcher.REQUEST); } else { this.setDispatcher(Dispatcher.FORWARD); } } if (uri.startsWith("http://") || uri.startsWith("https://")) { int start = uri.indexOf('/', 9); if (start == -1) { uri = ""; } else { uri = uri.substring(start); } } if (uri.indexOf('%') != -1) { try { String encoding = request.getCharacterEncoding(); if (encoding == null || encoding.length() == 0) { encoding = "UTF-8"; } uri = URLDecoder.decode(uri, encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } this.setUri(uri); // requestPathctxpathincludeinvocationCtxpath if (getCtxpath().length() <= 1) { setMvcPath(getUri()); } else { setMvcPath(getUri().substring((invocationCtxpath == null ? getCtxpath() : invocationCtxpath).length())); } }