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.springframework.extensions.webscripts.connector.RemoteClient.java

/**
 * Call a remote WebScript uri. The endpoint as supplied in the constructor will be used
 * as the prefix for the full WebScript url.
 * //  ww w . jav a2 s  . c om
 * @param uri    WebScript URI - for example /test/myscript?arg=value
 * @param req    HttpServletRequest the request to retrieve input and headers etc. from
 * @param res    HttpServletResponse the response to stream response to - will be closed automatically.
 *               A response data string will not therefore be available in the Response object.
 *               The HTTP method to be used should be set via the setter otherwise GET will be assumed
 *               and the InputStream will not be retrieve from the request.
 *               If remote call returns a status code then any available error response will be
 *               streamed into the response object. 
 *               If remote call fails completely the OutputStream will not be modified or closed.
 * 
 * @return Response object from the call {@link Response}
 */
public Response call(String uri, HttpServletRequest req, HttpServletResponse res) {
    Response result;
    ResponseStatus status = new ResponseStatus();
    try {
        boolean isPush = (requestMethod == HttpMethod.POST || requestMethod == HttpMethod.PUT);
        String encoding = service(buildURL(uri), isPush ? req.getInputStream() : null,
                res != null ? res.getOutputStream() : null, req, res, status);
        result = new Response(status);
        result.setEncoding(encoding);
    } catch (IOException ioErr) {
        if (logger.isInfoEnabled())
            logger.info("Error status " + status.getCode() + " " + status.getMessage(), ioErr);

        // error information already applied to Status object during service() call
        result = new Response(status);
    } catch (Throwable e) {
        if (logger.isErrorEnabled())
            logger.error("Error status " + status.getCode() + " " + status.getMessage(), e);

        // error information already applied to Status object during service() call
        result = new Response(status);
    }

    return result;
}

From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java

public void executePutBucketVersioning(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String bucketName = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
    String versioningStatus = null;
    Node item = null;/*from ww w  .ja  va  2s  .  com*/

    if (null == bucketName) {
        logger.error("executePutBucketVersioning - no bucket name given");
        response.setStatus(400);
        return;
    }

    // -> is the XML as defined?
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document restXML = db.parse(request.getInputStream());
        NodeList match = S3RestServlet.getElement(restXML, "http://s3.amazonaws.com/doc/2006-03-01/", "Status");
        if (0 < match.getLength()) {
            item = match.item(0);
            versioningStatus = new String(item.getFirstChild().getNodeValue());
        } else {
            logger.error("executePutBucketVersioning - cannot find Status tag in XML body");
            response.setStatus(400);
            return;
        }
    } catch (Exception e) {
        logger.error("executePutBucketVersioning - failed to parse XML due to " + e.getMessage(), e);
        response.setStatus(400);
        return;
    }

    try {
        // Irrespective of what the ACLs say only the owner can turn on
        // versioning on a bucket.
        // The bucket owner may want to restrict the IP address from which
        // this can occur.

        SBucketVO sbucket = bucketDao.getByName(bucketName);

        String client = UserContext.current().getCanonicalUserId();
        if (!client.equals(sbucket.getOwnerCanonicalId()))
            throw new PermissionDeniedException(
                    "Access Denied - only the owner can turn on versioing on a bucket");

        S3PolicyContext context = new S3PolicyContext(PolicyActions.PutBucketVersioning, bucketName);
        if (PolicyAccess.DENY == S3Engine.verifyPolicy(context)) {
            response.setStatus(403);
            return;
        }

        if (versioningStatus.equalsIgnoreCase("Enabled"))
            sbucket.setVersioningStatus(1);
        else if (versioningStatus.equalsIgnoreCase("Suspended"))
            sbucket.setVersioningStatus(2);
        else {
            logger.error("executePutBucketVersioning - unknown state: [" + versioningStatus + "]");
            response.setStatus(400);
            return;
        }
        bucketDao.update(sbucket.getId(), sbucket);

    } catch (PermissionDeniedException e) {
        logger.error("executePutBucketVersioning - failed due to " + e.getMessage(), e);
        throw e;

    } catch (Exception e) {
        logger.error("executePutBucketVersioning - failed due to " + e.getMessage(), e);
        response.setStatus(500);
        return;
    }
    response.setStatus(200);
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

