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.esri.gpt.control.search.ServletSavedSearch.java

/**
 * Delete saved search.// w  ww  .j  ava  2 s . c o  m
 * 
 * @param request the request
 * @param response the response
 * @param context the context
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws SearchException the search exception
 * @throws JSONException the jSON exception
 */
private void deleteSavedSearch(HttpServletRequest request, HttpServletResponse response, RequestContext context)
        throws IOException, SearchException, JSONException {
    String url = IOUtils.toString(request.getInputStream(), "UTF-8");
    Map<String, String> urlParams = urlToParamMap(url);
    String id = Val.chkStr(urlParams.get("id"));
    if (id.equals("")) {
        id = Val.chkStr(request.getParameter("id"));
    }
    ISearchSaveRepository saveRpstry = SearchSaveRpstryFactory.getSearchSaveRepository();
    if (saveRpstry instanceof GptRepository) {
        ((GptRepository) saveRpstry).setRequestContext(context);
    }
    saveRpstry.delete(id, context.getUser());
    writeSavedSearches(request, response, context);

}

From source file:org.eclipse.jgit.lfs.server.LfsProtocolServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Writer w = new BufferedWriter(new OutputStreamWriter(res.getOutputStream(), UTF_8));

    Reader r = new BufferedReader(new InputStreamReader(req.getInputStream(), UTF_8));
    LfsRequest request = gson.fromJson(r, LfsRequest.class);
    String path = req.getPathInfo();

    res.setContentType(CONTENTTYPE_VND_GIT_LFS_JSON);
    LargeFileRepository repo = null;// w w w  .  j  av  a 2 s.  c  o  m
    try {
        repo = getLargeFileRepository(request, path);
        if (repo == null) {
            String error = MessageFormat.format(LfsText.get().lfsFailedToGetRepository, path);
            LOG.error(error);
            throw new LfsException(error);
        }
        res.setStatus(SC_OK);
        TransferHandler handler = TransferHandler.forOperation(request.operation, repo, request.objects);
        gson.toJson(handler.process(), w);
    } catch (LfsValidationError e) {
        sendError(res, w, SC_UNPROCESSABLE_ENTITY, e.getMessage());
    } catch (LfsRepositoryNotFound e) {
        sendError(res, w, SC_NOT_FOUND, e.getMessage());
    } catch (LfsRepositoryReadOnly e) {
        sendError(res, w, SC_FORBIDDEN, e.getMessage());
    } catch (LfsRateLimitExceeded e) {
        sendError(res, w, SC_RATE_LIMIT_EXCEEDED, e.getMessage());
    } catch (LfsBandwidthLimitExceeded e) {
        sendError(res, w, SC_BANDWIDTH_LIMIT_EXCEEDED, e.getMessage());
    } catch (LfsInsufficientStorage e) {
        sendError(res, w, SC_INSUFFICIENT_STORAGE, e.getMessage());
    } catch (LfsUnavailable e) {
        sendError(res, w, SC_SERVICE_UNAVAILABLE, e.getMessage());
    } catch (LfsUnauthorized e) {
        sendError(res, w, SC_UNAUTHORIZED, e.getMessage());
    } catch (LfsException e) {
        sendError(res, w, SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        w.flush();
    }
}

From source file:com.tbodt.jswerve.servlet.JSwerveServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getMethod().equals("OPTIONS")) {
        serviceOptions(req, resp);/*from w ww  .  j  ava 2 s  . c  om*/
        return;
    }

    HttpMethod method = HttpMethod.valueOf(req.getMethod());
    URI uri = extractUri(req);
    Headers headers = translateHeaders(req);
    Content content = new Content(IOUtils.toByteArray(req.getInputStream()), req.getContentType());
    Request request = new Request(method, uri, headers, content);
    try {
        Response response = website.service(request);
        resp.setStatus(response.getStatus().getCode());
        for (Map.Entry<String, String> header : response.getHeaders())
            resp.setHeader(header.getKey(), header.getValue());
        resp.getOutputStream().write(response.getBody().getData());
    } catch (StatusCodeException ex) {
        resp.setStatus(ex.getStatusCode().getCode());
        ex.printStackTrace(resp.getWriter());
    }
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;/*from  w w  w .  j a  v  a  2 s  .  c o  m*/
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }
    GatewayConfig config = (GatewayConfig) request.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    if (config != null && config.isHadoopKerberosSecured()) {
        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (replayBufferSize < 0) {
            replayBufferSize = config.getHttpServerRequestBuffer();
        }
        if (!delegationTokenPresent && replayBufferSize > 0) {
            entity = new PartiallyRepeatableHttpEntity(entity, replayBufferSize);
        }
    }

    return entity;
}

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

