List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java
private void executeMultiObjectDelete(HttpServletRequest request, HttpServletResponse response) throws IOException { int contentLength = request.getContentLength(); StringBuffer xmlDeleteResponse = null; boolean quite = true; if (contentLength > 0) { InputStream is = null;// w w w . j a v a 2 s . c om String versionID = null; try { is = request.getInputStream(); String xml = StringHelper.stringFromStream(is); String elements[] = { "Key", "VersionId" }; Document doc = XmlHelper.parse(xml); Node node = XmlHelper.getRootNode(doc); if (node == null) { System.out.println("Invalid XML document, no root element"); return; } xmlDeleteResponse = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DeleteResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"); String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY); S3DeleteObjectRequest engineRequest = new S3DeleteObjectRequest(); engineRequest.setBucketName(bucket); is.close(); doc.getDocumentElement().normalize(); NodeList qList = doc.getElementsByTagName("Quiet"); if (qList.getLength() == 1) { Node qNode = qList.item(0); if (qNode.getFirstChild().getNodeValue().equalsIgnoreCase("true") == false) quite = false; logger.debug("Quite value :" + qNode.getFirstChild().getNodeValue()); } NodeList objList = doc.getElementsByTagName("Object"); for (int i = 0; i < objList.getLength(); i++) { Node key = objList.item(i); NodeList key_data = key.getChildNodes(); if (key.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) key; String key_name = getTagValue(elements[0], eElement); engineRequest.setBucketName(bucket); engineRequest.setKey(key_name); if (key_data.getLength() == 2) { versionID = getTagValue(elements[1], eElement); engineRequest.setVersion(versionID); } S3Response engineResponse = ServiceProvider.getInstance().getS3Engine() .handleRequest(engineRequest); int resultCode = engineResponse.getResultCode(); String resutlDesc = engineResponse.getResultDescription(); if (resultCode == 204) { if (quite) { // show response depending on quite/verbose xmlDeleteResponse.append("<Deleted><Key>" + key_name + "</Key>"); if (resutlDesc != null) xmlDeleteResponse.append(resutlDesc); xmlDeleteResponse.append("</Deleted>"); } } else { logger.debug("Error in delete ::" + key_name + " eng response:: " + engineResponse.getResultDescription()); xmlDeleteResponse.append("<Error><Key>" + key_name + "</Key>"); if (resutlDesc != null) xmlDeleteResponse.append(resutlDesc); xmlDeleteResponse.append("</Error>"); } } } String version = engineRequest.getVersion(); if (null != version) response.addHeader("x-amz-version-id", version); } catch (IOException e) { logger.error("Unable to read request data due to " + e.getMessage(), e); throw new NetworkIOException(e); } finally { if (is != null) is.close(); } xmlDeleteResponse.append("</DeleteResult>"); } response.setStatus(200); response.setContentType("text/xml; charset=UTF-8"); S3RestServlet.endResponse(response, xmlDeleteResponse.toString()); }
From source file:org.openqa.grid.internal.TestSession.java
private HttpRequest prepareProxyRequest(HttpServletRequest request /*, ForwardConfiguration config*/) throws IOException { URL remoteURL = slot.getRemoteURL(); String pathSpec = request.getServletPath() + request.getContextPath(); String path = request.getRequestURI(); if (!path.startsWith(pathSpec)) { throw new IllegalStateException("Expected path " + path + " to start with pathSpec " + pathSpec); }/* ww w . jav a2 s.c o m*/ String end = path.substring(pathSpec.length()); String ok = remoteURL + end; if (request.getQueryString() != null) { ok += "?" + request.getQueryString(); } String uri = new URL(remoteURL, ok).toExternalForm(); InputStream body = null; if (request.getContentLength() > 0 || request.getHeader("Transfer-Encoding") != null) { body = request.getInputStream(); } HttpRequest proxyRequest; if (body != null) { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(request.getMethod(), uri); r.setEntity(new InputStreamEntity(body, request.getContentLength())); proxyRequest = r; } else { proxyRequest = new BasicHttpRequest(request.getMethod(), uri); } for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = (String) e.nextElement(); if ("Content-Length".equalsIgnoreCase(headerName)) { continue; // already set } proxyRequest.setHeader(headerName, request.getHeader(headerName)); } return proxyRequest; }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private boolean checkPutPreconditions(HttpServletRequest req, HttpServletResponse resp) { if (req.getContentLength() <= 0) { resp.setStatus(HttpServletResponse.SC_LENGTH_REQUIRED); return false; }/*ww w.java 2 s. c o m*/ if (req.getContentType() == null || !req.getContentType().startsWith("text/xml")) { resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return false; } if (req.getHeader("Content-Transfer-Encoding") != null || req.getHeader("Content-Encoding") != null || req.getHeader("Content-Base") != null || req.getHeader("Content-Location") != null || req.getHeader("Content-MD5") != null || req.getHeader("Content-Range") != null) { resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); return false; } return true; }
From source file:uk.ac.ebi.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request // note: we won't transfer the protocol version because I'm not sure it // would truly be compatible BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest( servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null;// w ww .j av a2 s . co m InputStream servletRequestInputStream = servletRequest.getInputStream(); try { try { proxyRequest.setEntity( new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength())); // Execute the request if (doLog) { log("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); } finally { closeQuietly(servletRequestInputStream); } // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is // deprecated but it's the only way to pass the // reason along too. // noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { // abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; throw new RuntimeException(e); } }
From source file:sg.ncl.DataController.java
@RequestMapping(value = "{datasetId}/resources/upload", method = RequestMethod.POST) public ResponseEntity<String> uploadChunk(@PathVariable String datasetId, HttpServletRequest request) { int resumableChunkNumber = getResumableChunkNumber(request); ResumableInfo info = getResumableInfo(request); try {//from w w w . j a v a2 s . c o m InputStream is = request.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); long readed = 0; long content_length = request.getContentLength(); byte[] bytes = new byte[1024 * 100]; while (readed < content_length) { int r = is.read(bytes); if (r < 0) { break; } os.write(bytes, 0, r); readed += r; } JSONObject resumableObject = new JSONObject(); resumableObject.put("resumableChunkSize", info.resumableChunkSize); resumableObject.put("resumableTotalSize", info.resumableTotalSize); resumableObject.put("resumableIdentifier", info.resumableIdentifier); resumableObject.put("resumableFilename", info.resumableFilename); resumableObject.put("resumableRelativePath", info.resumableRelativePath); String resumableChunk = Base64.encodeBase64String(os.toByteArray()); log.debug(resumableChunk); resumableObject.put("resumableChunk", resumableChunk); String url = properties.sendUploadChunk(datasetId, resumableChunkNumber); log.debug("URL: {}", url); HttpEntity<String> httpEntity = createHttpEntityWithBody(resumableObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); String body = responseEntity.getBody().toString(); if (RestUtil.isError(responseEntity.getStatusCode())) { MyErrorResource error = objectMapper.readValue(body, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); return getStringResponseEntity(exceptionState); } else if (body.equals("All finished.")) { log.info("Data resource uploaded."); } return ResponseEntity.ok(body); } catch (Exception e) { log.error("Error sending upload chunk: {}", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error sending upload chunk"); } }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private Document readXmlRequest(HttpServletRequest req) throws SAXException, IOException { if (req.getContentLength() == 0) { return null; }/* ww w . ja v a 2 s . c o m*/ InputStream in = req.getInputStream(); if (in == null) { return null; } // check to see if there's any data to read PushbackInputStream filtered = new PushbackInputStream(in, 1); int read = filtered.read(); if (read == -1) { return null; } filtered.unread(read); // there is data, so read the stream try { BUILDER_FACTORY.setNamespaceAware(true); DocumentBuilder docBuilder = BUILDER_FACTORY.newDocumentBuilder(); return docBuilder.parse(filtered); } catch (ParserConfigurationException e) { throw new CmpException("error configuring xml builder", e); } }
From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java
private void dump(HttpServletRequest request, StringBuffer log) throws IOException { String hN;/*from w ww .jav a2s . c om*/ log.append("-- DUMP HttpServletRequest START").append("\n"); log.append("Method : ").append(request.getMethod()).append("\n"); log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n"); log.append("Scheme : ").append(request.getScheme()).append("\n"); log.append("IsSecure : ").append(request.isSecure()).append("\n"); log.append("Protocol : ").append(request.getProtocol()).append("\n"); log.append("ContextPath : ").append(request.getContextPath()).append("\n"); log.append("PathInfo : ").append(request.getPathInfo()).append("\n"); log.append("QueryString : ").append(request.getQueryString()).append("\n"); log.append("RequestURI : ").append(request.getRequestURI()).append("\n"); log.append("RequestURL : ").append(request.getRequestURL()).append("\n"); log.append("ContentType : ").append(request.getContentType()).append("\n"); log.append("ContentLength : ").append(request.getContentLength()).append("\n"); log.append("CharacterEncoding : ").append(request.getCharacterEncoding()).append("\n"); log.append("---- Headers START\n"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { hN = headerNames.nextElement(); log.append("[" + hN + "]="); Enumeration<String> headers = request.getHeaders(hN); while (headers.hasMoreElements()) { log.append("[" + headers.nextElement() + "]"); } log.append("\n"); } log.append("---- Headers END\n"); log.append("---- Body START\n"); log.append(IOUtils.toString(request.getInputStream(), "UTF-8")).append("\n"); log.append("---- Body END\n"); log.append("-- DUMP HttpServletRequest END \n"); }
From source file:com.redblackit.web.server.EchoServlet.java
/** * doEcho/* w w w . ja va2 s. com*/ * * <ul> * <li>Log method, URL, headers, body</li> * <li>Replicate request headers, except for setting location to received * URL</li> * <li>Replicate request body in response</li> * </ul> * * @param req * @param resp * @param method */ @SuppressWarnings("rawtypes") private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException { String reqURI = req.getRequestURI(); logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI); for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) { String headerName = (String) hdrse.nextElement(); int hnct = 0; for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) { String headerValue = (String) hdre.nextElement(); logger.debug( this.getClass().getName() + ": header[" + headerName + "," + hnct + "]=" + headerValue); if (!headerName.equals("Location")) { resp.addHeader(headerName, headerValue); } hnct++; } if (hnct == 0) { resp.setHeader(headerName, ""); logger.info(this.getClass().getName() + ": header[" + headerName + "," + hnct + "]='' (empty)"); } } resp.setHeader("Location", reqURI); resp.setStatus(HttpServletResponse.SC_OK); if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) { String body = FileCopyUtils.copyToString(req.getReader()); logger.debug(this.getClass().getName() + ": body>>\n" + body + "\nbody<<"); FileCopyUtils.copy(body, resp.getWriter()); resp.flushBuffer(); resp.setContentLength(req.getContentLength()); } else { logger.debug(this.getClass().getName() + ": body is empty"); resp.setContentLength(0); } }
From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java
protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response, boolean showResponse) { sb.append("Request class=" + request.getClass().getName()); sb.append(", RequestedSessionId=").append(request.getRequestedSessionId()); sb.append(LF).append(IND);// w w w . j a v a2s .co m sb.append(", REQUEST_URI=").append(request.getRequestURI()); sb.append(", SERVLET_PATH=").append(request.getServletPath()); sb.append(", CharacterEncoding=" + request.getCharacterEncoding()); sb.append(", ContentLength=").append(request.getContentLength()); sb.append(LF).append(IND); sb.append(", ContentType=").append(request.getContentType()); sb.append(", Locale=").append(request.getLocale()); sb.append(", Locales="); final Enumeration<?> locales = request.getLocales(); boolean first = true; while (locales.hasMoreElements()) { final Locale locale = (Locale) locales.nextElement(); if (first) { first = false; } else { sb.append(", "); } sb.append(locale.toString()); } sb.append(", Scheme=").append(request.getScheme()); sb.append(", isSecure=").append(request.isSecure()); sb.append(LF).append(IND); sb.append(", SERVER_PROTOCOL=").append(request.getProtocol()); sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr()); sb.append(", REMOTE_HOST=").append(request.getRemoteHost()); sb.append(", SERVER_NAME=").append(request.getServerName()); sb.append(", SERVER_PORT=").append(request.getServerPort()); sb.append(LF).append(IND); sb.append(", ContextPath=").append(request.getContextPath()); sb.append(", REQUEST_METHOD=").append(request.getMethod()); sb.append(", PathInfo=").append(request.getPathInfo()); sb.append(", RemoteUser=").append(request.getRemoteUser()); sb.append(LF).append(IND); sb.append(", REQUEST_URL=").append(request.getRequestURL()); sb.append(LF).append(IND); sb.append(", QUERY_STRING=").append(request.getQueryString()); if (showResponse) { sb.append(LF).append(IND); buildResponseInfo(sb, request, response); } sb.append(LF); buildRequestHeaders(sb, request); buildRequestParameters(sb, request); buildCookies(sb, request); buildRequestAttributes(sb, request); buildSessionAttributes(sb, request); }
From source file:eu.freme.broker.tools.loggingfilter.LoggingFilter.java
private void logRequest(final HttpServletRequest request) { StringBuilder msg = new StringBuilder(); msg.append(REQUEST_PREFIX);//w w w.j a v a 2 s .c o m if (request instanceof RequestWrapper) { msg.append("request id=").append(((RequestWrapper) request).getId()).append("; "); } HttpSession session = request.getSession(false); if (session != null) { msg.append("session id=").append(session.getId()).append("; "); } if (request.getContentType() != null) { msg.append("content type=").append(request.getContentType()).append("; "); } msg.append("uri=").append(request.getRequestURI()); if (request.getQueryString() != null) { msg.append('?').append(request.getQueryString()); } if (request instanceof RequestWrapper && !isMultipart(request)) { RequestWrapper requestWrapper = (RequestWrapper) request; try { String charEncoding = requestWrapper.getCharacterEncoding() != null ? requestWrapper.getCharacterEncoding() : "UTF-8"; if (request.getContentLength() == 0 || checkAgainstWhitelist(request)) { String body = new String(requestWrapper.toByteArray(), charEncoding); if (request.getContentLength() >= maxSize) { try { body = body.substring(0, maxSize).concat("... (truncated by LoggingFilter)"); } catch (StringIndexOutOfBoundsException e) { logger.warn( "A Request was made whose Content-Length Header is longer than its actual content"); } } msg.append("; payload=").append(body); } else { msg.append("; payload ommitted from logging as it is not in the whitelisted mime-types"); } } catch (UnsupportedEncodingException e) { logger.warn("Failed to parse request payload", e); } } logger.info(msg.toString()); }