private File getRequestBodyAsFile(HttpServletRequest req) throws IOException {
    if (this.m_requestBody == null) {
        this.m_requestBody = TempFileProvider.createTempFile("webdav_" + req.getMethod() + "_", ".bin");
        OutputStream out = new FileOutputStream(this.m_requestBody);
        int bytesRead = FileCopyUtils.copy(req.getInputStream(), out);

        // ALF-7377: check for corrupt request
        int contentLength = req.getIntHeader(WebDAV.HEADER_CONTENT_LENGTH);
        if (contentLength >= 0 && contentLength != bytesRead) {
            throw new IOException("Request body does not have specified Content Length");
        }//from   w ww .  j a v  a 2  s .c  o m
    }
    return this.m_requestBody;
}

From source file:net.ontopia.topicmaps.nav2.servlets.DataIntegrationServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/plain; charset=utf-8");

    // get topic map id
    String topicMapId = topicMapId = getInitParameter("topicMapId");
    if (topicMapId == null)
        throw new ServletException("Topic map identifier is not specified.");

    // parse path
    String path = request.getPathInfo();
    if (path == null)
        throw new ServletException("Path is missing.");
    path = path.substring(1);//from  w  ww .j  av  a  2  s.co  m

    String[] args = StringUtils.split(path, "/");
    String name = args[0];
    String action = args[1];

    // get topics query
    String topicsQuery = getInitParameter("topicsQuery");
    if (topicsQuery == null)
        throw new ServletException("Parameter 'topicsQuery' is not specified.");

    // get characteristcs query
    String characteristicsQuery = getInitParameter("characteristicsQuery");
    if (characteristicsQuery == null)
        throw new ServletException("Parameter 'characteristicsQuery' is not specified.");

    TopicMapStoreIF targetStore = TopicMaps.createStore(topicMapId, false);
    try {
        final TopicMapIF target = targetStore.getTopicMap();

        // transform input document to topic map
        final TopicMapIF source = transformRequest(name, request.getInputStream(),
                targetStore.getBaseAddress());

        // find topics to synchronize
        QueryProcessorIF qp = QueryUtils.getQueryProcessor(source);

        List candidates = new ArrayList();
        QueryResultIF qr = qp.execute(topicsQuery);
        try {
            while (qr.next()) {
                // synchronize topic
                candidates.add(qr.getValue(0));
            }
        } finally {
            qr.close();
        }

        if ("updated".equals(action) || "created".equals(action)) {

            DeciderIF tfilter = new DeciderIF() {
                @Override
                public boolean ok(Object o) {
                    return true;
                }
            };

            Iterator iter = candidates.iterator();
            while (iter.hasNext()) {
                TopicIF src = (TopicIF) iter.next();

                DeciderIF sfilter;
                if (characteristicsQuery == null) {
                    // let everything through
                    sfilter = tfilter;

                } else {
                    // let the characteristics query decide what gets synchronized
                    Collection characteristics = new HashSet();
                    QueryResultIF cqr = qp.execute(characteristicsQuery,
                            Collections.singletonMap("topic", src));
                    try {
                        while (cqr.next()) {
                            // synchronize topic
                            characteristics.add(cqr.getValue(0));
                        }
                    } finally {
                        cqr.close();
                    }
                    sfilter = new ContainmentDecider(characteristics);
                }
                // synchronize topic
                TopicMapSynchronizer.update(target, src, tfilter, sfilter);
            }
        } else if ("deleted".equals(action)) {

            Iterator iter = candidates.iterator();
            while (iter.hasNext()) {
                TopicIF src = (TopicIF) iter.next();
                Collection affectedTopics = IdentityUtils.findSameTopic(target, src);
                Iterator aiter = affectedTopics.iterator();
                while (aiter.hasNext()) {
                    TopicIF affectedTopic = (TopicIF) aiter.next();
                    affectedTopic.remove();
                }
            }
        } else {
            throw new ServletException("Unsupported action: " + action);
        }

        targetStore.commit();
    } catch (Exception e) {
        targetStore.abort();
        throw new ServletException(e);
    } finally {
        targetStore.close();
    }
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile,
        String version, boolean hasLocationHeader) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override/*from   w w  w.j  av  a2s  . com*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    });
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort,
                "fuse", "fuse", null);
        MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn(path);
        EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {
            private int i;

            @Override
            public int read() throws IOException {
                if (i >= contents.length) {
                    return -1;
                }
                return (contents[i++] & 0xFF);
            }
        });
        EasyMock.expect(request.getHeader("X-Location")).andReturn(location);
        EasyMock.expect(request.getParameter("profile")).andReturn(profile);
        EasyMock.expect(request.getParameter("version")).andReturn(version);

        final Map<String, String> headers = new HashMap<>();

        HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
        HttpServletResponse response = new HttpServletResponseWrapper(rm) {
            @Override
            public void addHeader(String name, String value) {
                headers.put(name, value);
            }
        };
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        EasyMock.replay(request, rm);

        servlet.start();
        servlet.doPut(request, response);

        EasyMock.verify(request, rm);

        Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));

        return headers;
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:com.photon.phresco.framework.rest.api.ActionService.java

/**
 * Seo CSV file upload test.//from  w  w w. ja  v  a 2s .com
 *
 * @param request the request
 * @return the response
 * @throws PhrescoException the phresco exception
 */
