List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:com.surevine.alfresco.audit.listeners.PostAuditEventListener.java
/** * Assumes that the post content was a JSON string. * * @param postContent/*from ww w . ja va2 s . c o m*/ * from the request * @return valid JSONObject, otherwise null */ public static JSONObject parseJSONFromPostContent(final HttpServletRequest request) { if (request.getAttribute(REQUEST_ATTRIBUTE_JSON) != null) { return (JSONObject) request.getAttribute(REQUEST_ATTRIBUTE_JSON); } JSONObject retVal = null; InputStream inStream; try { inStream = request.getInputStream(); } catch (IOException eIO) { logger.error("Error encountered while reading from the request stream", eIO); return null; } InputStreamReader reader = new InputStreamReader(inStream); JSONTokener tokenizer = new JSONTokener(reader); try { retVal = new JSONObject(tokenizer); } catch (JSONException e) { // We will only warn in the logs if it was supposed to be JSON if ("application/json".equals(request.getHeader("Content-Type"))) { try { logger.warn("Invalid JSON string parsed from post content " + IOUtils.toString(request.getInputStream()), e); } catch (IOException e1) { logger.error("IOException caught parsing request stream", e1); } } } request.setAttribute(REQUEST_ATTRIBUTE_JSON, retVal); return retVal; }
From source file:be.solidx.hot.utils.IOUtils.java
public static Promise<byte[], Exception, Void> asyncRead(final HttpServletRequest req, final ExecutorService executorService, final ExecutorService promiseResolver) { final DeferredObject<byte[], Exception, Void> deferredObject = new DeferredObject<>(); try {//from w w w .ja v a2s . c om final ServletInputStream servletInputStream = req.getInputStream(); servletInputStream.setReadListener(new ReadListener() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void onError(final Throwable t) { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.reject(new Exception(t)); } }); } @Override public void onDataAvailable() throws IOException { executorService.execute(new Runnable() { @Override public void run() { byte b[] = new byte[2048]; int len = 0; try { while (servletInputStream.isReady() && (len = servletInputStream.read(b)) != -1) { baos.write(b, 0, len); } } catch (IOException e) { LOGGER.error("", e); } } }); } @Override public void onAllDataRead() throws IOException { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.resolve(baos.toByteArray()); } }); } }); } catch (final IOException e2) { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.reject(new Exception(e2)); } }); } catch (final IllegalStateException exception) { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.resolve("".getBytes()); } }); } // executorService.execute(new Runnable() { // @Override // public void run() { // final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // try { // IOUtils.toOutputStreamBuffered(req.getInputStream(), outputStream); // promiseResolver.execute(new Runnable() { // @Override // public void run() { // deferredObject.resolve(outputStream.toByteArray()); // } // }); // } catch (final IOException e) { // promiseResolver.execute(new Runnable() { // @Override // public void run() { // deferredObject.reject(e); // } // }); // } // } // }); return deferredObject.promise(); }
From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java
@SuppressWarnings({ "unchecked" }) private static StringEntity getEntity(HttpServletRequest request) throws IOException { if (APPLICATION_JSON.equalsIgnoreCase(request.getHeader("Content-type"))) { StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); char[] charBuffer = new char[512]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); }//from w w w . j ava 2s . com if (bufferedReader != null) { bufferedReader.close(); } } else { stringBuilder.append(""); } return new StringEntity(stringBuilder.toString(), "UTF-8"); } List<NameValuePair> formparams = new ArrayList<NameValuePair>(); Enumeration<String> en = request.getParameterNames(); while (en.hasMoreElements()) { String name = en.nextElement(); String value = request.getParameter(name); formparams.add(new BasicNameValuePair(name, value)); } return new UrlEncodedFormEntity(formparams, "UTF-8"); }
From source file:com.provenance.cloudprovenance.traceabilitystore.ws.controler.TraceabilityStoreController.java
/** * Get request body content/*from w w w . ja va 2s . c o m*/ * * @param request * @return string * @throws IOException */ public static String getBody(HttpServletRequest request) throws IOException { String body = null; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } else { stringBuilder.append(""); } } catch (IOException ex) { throw ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { throw ex; } } } body = stringBuilder.toString(); return body; }
From source file:org.acoustid.server.util.ParameterMap.java
public static ParameterMap parseRequest(HttpServletRequest request) throws IOException { String contentEncoding = request.getHeader("Content-Encoding"); if (contentEncoding != null) { contentEncoding = contentEncoding.toLowerCase(); }/*from ww w. j a v a2 s . c om*/ String contentType = request.getContentType(); Map<String, String[]> map; if ("gzip".equals(contentEncoding) && "application/x-www-form-urlencoded".equals(contentType)) { InputStream inputStream = new GZIPInputStream(request.getInputStream()); InputStreamEntity entity = new InputStreamEntity(inputStream, -1); entity.setContentType(contentType); map = new HashMap<String, String[]>(); for (NameValuePair param : URLEncodedUtils.parse(entity)) { String name = param.getName(); String value = param.getValue(); String[] values = map.get(name); if (values == null) { values = new String[] { value }; } else { values = (String[]) ArrayUtils.add(values, value); } map.put(name, values); } } else { map = request.getParameterMap(); } return new ParameterMap(map); }
From source file:elw.web.ControllerElw.java
protected static InputSupplier<InputStream> supplierForRequest(final HttpServletRequest myReq) { return new InputSupplier<InputStream>() { public InputStream getInput() throws IOException { return myReq.getInputStream(); }/*from w ww . ja v a2 s.c om*/ }; }
From source file:controllers.IndexServlet.java
private static void Track(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) { String userAddress = request.getParameter("userAddress"); String fileName = request.getParameter("fileName"); String storagePath = DocumentManager.StoragePath(fileName, userAddress); String body = ""; try {//from w ww.ja v a 2s . co m Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A"); body = scanner.hasNext() ? scanner.next() : ""; } catch (Exception ex) { writer.write("get request.getInputStream error:" + ex.getMessage()); return; } if (body.isEmpty()) { writer.write("empty request.getInputStream"); return; } JSONParser parser = new JSONParser(); JSONObject jsonObj; try { Object obj = parser.parse(body); jsonObj = (JSONObject) obj; } catch (Exception ex) { writer.write("JSONParser.parse error:" + ex.getMessage()); return; } long status = (long) jsonObj.get("status"); if (status == 2 || status == 3)//MustSave, Corrupted { String downloadUri = (String) jsonObj.get("url"); int saved = 1; try { URL url = new URL(downloadUri); java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); InputStream stream = connection.getInputStream(); if (stream == null) { throw new Exception("Stream is null"); } File savedFile = new File(storagePath); try (FileOutputStream out = new FileOutputStream(savedFile)) { int read; final byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); } connection.disconnect(); } catch (Exception ex) { saved = 0; } } writer.write("{\"error\":0}"); }
From source file:com.jadyounan.Packager.java
/** * Servlet handler , should listen on the callback URL (as in webServiceURL) * @param requestPath// w ww. ja v a 2 s .c om * @param req * @param servletRequest * @param servletResponse * @throws Exception */ public static void handle(String requestPath, Request req, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception { StringTokenizer st = new StringTokenizer(requestPath, "/"); st.nextToken(); String companyDomain = st.nextToken(); String version = st.nextToken(); byte bytes[] = new byte[] {}; switch (st.nextToken().toLowerCase()) { case "log": { bytes = new byte[] {}; byte r[] = org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream()); System.out.println("LOG " + new String(r)); } break; case "devices": { String deviceID = st.nextToken(); String authToken = req.getHeader("Authorization").split(" ")[1]; // use the authToken to get the userID who started the request switch (servletRequest.getMethod().toUpperCase()) { case "DELETE": //handle deleting the token from your database break; default: { //handle adding the token/deviceID to your database } break; } FLUSH.updatePushDevices(userID); bytes = new byte[] {}; } break; case "pushpackages": { /** * Safari requests the pacakge */ String id = st.nextToken(); JSONObject obj = new JSONObject( new String(org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream()))); String userID = obj.getString("user_id"); String authenticationToken = "..a random string so you can later identify the user who started the request"; bytes = createPackageFile(authenticationToken); } break; default: bytes = new byte[] {}; break; } servletResponse.setStatus(200); servletResponse.setContentLength(bytes.length); try (OutputStream out = servletResponse.getOutputStream()) { out.write(bytes); out.flush(); } }
From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java
private static Object deserialize(HttpServletRequest req) throws Exception { if (req.getContentLength() == 0) { return null; }//from w w w . jav a 2 s . c o m byte[] bytesIn = new byte[req.getContentLength()]; req.getInputStream().readLine(bytesIn, 0, bytesIn.length); if (isDevelopment()) { // workaround for issue #2097 bytesIn = decodeBase64(bytesIn); } ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream(new ByteArrayInputStream(bytesIn))); try { return objectIn.readObject(); } finally { objectIn.close(); } }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same standard POST data * as was sent in the given {@link HttpServletRequest} * * @param methodProxyRequest The {@link org.apache.commons.httpclient.methods.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 org.apache.commons.httpclient.methods.PostMethod} * @param history The {@link com.groupon.odo.proxylib.models.History} log for this request *///from w w w.j av a2s . c o m @SuppressWarnings("unchecked") public static void handleStandardPost(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest, History history) throws Exception { String deserialisedMessages = ""; byte[] requestByteArray = null; // Create a new StringBuffer with the data to be passed StringBuilder requestBody = new StringBuilder(); InputStream body = httpServletRequest.getInputStream(); java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A"); if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_FORM_URLENCODED)) { // Get the client POST data as a Map if content type is: application/x-www-form-urlencoded // We do this manually since some data is not properly parseable by the servlet request Map<String, String[]> mapPostParameters = HttpUtilities.mapUrlEncodedParameters(httpServletRequest); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParameterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list // add an & if there is already data if (requestBody.length() > 0) { requestBody.append("&"); } requestBody.append(stringParameterName); // not everything has a value so lets check if (stringParameterValue.length() > 0) { requestBody.append("="); requestBody.append(stringParameterValue); } } } } else if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { /** * Convert input stream to bytes for it to be read by the deserializer * Unpack and iterate the list to see the contents */ MessagePack msgpack = new MessagePack(); requestByteArray = IOUtils.toByteArray(body); ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(requestByteArray); Unpacker unpacker = msgpack.createUnpacker(byteArrayIS); for (Value message : unpacker) { deserialisedMessages += message; deserialisedMessages += "\n"; } } else { // just set the request body to the POST body if (s.hasNext()) { requestBody.append(s.next()); } } // Set the proxy request data StringRequestEntity stringEntity = new StringRequestEntity(requestBody.toString(), null, null); // set post body in history object history.setRequestPostData(requestBody.toString()); // set post body in proxy request object methodProxyRequest.setRequestEntity(stringEntity); /** * Set the history to have decoded messagepack. Pass the byte data back to request */ if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { history.setRequestPostData(deserialisedMessages); ByteArrayRequestEntity byteRequestEntity = new ByteArrayRequestEntity(requestByteArray); methodProxyRequest.setRequestEntity(byteRequestEntity); } }