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:net.duckling.ddl.web.controller.team.ConfigTeamController.java

@RequestMapping(params = "func=uploadMailList", headers = { "X-File-Name" })
public void uploadMailList(HttpServletRequest request, HttpServletResponse response) throws IOException {
    InputStream in = request.getInputStream();
    String fileName = request.getHeader("X-File-Name");
    uploadMailListCommon(fileName, in, response);
}

From source file:org.openxdata.server.servlet.FormDownloadServlet.java

private void uploadData(HttpServletRequest request, HttpServletResponse response) throws IOException {
    byte status = OpenXDataConstants.STATUS_NULL;

    try {//from w  ww  .  j  av a 2s.  c  om
        if (OpenXDataConstants.TRUE_TEXT_VALUE
                .equalsIgnoreCase(request.getParameter(OpenXDataConstants.REQUEST_PARAM_BATCH_ENTRY))) {
            try {

                String serializerKey = request.getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER);
                XformSerializer formSerializer = serializationService.getFormSerializer(serializerKey);
                List<String> xforms = formSerializer.deSerialize(request.getInputStream(), getXforms());
                if (xforms != null) {
                    for (String xml : xforms)
                        processForm(xml);

                    status = OpenXDataConstants.STATUS_SUCCESS;
                } else {
                    status = OpenXDataConstants.STATUS_FAILURE;
                    formSerializer.serializeFailure(response.getOutputStream(),
                            new Exception("No forms returned from the serializer"));
                    log.warn("No forms returned by the serializer");
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
                status = OpenXDataConstants.STATUS_FAILURE;
            }
        } else {

            User user = authenticationService.authenticate(request.getParameter("uname"),
                    request.getParameter("pw"));
            if (user == null)
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            else {
                response.setContentType("text/html");
                String form = getRequestAsString(request);
                processForm(form);
            }
        }
    } catch (Exception ex) {
        if (status == OpenXDataConstants.STATUS_NULL) {
            PrintWriter out = response.getWriter();
            out.println("<HTML><HEAD><TITLE>Form Submission Status</TITLE>"
                    + "</HEAD><BODY>Problem submitting form! <BR /> " + ex.getMessage() + "</BODY></HTML>");
            out.close();
        }
    }
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * Get the request body.//w w  w.  j  av  a  2s.c  om
 *
 * @param request the request.
 * @return the body as a string.
 * @throws IOException
 */
private String getRequestBody(HttpServletRequest request) throws IOException {
    final String contentEncoding = request.getHeader("Content-Encoding");
    if (contentEncoding != null && contentEncoding.contains("gzip")) {
        // then treat the request body as gzip:
        final GZIPInputStream gzipIn = new GZIPInputStream(request.getInputStream());
        final String gunzippedEncodedJson = IOUtils.toString(gzipIn);
        gzipIn.close();
        return gunzippedEncodedJson;
    } else {
        // otherwise assume plain-text:
        return IOUtils.toString(request.getReader());
    }
}

From source file:edu.utah.further.i2b2.hook.further.FurtherInterceptionFilter.java

/**
 * Send the i2b2 query request message to the FURTHeR FQE. Must be run after the i2b2
 * processing chain, because it depends on the i2b2 query ID generated by the i2b2
 * server.//from  w w  w  .  j a  va  2s .  c  o  m
 * 
 * @param request
 * @param i2b2QueryId
 *            i2b2 query ID, obtained from the i2b2 response
 */
private void spawnFurtherRequest(final HttpServletRequest request, final long i2b2QueryId) {
    if (log.isDebugEnabled()) {
        log.debug("Read i2b2QueryId from request: " + i2b2QueryId);
    }
    try {
        // Need to read create from request.getInputStream() multiple times
        // in this method ==> save a copy in a buffer first
        // inputStream is already at the end of the file.
        final InputStream inputStream = request.getInputStream();
        final byte[] buffer = CoreUtil.readBytesFromStream(inputStream);
        inputStream.close();

        // Decide whether to fork or not
        if (StringUtil.isValidLong(i2b2QueryId) && isProcessRequest(buffer)) {
            // Read the FURTHeR section of the i2b2 request body
            final String requestXml = new String(buffer);
            // Request contains an FQE processing flag, send to FURTHeR
            if (log.isDebugEnabled()) {
                ServletUtil.printRequestHeaders(request);
                ServletUtil.printRequestParameters(request);
                ServletUtil.printRequestAttributes(request);
            }

            // TODO: read query instance id from i2b2 response and pass to the
            // following call
            final QueryContextIdentifier id = furtherServices.i2b2QueryRequest(requestXml, i2b2QueryId);

            // Make available to response through the request, ensures thread safety
            // instead of using instance var
            request.setAttribute(QUERY_ID, id);

            QueryState state = furtherServices.getQueryState(id).getState();

            final StopWatch stopWatch = new StopWatch();

            final int interval = 10;
            int i = 0;
            stopWatch.start();
            // Poll state every sec
            final long maxQueryTimeMillis = furtherServices.getMaxQueryTime() * 1000;
            while (state != QueryState.COMPLETED && state != QueryState.STOPPED && state != QueryState.FAILED
                    && state != QueryState.INVALID && state != null
                    && stopWatch.getTime() < maxQueryTimeMillis) {
                Thread.yield();
                state = furtherServices.getQueryState(id).getState();

                if (log.isDebugEnabled() && ((i % interval) == 0)) {
                    log.debug("QueryState for query " + id.getId() + ": " + state);
                }

                i++;
            }
            stopWatch.stop();
        } else {
            if (log.isDebugEnabled()) {
                log.info("Ignoring unrecognized/irrelvant requestXml");
            }
        }
    } catch (final Throwable throwable) {
        if (log.isDebugEnabled()) {
            log.error("Caught " + throwable + ", ignoring", throwable);
        }
    }
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/*from  w w w . j  a  va 2  s .  c o  m*/

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

    if (postMethod instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) postMethod)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

    monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod);
    }
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

    monitor.fireAfterProxy(request, response, postMethod, capturedData);

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // copy headers to response
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (String name : responseHeaders.keySet()) {
        for (String header : responseHeaders.get(name))
            httpResponse.addHeader(name, header);

    }

    IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}

