Example usage for javax.servlet.http HttpServletRequest getInputStream

List of usage examples for javax.servlet.http HttpServletRequest getInputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getInputStream.

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:com.gwtquickstarter.server.Deferred.java

/**
 * Deserialize an object from an HttpServletRequest input stream. Does not
 * throw any exceptions; instead, exceptions are logged and null is returned.
 *
 * @param req An HttpServletRequest that contains a serialized object.
 * @return An object instance, or null if an exception occurred.
 *///from  w  w w .ja v a  2s . c  o  m
private static Object deserialize(HttpServletRequest req) {
    if (req.getContentLength() == 0) {
        log.severe("request content length is 0");
        return null;
    }
    try {
        byte[] bytesIn = new byte[req.getContentLength()];
        req.getInputStream().readLine(bytesIn, 0, bytesIn.length);
        return deserialize(bytesIn);
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error deserializing task", e);
        return null; // don't retry task
    }
}

From source file:eu.comvantage.dataintegration.QueryDistributionServiceImpl.java

private static String getBody(HttpServletRequest request) throws IOException {
    String body = null;/*from   w  w  w.j  ava2s .  c om*/
    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:gov.loc.ndmso.proxyfilter.RequestProxy.java

private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl)
        throws IOException {
    final String methodName = hsRequest.getMethod();
    final HttpMethod method;
    if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod postMethod = new PostMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        postMethod.setRequestEntity(inputStreamRequestEntity);
        method = postMethod;/*  w  w w. j  a v a2s.  co m*/
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else {
        // log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    @SuppressWarnings("unchecked")
    Enumeration<String> e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = e.nextElement();
            if ("host".equalsIgnoreCase(headerName)) {
                //the host value is set by the http client
                continue;
            } else if ("content-length".equalsIgnoreCase(headerName)) {
                //the content-length is managed by the http client
                continue;
            } else if ("accept-encoding".equalsIgnoreCase(headerName)) {
                //the accepted encoding should only be those accepted by the http client.
                //The response stream should (afaik) be deflated. If our http client does not support
                //gzip then the response can not be unzipped and is delivered wrong.
                continue;
            } else if (headerName.toLowerCase().startsWith("cookie")) {
                //fixme : don't set any cookies in the proxied request, this needs a cleaner solution
                continue;
            }

            @SuppressWarnings("unchecked")
            Enumeration<String> values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = values.nextElement();
                // log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    // add rs5/tomcat5 request header for ML
    method.addRequestHeader("X-Via", "tomcat5");

    // log.info("proxy query string " + method.getQueryString());
    return method;
}

From source file:com.ecbeta.common.util.JSONUtils.java

public static JSONObject toJSON(HttpServletRequest request) {
    MapJSONBean json = new MapJSONBean();
    for (Object s : request.getParameterMap().keySet()) {
        for (String value : request.getParameterValues(s.toString())) {
            json.add(s.toString(), value);
        }// w  ww.j a va 2 s .  c  om
    }

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        String data = "";
        while ((line = br.readLine()) != null) {
            data += line;
        }
        data = URLDecoder.decode(data, "UTF-8");
        try {
            JSONObject oo = JSONObject.fromObject(data);
            return oo;
        } catch (Exception ex) {
            Map<String, List<String>> params = parseParameters(data);
            for (Map.Entry<String, List<String>> entry : params.entrySet()) {
                for (String value : entry.getValue()) {
                    json.add(entry.getKey(), value);
                }
            }
        }

    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    JSONObject job = json.toJson();
    logger.info("~~~~~~~~~AutoCreating~~~~~~~~~");
    logger.info(json == null ? "" : job.toString(2));
    logger.info("~~~~~~~~~End~~~~~~~~~");
    return job;
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static JSONObject getPostedJson(HttpServletRequest httpRequest) throws Exception {
    StringBuffer jb = new StringBuffer();
    String line = null;//w w w . j a  v  a 2  s  .  c o  m
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpRequest.getInputStream()));
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        log.warning("Error receiving data:" + e);
        throw e;
    }
    log.debug("Posted Json:" + jb);
    try {
        return new JSONObject(jb.toString());
    } catch (Exception e) {
        log.warning("Error parsing JSON request string:" + jb);
    }
    return null;
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static String getPostedString(HttpServletRequest httpRequest) throws Exception {
    StringBuffer jb = new StringBuffer();
    String line = null;//from   w  ww  . j  av a  2  s .c om
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpRequest.getInputStream()));
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        log.warning("Error receiving data:" + e);
        throw e;
    }
    log.debug("Posted string:" + jb);
    try {
        return jb.toString();
    } catch (Exception e) {
        log.warning("Error parsing request string:" + jb);
    }
    return null;
}

