List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
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) *//*from w w w. j av a 2 s .com*/ 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:com.zimbra.soap.SoapServlet.java
private void doWork(HttpServletRequest req, HttpServletResponse resp) throws IOException { int len = req.getContentLength(); byte[] buffer; boolean isResumed = true; // resuming from a Jetty Continuation does *not* reset the HttpRequest's input stream - // therefore we store the read buffer in the Continuation, and use the stored buffer // if we're resuming buffer = (byte[]) req.getAttribute("com.zimbra.request.buffer"); if (buffer == null) { isResumed = false;//from w w w . j av a2 s . c o m // Look up max request size int maxSize = 0; try { maxSize = Provisioning.getInstance().getLocalServer() .getIntAttr(Provisioning.A_zimbraSoapRequestMaxSize, 0); } catch (ServiceException e) { ZimbraLog.soap.warn("Unable to look up %s. Not limiting the request size.", Provisioning.A_zimbraSoapRequestMaxSize, e); } if (maxSize <= 0) { maxSize = Integer.MAX_VALUE; } // Read the request boolean success; if (len > maxSize) { success = false; } else { BufferStream bs = null; try { bs = new BufferStream(len, maxSize, maxSize); int in = (int) bs.readFrom(req.getInputStream(), len >= 0 ? len : Integer.MAX_VALUE); if (len > 0 && in < len) throw new EOFException("SOAP content truncated " + in + "!=" + len); success = in <= maxSize; buffer = bs.toByteArray(); } finally { ByteUtil.closeStream(bs); } } // Handle requests that exceed the size limit if (!success) { String sizeString = (len < 0 ? "" : " size " + len); String msg = String.format("Request%s exceeded limit of %d bytes set for %s.", sizeString, maxSize, Provisioning.A_zimbraSoapRequestMaxSize); ServiceException e = ServiceException.INVALID_REQUEST(msg, null); ZimbraLog.soap.warn(null, e); Element fault = SoapProtocol.Soap12.soapFault(e); Element envelope = SoapProtocol.Soap12.soapEnvelope(fault); sendResponse(req, resp, envelope); return; } req.setAttribute("com.zimbra.request.buffer", buffer); } HashMap<String, Object> context = new HashMap<String, Object>(); context.put(SERVLET_CONTEXT, getServletContext()); context.put(SERVLET_REQUEST, req); context.put(SERVLET_RESPONSE, resp); try { Boolean isAdminReq = isAdminRequest(req); context.put(IS_ADMIN_REQUEST, isAdminReq); } catch (ServiceException se) { ZimbraLog.soap.warn("unable to determine isAdminReq", se); } // setup IPs in the context and add to logging context RemoteIP remoteIp = new RemoteIP(req, ZimbraServlet.getTrustedIPs()); context.put(SoapEngine.SOAP_REQUEST_IP, remoteIp.getClientIP()); context.put(SoapEngine.ORIG_REQUEST_IP, remoteIp.getOrigIP()); context.put(SoapEngine.REQUEST_IP, remoteIp.getRequestIP()); remoteIp.addToLoggingContext(); //checkAuthToken(req.getCookies(), context); context.put(SoapEngine.REQUEST_PORT, req.getServerPort()); Element envelope = null; try { envelope = mEngine.dispatch(req.getRequestURI(), buffer, context); if (context.containsKey(INVALIDATE_COOKIES)) { ZAuthToken.clearCookies(resp); } } catch (Throwable e) { if (e instanceof OutOfMemoryError) { Zimbra.halt("handler exception", e); } if (ZimbraLog.soap.isTraceEnabled() && !context.containsKey(SoapEngine.SOAP_REQUEST_LOGGED)) { ZimbraLog.soap.trace(!isResumed ? "C:\n%s" : "C: (resumed)\n%s", new String(buffer, Charsets.UTF_8)); } // don't interfere with Jetty Continuations -- pass the exception right up if (e.getClass().getName().equals("org.eclipse.jetty.continuation.ContinuationThrowable")) throw (Error) e; ZimbraLog.soap.warn("handler exception", e); Element fault = SoapProtocol.Soap12.soapFault(ServiceException.FAILURE(e.toString(), e)); envelope = SoapProtocol.Soap12.soapEnvelope(fault); } if (ZimbraLog.soap.isTraceEnabled()) { ZimbraLog.soap.trace("S:\n%s", envelope.prettyPrint()); } sendResponse(req, resp, envelope); }
From source file:com.google.ratel.util.RatelUtils.java
public static Reader createLimitedReader(HttpServletRequest request, final int maxRequestSize) { try {/* www . j av a2 s .c o m*/ Reader reader = request.getReader(); // Limit input to stop flood requests final long requestSize = request.getContentLength(); if (maxRequestSize >= 0) { if (requestSize != -1 && requestSize > maxRequestSize) { String msg = format( "the request was rejected because its size (%s) exceeds the configured maximum (%s)", requestSize, maxRequestSize); throw new IllegalArgumentException(msg); } reader = new LimitedReader(reader, maxRequestSize) { @Override protected void raiseError(long pSizeMax, long pCount) throws IOException { String msg = format( "the request was rejected because its size (%s) exceeds the configured maximum (%s)", requestSize, maxRequestSize); throw new IllegalArgumentException(msg); } }; } return reader; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.atricore.idbus.kernel.main.mediation.camel.component.logging.HttpLogMessageBuilder.java
public String buildLogMessage(Message message) { HttpExchange httpEx = (HttpExchange) message.getExchange(); if (message instanceof HttpMessage) { HttpServletRequest hreq = httpEx.getRequest(); StringBuffer logMsg = new StringBuffer(1024); logMsg.append("<http-request method=\"").append(hreq.getMethod()).append("\"").append("\n\t url=\"") .append(hreq.getRequestURL()).append("\"").append("\n\t content-type=\"") .append(hreq.getContentType()).append("\"").append("\n\t content-length=\"") .append(hreq.getContentLength()).append("\"").append("\n\t content-encoding=\"") .append(hreq.getCharacterEncoding()).append("\"").append(">"); Enumeration headerNames = hreq.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); Enumeration headers = hreq.getHeaders(headerName); logMsg.append("\n\t<header name=\"").append(headerName).append("\">"); while (headers.hasMoreElements()) { String headerValue = (String) headers.nextElement(); logMsg.append("\n\t\t<header-value>").append(headerValue).append("</header-value>"); }// www. j a v a 2 s .co m logMsg.append("\n\t</header>"); } Enumeration params = hreq.getParameterNames(); while (params.hasMoreElements()) { String param = (String) params.nextElement(); logMsg.append("\n\t<parameter name=\"").append(param).append("\">"); logMsg.append("\n\t\t\t<value>").append(hreq.getParameter(param)).append("</value>"); logMsg.append("\n\t</parameter>"); } logMsg.append("\n</http-request>"); return logMsg.toString(); } else { StringBuffer logMsg = new StringBuffer(1024); logMsg.append("\t<http-response />"); return logMsg.toString(); } }
From source file:de.eorganization.crawler.server.servlets.JSONImportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w ww. j a v a2 s . c o m*/ resp.setContentType("text/plain"); InputStream stream = req.getInputStream(); log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from " + req.getRemoteAddr()); String amiId = req.getHeader("AMI-ID"); log.info("Got AMI ID:" + amiId); String repository = req.getHeader("REPO"); log.info("Got REPO:" + repository); if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) { log.severe("AMI ID and REPO HTTP Header required."); return; } // Gson gson = new Gson(); // log.info("Parsed Gson " + gson.fromJson(new // InputStreamReader(stream), JsonObject.class)); String jsonString = IOUtils.toString(stream); log.info("Got JSON String " + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1)); JSONObject json = new JSONObject(); try { json = new JSONObject(jsonString); log.fine("Parsed Json " + json); log.finer("Json has keys: " + json.names()); } catch (JSONException e) { log.severe("No JSON sent or wrong format."); return; } JSONObject software = json.optJSONObject("software"); if (software != null) { log.finer("Software JSON " + software); JSONArray softwareNames = software.names(); log.finer("Key Array JSON " + softwareNames); for (int i = 0; i < softwareNames.length(); i++) { log.fine("software " + softwareNames.getString(i) + " with version " + software.getJSONObject(softwareNames.getString(i)).getString("version")); Map<String, String> softAttributes = new HashMap<String, String>(); JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names(); for (int j = 0; j < softwareAttributes.length(); j++) softAttributes.put(softwareAttributes.getString(j), software.getJSONObject(softwareNames.getString(i)) .getString(softwareAttributes.getString(j))); Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i), software.getJSONObject(softwareNames.getString(i)).getString("version"), softAttributes); if (soft != null) { log.fine("Saved/restored software " + soft); // soft.getAttributes().putAll(softAttributes); // AmiManager.updateSoftware(soft); // log.fine("Saved object " + soft); } else log.severe("Not able to save software information for given Ami Id " + amiId + "!"); } List<String> names = new ArrayList<String>(); for (int i = 0; i < softwareNames.length(); i++) names.add(softwareNames.getString(i)); AmiManager.updateSoftwareNames(names); log.info("Saved " + softwareNames.length() + " software objects"); } JSONObject languages = json.optJSONObject("languages"); if (languages != null) { log.finer("Languages JSON " + languages); JSONArray languagesNames = languages.names(); log.finer("Key Array JSON " + languagesNames); for (int i = 0; i < languagesNames.length(); i++) { log.fine("languages " + languagesNames.getString(i) + " with version " + languages.getJSONObject(languagesNames.getString(i)).getString("version")); Map<String, String> langAttributes = new HashMap<String, String>(); JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names(); for (int j = 0; j < languageAttributes.length(); j++) langAttributes.put(languageAttributes.getString(j), languages.getJSONObject(languagesNames.getString(i)) .getString(languageAttributes.getString(j))); Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i), languages.getJSONObject(languagesNames.getString(i)).getString("version"), langAttributes); if (lang != null) { log.fine("Saved/restored programming language " + lang); lang.getAttributes().putAll(langAttributes); AmiManager.updateLanguage(lang); log.fine("Saved object " + lang); } else log.severe("Not able to save programming language information for given Ami Id " + amiId + "!"); } log.info("Saved " + languagesNames.length() + " programming language objects"); } resp.getWriter().println( "Saving software packages and programming languages for " + amiId + " (" + repository + ")."); } catch (JSONException e) { log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace()); log.throwing(JSONImportServlet.class.getName(), "doPost", e); e.printStackTrace(); } catch (Exception ex) { log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace()); log.throwing(JSONImportServlet.class.getName(), "doPost", ex); ex.printStackTrace(); } // log.info("returning to referer " + req.getHeader("referer")); // resp.sendRedirect(req.getHeader("referer") != null && // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") : // "localhost:8088"); }
From source file:org.red5.server.net.servlet.RTMPTServlet.java
/** * Main entry point for the servlet./*from w w w . j a v a2s .com*/ */ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log.info("RTMPT service"); if (!req.getMethod().equals(REQUEST_METHOD) || req.getContentLength() == 0 || req.getContentType() == null || !req.getContentType().equals(CONTENT_TYPE)) { // Bad request - return simple error page handleBadRequest("Bad request, only RTMPT supported.", resp); return; } // XXX Paul: since the only current difference in the type of request // that we are interested in is the 'second' character, we can double // the speed of this entry point by using a switch on the second charater. char p = req.getServletPath().charAt(1); switch (p) { case 'o': //OPEN_REQUEST handleOpen(req, resp); break; case 'c': //CLOSE_REQUEST handleClose(req, resp); break; case 's': //SEND_REQUEST handleSend(req, resp); break; case 'i': //IDLE_REQUEST handleIdle(req, resp); break; default: handleBadRequest("RTMPT command " + p + " is not supported.", resp); } }
From source file:com.aipo.container.protocol.AipoDataServiceServlet.java
private String getBodyAsString(HttpServletRequest request) { if (request.getContentLength() == 0) { return ""; }//from w ww .j a v a 2 s . c o m InputStream is = null; try { String line; StringBuilder sb = new StringBuilder(); is = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); return sb.toString(); } catch (IOException ioe) { // ignore return null; } finally { IOUtils.closeQuietly(is); } }
From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param sr The servlet request. Must not be * {@code null}./*from w w w .j a v a2 s . c o m*/ * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(sr); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(sr.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = sr.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, sr.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(sr.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = sr.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = sr.getReader(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:com.stormpath.sdk.servlet.mvc.FormController.java
protected void validate(HttpServletRequest request, HttpServletResponse response, Form form) { validateCsrfToken(request, response, form); // check for request body and no parameters if (request.getParameterMap().size() == 0 && request.getContentLength() > 0) { // Read from request to see if social information exists ProviderAccountRequest accountRequest = getAccountProviderRequest(request); if (accountRequest != null) { ProviderAccountResult result = getApplication(request).getAccount(accountRequest); Account account = result.getAccount(); if (account.getStatus().equals(AccountStatus.ENABLED)) { request.setAttribute(Account.class.getName(), account); return; }/* w w w .j av a 2 s.c o m*/ } } //ensure required fields are present: List<Field> fields = form.getFields(); for (Field field : fields) { if (field.isRequired() && field.isEnabled()) { String value = form.getFieldValue(field.getName()); if (value == null) { String key = "stormpath.web." + getControllerKey() + ".form.fields." + field.getName() + ".required"; String msg = i18n(request, key); throw new ValidationException(msg); } } } //If JSON ensure we are not posting undeclared fields according to the spec if (isJsonPreferred(request, response)) { Map<String, Object> postedJsonFields = fieldValueResolver.getAllFields(request); for (String fieldName : postedJsonFields.keySet()) { if (form.getField(fieldName) == null && !"customData".equals(fieldName)) { String key = "stormpath.web.form.fields.unknown"; String msg = i18n(request, key, fieldName); throw new ValidationException(msg); } } } }
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 va 2 s.c om 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"); } }