From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java

/**
 * Returns the request that points to the backend service defined by the provided 
 * <code>urlToService</code> URL. The headers of the origin request are copied to 
 * the backend request, except of "host" and "content-length".   
 * // w ww.  j  a va 2s.c  om
 * @param request
 *            original request to the Web application
 * @param urlToService
 *            URL to the targeted backend service
 * @return initialized backend service request
 * @throws IOException 
 */
private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException {
    String method = request.getMethod();
    LOGGER.debug("HTTP method: " + method);

    HttpRequestBase backendRequest = null;
    if (HttpPost.METHOD_NAME.equals(method)) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipe(request.getInputStream(), out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        entity.setContentType(request.getHeader("Content-Type"));
        HttpPost post = new HttpPost(urlToService);
        post.setEntity(entity);
        backendRequest = post;
    } else if (HttpGet.METHOD_NAME.equals(method)) {
        HttpGet get = new HttpGet(urlToService);
        backendRequest = get;
    } else if (HttpPut.METHOD_NAME.equals(method)) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipe(request.getInputStream(), out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        entity.setContentType(request.getHeader("Content-Type"));
        HttpPut put = new HttpPut(urlToService);
        put.setEntity(entity);
        backendRequest = put;
    } else if (HttpDelete.METHOD_NAME.equals(method)) {
        HttpDelete delete = new HttpDelete(urlToService);
        backendRequest = delete;
    }

    // copy headers from Web application request to backend request, while
    // filtering the blocked headers

    LOGGER.debug("backend request headers:");

    Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS));

    Enumeration<String> setCookieHeaders = request.getHeaders("Cookie");
    while (setCookieHeaders.hasMoreElements()) {
        String cookieHeader = setCookieHeaders.nextElement();
        if (blockedHeaders.contains(cookieHeader.toLowerCase())) {
            String replacedCookie = removeJSessionID(cookieHeader);
            backendRequest.addHeader("Cookie", replacedCookie);
        }
        LOGGER.debug("Cookie header => " + cookieHeader);
    }

    for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
        String headerName = e.nextElement().toString();
        if (!blockedHeaders.contains(headerName.toLowerCase())) {
            backendRequest.addHeader(headerName, request.getHeader(headerName));
            LOGGER.debug("    => " + headerName + ": " + request.getHeader(headerName));
        } else {
            LOGGER.debug("    => " + headerName + ": blocked request header");
        }
    }

    return backendRequest;
}