@POST
@Path(REST_CSV_FILE_UPLOAD)
@Produces(MediaType.APPLICATION_JSON)
public Response csvFileupload(@Context HttpServletRequest request) throws PhrescoException {
    ActionResponse response = new ActionResponse();
    String appDirName = "";
    try {
        String uploadedFileName = request.getHeader(FrameworkConstants.X_FILE_NAME);
        String fileName = URLDecoder.decode(uploadedFileName, CI_UTF8);

        InputStream inputStream = request.getInputStream();
        appDirName = request.getParameter(REQ_APP_DIR_NAME);
        String moduleName = request.getParameter(MODULE_NAME);
        String rootModulePath = "";
        String subModuleName = "";
        if (StringUtils.isNotEmpty(moduleName)) {
            rootModulePath = Utility.getProjectHome() + appDirName;
            subModuleName = moduleName;
        } else {
            rootModulePath = Utility.getProjectHome() + appDirName;
        }
        String seoTestPath = getSeoTestReportDir(rootModulePath, subModuleName);
        ProjectInfo projectinfo = Utility.getProjectInfo(rootModulePath, subModuleName);
        File testDir = Utility.getTestFolderLocation(projectinfo, rootModulePath, subModuleName);
        StringBuilder builder = new StringBuilder(testDir.toString());
        builder.append(seoTestPath);
        builder.append(RESOURCE_FOLDER);
        System.out.println("Target = " + builder.toString());
        File destFile = new File(builder.toString() + File.separator + fileName);
        FileUtils.copyInputStreamToFile(inputStream, destFile);
        response.setStatus(SUCCESS);
        response.setResponseCode(PHRQ400001);
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return Response.status(Status.OK).entity(response).header("Access-Control-Allow-Origin", "*").build();
}

From source file:fedora.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request/*from   www .j  a v a2  s  . co m*/
 */
public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception {
    RequestContent rContent = null;

    // See if the request is a multi-part file upload request
    if (ServletFileUpload.isMultipartContent(request)) {

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, use the first available File item
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                rContent = new RequestContent();
                rContent.contentStream = item.openStream();
                rContent.mimeType = item.getContentType();

                FileItemHeaders itemHeaders = item.getHeaders();
                if (itemHeaders != null) {
                    String contentLength = itemHeaders.getHeader("Content-Length");
                    if (contentLength != null) {
                        rContent.size = Integer.parseInt(contentLength);
                    }
                }

                break;
            }
        }
    } else {
        // If the content stream was not been found as a multipart,
        // try to use the stream from the request directly
        if (rContent == null) {
            if (request.getContentLength() > 0) {
                rContent = new RequestContent();
                rContent.contentStream = request.getInputStream();
                rContent.size = request.getContentLength();
            } else {
                String transferEncoding = request.getHeader("Transfer-Encoding");
                if (transferEncoding != null && transferEncoding.contains("chunked")) {
                    BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
                    bis.mark(2);
                    if (bis.read() > 0) {
                        bis.reset();
                        rContent = new RequestContent();
                        rContent.contentStream = bis;
                    }
                }
            }
        }
    }

    // Attempt to set the mime type and size if not already set
    if (rContent != null) {
        if (rContent.mimeType == null) {
            MediaType mediaType = headers.getMediaType();
            if (mediaType != null) {
                rContent.mimeType = mediaType.toString();
            }
        }

        if (rContent.size == 0) {
            List<String> lengthHeaders = headers.getRequestHeader("Content-Length");
            if (lengthHeaders != null && lengthHeaders.size() > 0) {
                rContent.size = Integer.parseInt(lengthHeaders.get(0));
            }
        }
    }

    return rContent;
}

