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:org.chtijbug.drools.platform.web.annotation.JsonPathArgumentResolver.java

private String getRequestBody(NativeWebRequest webRequest) {
    HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
    String jsonBody = (String) servletRequest.getAttribute(JSONBODYATTRIBUTE);
    if (jsonBody == null) {
        try {/*from   www  .  j a  v  a 2 s.c om*/
            String body = IOUtils.toString(servletRequest.getInputStream());
            servletRequest.setAttribute(JSONBODYATTRIBUTE, body);
            return body;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return jsonBody;

}

From source file:br.com.munif.personalsecurity.aplicacao.autorizacao.Login.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");

    Map<String, Object> map = mapper.readValue(request.getInputStream(), Map.class);
    System.out.println("---------->" + map);

    Usuario usuario = service.loga("" + map.get("user"), "" + map.get("password"));

    mapper.writeValue(response.getOutputStream(), TokenAdapter.getLoginData(usuario));

}

From source file:com.thinkberg.moxo.dav.PropFindHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {//from  ww  w . j  av  a  2  s .  c om
        Document propDoc = saxReader.read(request.getInputStream());
        // log(propDoc);
        Element propFindEl = propDoc.getRootElement();
        Element propEl = (Element) propFindEl.elementIterator().next();
        String propElName = propEl.getName();

        List<String> requestedProperties = new ArrayList<String>();
        boolean ignoreValues = false;
        if (TAG_PROP.equals(propElName)) {
            for (Object id : propEl.elements()) {
                requestedProperties.add(((Element) id).getName());
            }
        } else if (TAG_ALLPROP.equals(propElName)) {
            requestedProperties = DavResource.ALL_PROPERTIES;
        } else if (TAG_PROPNAMES.equals(propElName)) {
            requestedProperties = DavResource.ALL_PROPERTIES;
            ignoreValues = true;
        }

        FileObject object = getResourceManager().getFileObject(request.getPathInfo());
        if (object.exists()) {
            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusRespons(object, requestedProperties,
                    getBaseUrl(request), getDepth(request), ignoreValues);
            //log(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            writer.flush();
            writer.close();

        } else {
            log("!! " + object.getName().getPath() + " NOT FOUND");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (DocumentException e) {
        log("!! inavlid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.nominanuda.web.http.ServletHelper.java

/**
 * @param servletRequest/* ww w . j  ava 2s  . c  om*/
 * @return an InputStream that contains at least one byte or null if underlying stream is null or empty
 * @throws IOException if thrown while accessing the underlying ServletInputStream
 */
public @Nullable InputStream getServletRequestBody(HttpServletRequest servletRequest) throws IOException {
    ServletInputStream sis = servletRequest.getInputStream();
    if (servletRequest.getContentLength() > 0) {
        return sis;
    } else {
        return null;
    }
}

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

@Test
public void testCallToNonSecureClusterWithoutDelegationToken() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(false).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("a=123").anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertFalse("buffering in non secure cluster", (httpEntity instanceof PartiallyRepeatableHttpEntity));
}

From source file:org.fusesource.restygwt.examples.server.GreetingServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("Creating custom greeting.");
    try {// w ww.jav  a 2s .c o  m
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode nameObject = mapper.readValue(req.getInputStream(), ObjectNode.class);
        String name = nameObject.get("name").asText();

        String greeting = "Hello " + name;
        ObjectNode resultObject = new ObjectNode(JsonNodeFactory.instance);
        resultObject.put("greeting", greeting);
        mapper.writeValue(resp.getOutputStream(), resultObject);
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        System.out.flush();
        System.err.flush();
    }
}

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

public static File getUploadedFile(HttpServletRequest httpRequest) {
    String uploadDirPath = EPADConfig.getEPADWebServerFileUploadDir() + "temp"
            + Long.toString(System.currentTimeMillis());
    File uploadDir = new File(uploadDirPath);
    uploadDir.mkdirs();//from  ww w .  j ava2s .  com
    String fileName = httpRequest.getParameter("fileName");
    String tempXMLFileName = "temp" + System.currentTimeMillis() + "-annotation.xml";
    if (fileName != null)
        tempXMLFileName = "temp" + System.currentTimeMillis() + "-" + fileName;
    File uploadedFile = new File(uploadDir, tempXMLFileName);
    try {
        // opens input stream of the request for reading data
        InputStream inputStream = httpRequest.getInputStream();

        // opens an output stream for writing file
        FileOutputStream outputStream = new FileOutputStream(uploadedFile);

        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        log.info("Receiving data...");
        int len = 0;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            len = len + bytesRead;
            outputStream.write(buffer, 0, bytesRead);
        }

        log.debug("Data received, len:" + len);
        outputStream.close();
        inputStream.close();
        if (len == 0) {
            try {
                uploadedFile.delete();
                uploadDir.delete();
            } catch (Exception x) {
            }
            uploadedFile = null;
        } else
            log.debug("Created File:" + uploadedFile.getAbsolutePath());
        if (len > 0 && (tempXMLFileName.endsWith(".xml") || tempXMLFileName.endsWith(".txt"))) {
            log.debug("PUT Data:" + readFile(uploadedFile));
        }
        //         if (fileType != null)
        //         {
        //            File changeFileExt = new File(uploadedFile.getParentFile(), tempXMLFileName.substring(0, tempXMLFileName.length()-3) + fileType);
        //            uploadedFile.renameTo(changeFileExt);
        //            uploadedFile = changeFileExt;
        //         }
        return uploadedFile;
    } catch (Exception x) {
        log.warning("Error receiving Annotations file", x);
    }
    return null;
}

From source file:com.zextras.zimbradrive.UploadFileHttpHandler.java

private HttpEntity createUploadFileRequest(HttpServletRequest httpServletRequest, String formBoundary,
        Account userAccount) throws IOException {
    InputStream userRequestInputStream = httpServletRequest.getInputStream();
    String userInfoPartsString = createUserInfoInFormStyle(userAccount, formBoundary);
    String internalFormPartsBoundary = getInternalBodyBoundary(formBoundary);
    List<InputStream> payloadStreamToSendToDrive = Arrays.asList(
            new ByteArrayInputStream(userInfoPartsString.getBytes()),
            new ByteArrayInputStream(internalFormPartsBoundary.getBytes()), userRequestInputStream // TODO: This inputStreams will be closed?
    );/*from w  w w .  ja  v  a  2s  .c  o m*/

    SequenceInputStream payloadToSendToDriveInputStream = new SequenceInputStream(
            Collections.enumeration(payloadStreamToSendToDrive));

    int contentLength = httpServletRequest.getIntHeader(HTTP.CONTENT_LEN);
    int diffInternalFormPartsBoundaryAndFirstBodyBoundary = 2; // getFirstBodyBoundary(boundaryOfParts) - getInternalBodyBoundary(formBoundary)
    contentLength = contentLength + userInfoPartsString.length()
            + diffInternalFormPartsBoundaryAndFirstBodyBoundary;
    return new InputStreamEntity(payloadToSendToDriveInputStream, contentLength);
}

From source file:edu.uci.ics.asterix.api.http.servlet.RESTAPIServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringWriter sw = new StringWriter();
    IOUtils.copy(request.getInputStream(), sw, StandardCharsets.UTF_8.name());
    String query = sw.toString();
    handleRequest(request, response, query);
}

From source file:org.deegree.securityproxy.authentication.wass.AddParameterAnonymousAuthenticationFilterTest.java

@Test
public void testDoFilterWithPostRequest() throws Exception {
    AddParameterAnonymousAuthenticationFilter filter = createFilter(PARAMETER_VALUE);
    FilterChain filterChain = mockChain();
    HttpServletResponse response = mockResponse();

    filter.doFilter(mockPostRequest(), response, filterChain);

    ArgumentCaptor<ServletRequest> argument = ArgumentCaptor.forClass(ServletRequest.class);
    verify(filterChain).doFilter(argument.capture(), eq(response));
    HttpServletRequest passedRequest = (HttpServletRequest) argument.getValue();

    String requestAsString = IOUtils.toString(passedRequest.getInputStream());

    assertThat(requestAsString, is(PARAMETER_VALUE));
}