From source file:gwap.game.quiz.PlayNCommunicationResource.java

private void doWork(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // HttpSession session = request.getSession();
    this.request = request;
    this.response = response;

    ses = request.getSession();/*  w w w  . j  av a 2 s.  c o  m*/
    SessionTracker.instance().add(ses);

    // }

    // give it ten trys to find a valid game configuration
    for (int ii = 0; ii < 10; ++ii) {
        JSONObject jsonObject = createJSONObjectForNewGame();
        if (jsonObject != null) {

            jsonObject.put("SID", ses.getId());
            InputStream instream = null;
            OutputStream outstream = null;

            try {
                instream = request.getInputStream();
                response.setContentType("text/plain");
                outstream = response.getOutputStream();
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outstream));
                jsonObject.writeJSONString(out);
                out.flush();
                outstream.flush();
                outstream.close();

                instream.close();
                logger.info("Successfully initialized game");
                break;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            logger.info("Couldn't initialize a game in try no." + ii);
        }

    }

}

From source file:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 * //from w ww  .ja v  a2 s.  c  o  m
 * @param req the HTTP request.
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        @Override
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

        @Override
        public String getContentType() {
            return req.getContentType();
        }

        @Override
        @Deprecated
        public int getContentLength() {
            return req.getContentLength();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.MultiPartRequest.java

/** Constructor. 
 * @param request The request containing a multipart/form-data
 * request//www  .  j  a v  a2s  .c om
 * @exception IOException IOException
 */
public MultiPartRequest(HttpServletRequest request) throws IOException {
    _request = request;
    String content_type = request.getHeader(HttpFields.__ContentType);
    if (!content_type.startsWith("multipart/form-data"))
        throw new IOException("Not multipart/form-data request");

    if (log.isDebugEnabled())
        log.debug("Multipart content type = " + content_type);
    _encoding = request.getCharacterEncoding();
    if (_encoding != null)
        _in = new LineInput(request.getInputStream(), 2048, _encoding);
    else
        _in = new LineInput(request.getInputStream());

    // Extract boundary string
    _boundary = "--" + value(content_type.substring(content_type.indexOf("boundary=")));

    if (log.isDebugEnabled())
        log.debug("Boundary=" + _boundary);
    _byteBoundary = (_boundary + "--").getBytes(StringUtil.__ISO_8859_1);

    loadAllParts();
}

From source file:br.org.indt.ndg.servlets.DownloadClient.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("Started processing stream from " + request.getRemoteAddr());
    log.info("User: " + request.getParameter("user"));

    InputStreamReader dis = new InputStreamReader(request.getInputStream(), "UTF-8");
    DataOutputStream dos = new DataOutputStream(response.getOutputStream());

    if (dis != null) {
        BufferedReader reader = new BufferedReader(dis);
        StringBuffer tempBuffer = new StringBuffer();
        String line = null;// w w w.j  a v  a 2  s. c o m

        if (validateUser(request.getParameter("user"), request.getParameter("psw"))) {
            while ((line = reader.readLine()) != null) {
                tempBuffer.append(line + '\n');
                log.info(line);
            }

            try {
                msmBD.postSurvey(request.getParameter("user"), tempBuffer, createTransactionLogVO(request),
                        false);
                dos.writeBytes(SUCCESS);
            } catch (MSMApplicationException e) {
                dos.writeBytes(FAILURE);
                e.printStackTrace();
            } catch (MSMSystemException e) {
                dos.writeBytes(FAILURE);
                e.printStackTrace();
            }
        } else {
            dos.writeBytes(USERINVALID);
            log.info("User invalid, returning " + USERINVALID + " to " + request.getRemoteAddr());
        }

        reader.close();
        dos.close();
    } else {
        dos.writeBytes(FAILURE);
        log.info("Failed processing stream from " + request.getRemoteAddr());
    }
}