List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:it.geosolutions.httpproxy.HTTPProxy.java
/** * Sets up the given {@link PostMethod} to send the same standard POST data as was sent in the given {@link HttpServletRequest} * //from w w w . ja va 2s. c o m * @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} * @throws IOException */ private void handleStandard(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest) throws IOException { try { InputStream is = httpServletRequest.getInputStream(); methodProxyRequest.setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream())); //LOGGER.info("original request content length:" + httpServletRequest.getContentLength()); //LOGGER.info("proxied request content length:" +methodProxyRequest.getRequestEntity().getContentLength()+""); } catch (IOException e) { throw new IOException(e); } }
From source file:com.couchbase.capi.servlet.CAPIServlet.java
protected void handleBulkDocs(HttpServletRequest req, HttpServletResponse resp, String database) throws ServletException, IOException { if (!req.getMethod().equals("POST")) { throw new UnsupportedOperationException("_bulk_docs must be POST"); }/*from www . j a v a 2s . c om*/ logger.trace("Got bulk docs request for " + database); resp.setStatus(HttpServletResponse.SC_CREATED); resp.setContentType("application/json"); OutputStream os = resp.getOutputStream(); InputStream is = req.getInputStream(); int requestLength = req.getContentLength(); byte[] buffer = new byte[requestLength]; IOUtils.readFully(is, buffer, 0, requestLength); @SuppressWarnings("unchecked") Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class); logger.trace("parsed value is " + parsedValue); try { List<Object> responseList = capiBehavior.bulkDocs(database, (ArrayList<Map<String, Object>>) parsedValue.get("docs")); if (responseList == null) { sendNotFoundResponse(resp, "missing"); return; } mapper.writeValue(os, responseList); } catch (UnavailableException e) { sendServiceUnavailableResponse(resp, "too many concurrent requests"); } }
From source file:br.org.indt.ndg.servlets.PostResults.java
private String Decompress(HttpServletRequest request) { DataInputStream dis = null;//from w w w. j av a 2 s .c o m DataInputStream objIn = null; ByteArrayOutputStream baos = null; String result = null; try { dis = new DataInputStream(request.getInputStream()); baos = new ByteArrayOutputStream(); int length, uncomplength = 0; int data = 0; uncomplength = dis.readInt(); length = dis.readInt(); for (int i = 0; i < length; i++) { data = dis.read(); baos.write((byte) data); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ZInputStream zIn = new ZInputStream(bais); objIn = new DataInputStream(zIn); byte[] bytes = new byte[uncomplength]; objIn.readFully(bytes); result = new String(bytes, ENCODING); log.info("Compressed length: " + length + " bytes"); log.info("Decompressed length: " + result.getBytes().length + " bytes"); zIn.close(); dis.close(); baos.close(); objIn.close(); } catch (EOFException e) { servletError = true; log.error(e); } catch (IOException e) { servletError = true; log.error(e); } catch (Exception e) { servletError = true; log.error(e); } return result; }
From source file:net.sf.qooxdoo.rpc.RpcServlet.java
/** * Remote method execution. The method name and parameters are expected * in JSON format in the request body./*from www. j av a 2 s . c o m*/ * * @param request the servlet request. * @param response the servlet response. * * @throws ServletException thrown when executing the method or writing * the response fails. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { InputStream is = null; Reader reader = null; try { String res; String contentType = request.getHeader("Content-Type"); if (!checkReferrer(request) || contentType == null || contentType.indexOf("application/json") != 0) { res = ACCESS_DENIED_RESULT; } else { is = request.getInputStream(); reader = new InputStreamReader(is, "UTF-8"); StringBuffer requestBuffer = new StringBuffer(); char[] readBuffer = new char[BUFFER_SIZE]; int length; while ((length = reader.read(readBuffer)) != -1) { requestBuffer.append(readBuffer, 0, length); } String requestString = requestBuffer.toString(); //System.out.println("Request string: " + requestString); res = handleRPC(request, requestString); } response.setContentType("text/plain; charset=UTF-8"); Writer responseWriter = response.getWriter(); responseWriter.write(res); } catch (Exception e) { throw new ServletException("Cannot execute remote method", e); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { // ignore } } if (is != null) { try { is.close(); } catch (Exception e) { // ignore } } } }
From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java
/** * <p> Example of parsing the multipart request with in a blocking IO mode using the {@link BlockingIOAdapter}. * * @param request The {@code HttpServletRequest} * @return The {@code VerificationItems} * @throws Exception if an exception happens during the parsing *//* www. j a v a 2 s . co m*/ @RequestMapping(value = "/blockingio/adapter/multipart", method = RequestMethod.POST) public @ResponseBody VerificationItems blockingIoAdapterMultipart(final HttpServletRequest request) throws Exception { assertRequestIsMultipart(request); final VerificationItems verificationItems = new VerificationItems(); Metadata metadata = null; try (final CloseableIterator<PartItem> parts = Multipart.multipart(getMultipartContext(request)) .forBlockingIO(request.getInputStream())) { while (parts.hasNext()) { PartItem partItem = parts.next(); if (FORM.equals(partItem.getType())) { FormParameter formParameter = (FormParameter) partItem; if (METADATA_FIELD_NAME.equals(formParameter.getFieldName())) { if (metadata != null) { throw new IllegalStateException("Found more than one metadata field"); } metadata = unmarshalMetadata(formParameter.getFieldValue()); } } else if (ATTACHMENT.equals(partItem.getType())) { Attachment attachment = (Attachment) partItem; final String fieldName = MultipartUtils.getFieldName(attachment.getHeaders()); if (METADATA_FIELD_NAME.equals(fieldName)) { metadata = unmarshalMetadata(attachment.getPartBody()); } else { VerificationItem verificationItem = buildVerificationItem(attachment.getPartBody(), fieldName); verificationItems.getVerificationItems().add(verificationItem); } } else { throw new IllegalStateException("Invalid part type " + partItem.getClass().getName()); } } } catch (Exception e) { throw new IllegalStateException("Parsing error", e); } processVerificationItems(verificationItems, metadata, false); return verificationItems; }
From source file:keyserver.KeyServerServlet.java
private void performUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException { try {//from w w w . j a v a2s.c o m User user = getCurrentGoogleUser(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key userId = KeyFactory.createKey(DB_KIND_USER, user.getUserId()); Query query = new Query(DB_KIND_USER, userId); Entity identification = datastore.prepare(query).asSingleEntity(); JSONArray array = new JSONArray( (new BufferedReader(new InputStreamReader(req.getInputStream()))).readLine()); JSONObject obj; obj = array.getJSONObject(0); Key pictureKey = KeyFactory.stringToKey(obj.getString(JSON_PICTUREID)); if (pictureKey != null && pictureKey.getParent().equals(identification.getKey())) { // if requester is the owner of the picture, otherwise the request is dismissed for (int i = 1; i < array.length(); i++) { obj = array.getJSONObject(i); if (obj.getString(JSON_UPDATEACTION).equalsIgnoreCase(JSON_UPDATEACTION_ADD)) { Entity newPermission = new Entity(DB_KIND_PERMISSION, pictureKey); newPermission.setProperty(DB_PERMISSION_H_START, obj.getInt(JSON_HSTART)); newPermission.setProperty(DB_PERMISSION_H_END, obj.getInt(JSON_HEND)); newPermission.setProperty(DB_PERMISSION_V_START, obj.getInt(JSON_VSTART)); newPermission.setProperty(DB_PERMISSION_V_END, obj.getInt(JSON_VEND)); newPermission.setProperty(DB_PERMISSION_USERNAME, obj.getString(JSON_USERNAME)); datastore.put(newPermission); } else if (obj.getString(JSON_UPDATEACTION).equalsIgnoreCase(JSON_UPDATEACTION_DELETE)) { datastore.delete(KeyFactory.stringToKey(obj.getString(JSON_PERMISSIONID))); } } } JSONArray response = new JSONArray(); response.put(new JSONObject(JSON_DEFAULTOK)); resp.getWriter().print(response.toString()); } catch (JSONException jsonEx) { JSONArray error = createJsonErrorObject("Malformed JSON object received"); resp.getWriter().print(error); } catch (IllegalArgumentException illargex) { JSONArray error = createJsonErrorObject("Malformed or incomplete key received"); resp.getWriter().print(error); } }
From source file:bookkeepr.jettyhandlers.WebHandler.java
public void handle(String path, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { if (path.equals("/")) { response.sendRedirect("/web/"); }/*from w w w. j ava2s. c o m*/ HttpClient httpclient = null; if (path.startsWith("/web/xmlify")) { ((Request) request).setHandled(true); if (request.getMethod().equals("POST")) { try { String remotePath = path.substring(11); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); XMLAble xmlable = null; try { xmlable = httpForm2XmlAble(reader.readLine()); } catch (BookKeeprException ex) { response.sendError(400, "Server could not form xml from the form data you submitted. " + ex.getMessage()); return; } if (xmlable == null) { response.sendError(500, "Server could not form xml from the form data you submitted. The server created a null value!"); return; } // XMLWriter.write(System.out, xmlable); // if(true)return; HttpPost httppost = new HttpPost(bookkeepr.getConfig().getExternalUrl() + remotePath); httppost.getParams().setBooleanParameter("http.protocol.strict-transfer-encoding", false); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); XMLWriter.write(out, xmlable); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); httppost.setEntity(new InputStreamEntity(in, -1)); Logger.getLogger(WebHandler.class.getName()).log(Level.INFO, "Xmlifier posting to " + bookkeepr.getConfig().getExternalUrl() + remotePath); httpclient = bookkeepr.checkoutHttpClient(); HttpResponse httpresp = httpclient.execute(httppost); for (Header head : httpresp.getAllHeaders()) { if (head.getName().equalsIgnoreCase("transfer-encoding")) { continue; } response.setHeader(head.getName(), head.getValue()); } response.setStatus(httpresp.getStatusLine().getStatusCode()); httpresp.getEntity().writeTo(response.getOutputStream()); } catch (HttpException ex) { Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING, "HttpException " + ex.getMessage(), ex); response.sendError(500, ex.getMessage()); } catch (URISyntaxException ex) { Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING, ex.getMessage(), ex); response.sendError(400, "Invalid target URI"); } finally { if (httpclient != null) { bookkeepr.returnHttpClient(httpclient); } } } return; } if (request.getMethod().equals("GET")) { if (path.startsWith("/web")) { ((Request) request).setHandled(true); if (badchar.matcher(path).matches()) { response.sendError(400, "User Error"); return; } String localpath = path.substring(4); Logger.getLogger(WebHandler.class.getName()).log(Level.FINE, "Transmitting " + localroot + localpath); File targetFile = new File(localroot + localpath); if (targetFile.isDirectory()) { if (path.endsWith("/")) { targetFile = new File(localroot + localpath + "index.html"); } else { response.sendRedirect(path + "/"); return; } } if (targetFile.exists()) { if (targetFile.getName().endsWith(".html") || targetFile.getName().endsWith(".xsl")) { BufferedReader in = new BufferedReader(new FileReader(targetFile)); PrintStream out = null; String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new PrintStream(new GZIPOutputStream(response.getOutputStream())); response.setHeader("Content-Encoding", "gzip"); } else { out = new PrintStream(response.getOutputStream()); } String line = in.readLine(); while (line != null) { if (line.trim().startsWith("%%%")) { BufferedReader wrapper = new BufferedReader( new FileReader(localroot + "/wrap/" + line.trim().substring(3) + ".html")); String line2 = wrapper.readLine(); while (line2 != null) { out.println(line2); line2 = wrapper.readLine(); } wrapper.close(); } else if (line.trim().startsWith("***chooser")) { String[] elems = line.trim().split("\\s"); try { int type = TypeIdManager .getTypeFromClass(Class.forName("bookkeepr.xmlable." + elems[1])); List<IdAble> items = this.bookkeepr.getMasterDatabaseManager() .getAllOfType(type); out.printf("<select name='%sId'>\n", elems[1]); for (IdAble item : items) { out.printf("<option value='%x'>%s</option>", item.getId(), item.toString()); } out.println("</select>"); } catch (Exception e) { Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING, "Could not make a type ID for " + line.trim()); } } else { out.println(line); } line = in.readLine(); } in.close(); out.close(); } else { outputToInput(new FileInputStream(targetFile), response.getOutputStream()); } } else { response.sendError(HttpStatus.SC_NOT_FOUND); } } } }
From source file:com.imaginary.home.cloud.api.call.RelayCall.java
@Override public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path, @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp, @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters) throws RestException, IOException { try {/* w w w. jav a 2 s. com*/ if (path.length < 2) { throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION, "No PUT on /relay"); } ControllerRelay relay = ControllerRelay.getRelay(path[1]); if (relay == null) { throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT, "Relay " + path[1] + " not found"); } BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder source = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { source.append(line); source.append(" "); } JSONObject object = new JSONObject(source.toString()); String action; if (object.has("action") && !object.isNull("action")) { action = object.getString("action"); } else { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION, "An invalid action was specified (or not specified) in the PUT"); } if (action.equalsIgnoreCase("update")) { if (userId != null) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED, "This API call may be called only by controller relays"); } update(relay, object, resp); } else if (action.equalsIgnoreCase("modify")) { if (object.has("relay")) { object = object.getJSONObject("relay"); } else { object = null; } if (object == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT, "No location was specified in the PUT"); } String name; if (object.has("name") && !object.isNull("name")) { name = object.getString("name"); } else { name = relay.getName(); } relay.modify(name); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION, "The action " + action + " is not a valid action."); } } catch (JSONException e) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON, "Invalid JSON in body"); } catch (PersistenceException e) { e.printStackTrace(); throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR, "Internal database error"); } }
From source file:cn.tiup.httpproxy.ProxyServlet.java
protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri, HttpServletRequest servletRequest) throws IOException { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity(//from w w w. jav a 2 s . c o m new InputStreamEntity(servletRequest.getInputStream(), getContentLength(servletRequest))); return eProxyRequest; }
From source file:it.greenvulcano.gvesb.adapter.http.utils.DumpUtils.java
public static void dump(HttpServletRequest request, StringBuffer log) throws IOException { String hN;/*from w w w . j a v a2 s . co m*/ 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())).append("\n"); log.append("---- Body END\n"); log.append("-- DUMP HttpServletRequest END \n"); }