From source file:com.nc.common.utils.HttpUtils.java

/**
 * <pre>//  ww  w .  ja  v a 2s . c om
 * 1.  : http  
 * 2.  : POST ?  response body  (multipart / urlencode)
 * </pre>
 *
 * @method Name : getBodyConts
 * @param HttpServletRequest request, int type
 * @return String
 * @throws Exception
 * 
 */
public static String getBodyConts(HttpServletRequest request, int type) throws Exception {
    int loopNo = 1;
    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                if (type == 1) {
                    if (loopNo == 2 || loopNo == 4) {
                        if (loopNo == 2) {
                            line = line.substring(line.indexOf("=") + 1, line.length());
                        } else if (loopNo == 4) {
                            if (line.indexOf("pageNo") > 0) {
                                line = ":" + line + ",";
                            } else {
                                line = ":\"" + line + "\",";
                            }
                        }
                        stringBuilder.append(line);
                    }

                    loopNo++;

                    if (loopNo > 4) {
                        loopNo = 1;
                    }
                } else if (type == 2) {
                    stringBuilder.append(line);
                }
            }
        }
    } catch (IOException ex) {
        throw new NCException(ex.getMessage(), ex);
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw new NCException(ex.getMessage(), ex);
            }
        }
    }

    body = stringBuilder.toString();

    if (type == 1) {
        body = body.substring(0, body.length() - 1);
        body = "{" + body + "}";
    }

    return body;
}

From source file:com.newatlanta.appengine.taskqueue.Deferred.java

/**
 * Deserialize an object from an HttpServletRequest input stream. Does not
 * throw any exceptions; instead, exceptions are logged and null is returned.
 *
 * @param req An HttpServletRequest that contains a serialized object.
 * @return An object instance, or null if an exception occurred.
 *//*from   w  w w. ja  v a  2  s .co m*/
private static Object deserialize(HttpServletRequest req) {
    if (req.getContentLength() == 0) {
        log.severe("request content length is 0");
        return null;
    }
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int len;
        while ((len = req.getInputStream().read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        return deserialize(baos.toByteArray());
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error deserializing task", e);
        return null; // don't retry task
    }
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static JSONObject getPostedPListXML(HttpServletRequest httpRequest) throws Exception {
    StringBuffer jb = new StringBuffer();
    StringBuffer jb2 = new StringBuffer();
    String line = null;/* w w w.j  a v a2s.  c om*/
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpRequest.getInputStream()));
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
        return parsePListFile(jb.toString());

    } catch (Exception e) {
        log.warning("Error receiving data:" + e);
        throw e;
    }

}

From source file:io.apiman.test.common.mock.EchoResponse.java

/**
 * Create an echo response from the inbound information in the http server
 * request./*  ww w.  j a v a2  s  .c  o m*/
 * @param request
 * @param withBody 
 * @return a new echo response
 */
public static EchoResponse from(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    response.setResource(request.getRequestURI());
    response.setUri(request.getRequestURI());
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String value = request.getHeader(name);
        response.getHeaders().put(name, value);
    }
    if (withBody) {
        long totalBytes = 0;
        InputStream is = null;
        try {
            is = request.getInputStream();
            MessageDigest sha1 = MessageDigest.getInstance("SHA1"); //$NON-NLS-1$
            byte[] data = new byte[1024];
            int read = 0;
            while ((read = is.read(data)) != -1) {
                sha1.update(data, 0, read);
                totalBytes += read;
            }
            ;

            byte[] hashBytes = sha1.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < hashBytes.length; i++) {
                sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            String fileHash = sb.toString();

            response.setBodyLength(totalBytes);
            response.setBodySha1(fileHash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    return response;
}