@Before
@Override/*from  w  ww . j  a v a 2  s. c  o m*/
public void setUp() throws Exception {
    super.setUp();

    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    org.apache.catalina.Context context = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    privateAppFilter = new PrivateAppFilter();
    privateAppFilter.setSecretKey(secretKey);
    privateAppFilter.setEnabled(true);

    FilterDef filterDef = new FilterDef();
    filterDef.setFilter(privateAppFilter);
    filterDef.setFilterName(PrivateAppFilter.class.getName());
    context.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(PrivateAppFilter.class.getName());
    filterMap.addURLPattern("*");
    context.addFilterMap(filterMap);

    context.addFilterDef(filterDef);

    Tomcat.addServlet(context, "hello-servlet", new HttpServlet() {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            System.out.println(req.getRequestURL());
            IoUtils2.flush(req.getInputStream(), System.out);
            Enumeration<String> headers = req.getHeaderNames();
            while (headers.hasMoreElements()) {
                String header = headers.nextElement();
                System.out.println("   " + header + ": " + req.getHeader(header));
            }
            resp.addHeader("x-response", "hello");
            resp.getWriter().println("Hello world!");
        }
    });
    context.addServletMapping("/*", "hello-servlet");

    tomcat.start();

    httpClient = new DefaultHttpClient();
    httpHost = new HttpHost("localhost", getPort());
}

From source file:org.apache.shindig.social.core.oauth2.OAuth2NormalizedRequest.java

private String getBodyAsString(HttpServletRequest request) {
    if (request.getContentLength() == 0) {
        return "";
    }//from w  w  w . j  ava2  s  . c om
    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) {
        LOG.logp(Level.WARNING, classname, "getBodyAsString", MessageKeys.INVALID_OAUTH, ioe);
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.alfresco.encryption.DefaultEncryptionUtils.java

/**
 * {@inheritDoc}/*from  www .  ja v a 2  s  .  c  o m*/
 */
@Override
public byte[] decryptBody(HttpServletRequest req) throws IOException {
    if (req.getMethod().equals("POST")) {
        InputStream bodyStream = req.getInputStream();
        if (bodyStream != null) {
            // expect algorithParameters header
            AlgorithmParameters p = decodeAlgorithmParameters(req);

            // decrypt the body
            InputStream in = encryptor.decrypt(KeyProvider.ALIAS_SOLR, p, bodyStream);
            return IOUtils.toByteArray(in);
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.github.restdriver.clientdriver.unit.ClientDriverHandlerTest.java

/**
 * with no expectations set, and a request made, the handler throws an error upon verification
 *//*ww w.j  a va2 s  .  c  o  m*/
@Test
public void testUnexpectedRequest() throws IOException, ServletException {

    Request mockRequest = mock(Request.class);
    HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockHttpResponse = mock(HttpServletResponse.class);

    when(mockHttpRequest.getMethod()).thenReturn("POST");
    when(mockHttpRequest.getPathInfo()).thenReturn("yarr");
    when(mockHttpRequest.getQueryString()).thenReturn("gooo=gredge");
    when(mockHttpRequest.getInputStream()).thenReturn(new DummyServletInputStream(IOUtils.toInputStream("")));

    try {
        sut.handle("", mockRequest, mockHttpRequest, mockHttpResponse);
        Assert.fail();
    } catch (ClientDriverFailedExpectationException e) {
        assertThat(e.getMessage(), containsString("1 unexpected request(s):"));
        assertThat(e.getMessage(), containsString("POST yarr; PARAMS: [gooo=[gredge]];"));
    }
}

From source file:nl.tue.gale.ae.JSONServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ApplicationContext applicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());

    UMCache um = (UMCache) applicationContext.getBean("umCache");
    CacheSession<EntityValue> session = um.openSession();
    try {//  w  w  w.  j  ava2  s .c  o m
        JSONParser parser = new JSONParser(req.getInputStream());
        JSONArray array = (JSONArray) parser.nextValue();
        for (JSONValue value : array.getValue())
            addToUM((JSONObject) value, session);
        session.commit();
    } catch (Exception e) {
        e.printStackTrace();
        error(e, resp);
    } finally {
        if (session.isOpen())
            session.rollback();
    }
    reply("succes", resp);
}