From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    // Determine final URL
    StringBuffer uri = new StringBuffer();

    if (req.getParameter("update") != null) {
        uri.append(targetUri).append("/").append(req.getParameter("update"));
    } else {/*from w ww. ja v  a 2s.  c o  m*/
        uri.append(targetUri);
    }
    LOG.info("Access URI : " + uri.toString());
    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };
        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);
        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<?> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //LOG.info("header: " + headerName + " value: " + headerValue);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-type")) {
            request.addHeader(headerName, headerValue + ";charset=\"utf-8\"");
        } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) {
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);
    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        if (!header.getName().equals("Transfer-Encoding"))
            resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    byte buffer[] = new byte[50];
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }
    //        int b = input.read();
    //        while (b != -1) {
    //            output.write(b);
    //            b = input.read();
    //        }
    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

private HttpRequestBase prepareMethodWithUpdatedContent(HttpRequestBase method, HttpServletRequest request)
        throws ServletException {
    // PHIL, 2/28/2013
    // We should use the length when available, for HTTP 1.1
    // -> it optimizes with HTTP 1.1
    // -> it prevents the HTTP client to use Transfert-Encoding: chunked, which doesn't
    //    seem to work will all HTTP servers (ex: Domino)
    // A browser should anyway provide the length.
    long length = -1;
    String slength = request.getHeader("Content-Length");
    if (StringUtil.isNotEmpty(slength)) {
        length = Long.parseLong(slength);
    }/*w w  w.j a  v  a 2s . com*/
    try {
        // When no length is specified, the HTTP client core forces Transfert-Encoding: chunked
        // The code bellow shows a workaround, although we should avoid that
        if (false) {
            if (length < 0) {
                ByteStreamCache bs = new ByteStreamCache();
                bs.copyFrom(request.getInputStream());
                HttpEntity payloadEntity = new InputStreamEntity(bs.getInputStream(), bs.getLength());
                ((HttpEntityEnclosingRequest) method).setEntity(payloadEntity);
                return method;
            }
        }
        // Regular code
        HttpEntity payloadEntity = new InputStreamEntity(request.getInputStream(), length);
        ((HttpEntityEnclosingRequest) method).setEntity(payloadEntity);
    } catch (Exception e) {
        throw new ServletException("Error while parsing the payload");
    }
    return method;
}