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:cf.spring.servicebroker.ServiceBrokerHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!authenticator.authenticate(request, response)) {
        return;/*from   w w w .j  a  v  a  2s. c o m*/
    }
    ApiVersionValidator.validateApiVersion(request);
    try {
        response.setContentType(Constants.JSON_CONTENT_TYPE);
        final Matcher matcher = URI_PATTERN.matcher(request.getRequestURI());
        if (!matcher.matches()) {
            throw new NotFoundException("Resource not found");
        }
        final String instanceId = matcher.group(1);
        final String bindingId = matcher.group(3);
        if ("put".equalsIgnoreCase(request.getMethod())) {
            if (bindingId == null) {
                final ProvisionBody provisionBody = mapper.readValue(request.getInputStream(),
                        ProvisionBody.class);
                final String serviceId = provisionBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
                final ProvisionRequest provisionRequest = new ProvisionRequest(UUID.fromString(instanceId),
                        provisionBody.getPlanId(), provisionBody.getOrganizationGuid(),
                        provisionBody.getSpaceGuid());
                final ProvisionResponse provisionResponse = accessor.provision(provisionRequest);
                if (provisionResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), provisionResponse);
            } else {
                final BindBody bindBody = mapper.readValue(request.getInputStream(), BindBody.class);
                final String serviceId = bindBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);

                final BindRequest bindRequest = new BindRequest(UUID.fromString(instanceId),
                        UUID.fromString(bindingId), bindBody.applicationGuid, bindBody.getPlanId());
                final BindResponse bindResponse = accessor.bind(bindRequest);
                if (bindResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), bindResponse);
            }
        } else if ("delete".equalsIgnoreCase(request.getMethod())) {
            final String serviceId = request.getParameter(SERVICE_ID_PARAM);
            final String planId = request.getParameter(PLAN_ID_PARAM);
            final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
            try {
                if (bindingId == null) {
                    // Deprovision
                    final DeprovisionRequest deprovisionRequest = new DeprovisionRequest(
                            UUID.fromString(instanceId), planId);
                    accessor.deprovision(deprovisionRequest);
                } else {
                    // Unbind
                    final UnbindRequest unbindRequest = new UnbindRequest(UUID.fromString(bindingId),
                            UUID.fromString(instanceId), planId);
                    accessor.unbind(unbindRequest);
                }
            } catch (MissingResourceException e) {
                response.setStatus(HttpServletResponse.SC_GONE);
            }
            response.getWriter().write("{}");
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (ConflictException e) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        response.getWriter().write("{}");
    } catch (ServiceBrokerException e) {
        LOGGER.warn("An error occurred processing a service broker request", e);
        response.setStatus(e.getHttpResponseCode());
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    } catch (Throwable e) {
        LOGGER.error(e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    }
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom POST by calling handler to identify URI, reading/parsing
 * data, calling handler and writing results to response.
 *//*from w  ww. j  a va 2  s  . c  o  m*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isCollectionURI(areq)) {

                if (req.getContentType().startsWith("application/atom+xml")) {

                    // parse incoming entry
                    Entry entry = Atom10Parser.parseEntry(
                            new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null);

                    // call handler to post it
                    Entry newEntry = handler.postEntry(areq, entry);

                    // set Location and Content-Location headers                        
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    // write entry back out to response
                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else if (req.getContentType() != null) {

                    // get incoming title and slug from HTTP header
                    String title = areq.getHeader("Title");

                    // create new entry for resource, set title and type
                    Entry resource = new Entry();
                    resource.setTitle(title);
                    Content content = new Content();
                    content.setType(areq.getContentType());
                    resource.setContents(Collections.singletonList(content));

                    // hand input stream off to hander to post file
                    Entry newEntry = handler.postMedia(areq, resource);

                    // set Location and Content-Location headers
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else {
                    res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                            "No content-type specified in request");
                }

            } else {
                res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid collection specified in request");
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing POST", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing POST", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public void handleConnect(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uri = request.getRequestURI();

    String port = "";
    String host = "";

    int c = uri.indexOf(':');
    if (c >= 0) {
        port = uri.substring(c + 1);//w  w w .  j  a va2  s  .  co m
        host = uri.substring(0, c);
        if (host.indexOf('/') > 0)
            host = host.substring(host.indexOf('/') + 1);
    }

    InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port));

    // if
    // (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
    // {
    // sendForbid(request,response,uri);
    // }
    // else
    {
        InputStream in = request.getInputStream();
        final OutputStream out = response.getOutputStream();

        final Socket socket = new Socket(inetAddress.getAddress(), inetAddress.getPort());

        response.setStatus(200);
        response.setHeader("Connection", "close");
        response.flushBuffer();

        //         try {
        //            Thread copy = new Thread(new Runnable() {
        //               public void run() {
        //                  try {
        IOUtils.copy(socket.getInputStream(), out);
        //                  } catch (IOException e) {
        //                     e.printStackTrace();
        //                  }
        //               }
        //            });
        //            copy.start();
        IOUtils.copy(in, socket.getOutputStream());
        //            copy.join();
        //            copy.join(10000);
        //         }
        //         catch (InterruptedException e) {
        //            e.printStackTrace();
        //         }
    }
}

From source file:uk.ac.ebi.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    // note: we won't transfer the protocol version because I'm not sure it
    // would truly be compatible
    BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(
            servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest));

    copyRequestHeaders(servletRequest, proxyRequest);

    // Add the input entity (streamed) then execute the request.
    HttpResponse proxyResponse = null;//from w w  w. jav  a2 s. c o  m
    InputStream servletRequestInputStream = servletRequest.getInputStream();
    try {
        try {
            proxyRequest.setEntity(
                    new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength()));

            // Execute the request
            if (doLog) {
                log("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- "
                        + proxyRequest.getRequestLine().getUri());
            }
            proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);
        } finally {
            closeQuietly(servletRequestInputStream);
        }

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            EntityUtils.consume(proxyResponse.getEntity());
            return;
        }

        // Pass the response code. This method with the "reason phrase" is
        // deprecated but it's the only way to pass the
        // reason along too.
        // noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        // abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        throw new RuntimeException(e);
    }
}

From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java

private void doProcess(HttpServletRequest request, HttpServletResponse resp)
        throws ServletException, IOException {
    for (String[] h : additionalResponseHeaders) {
        resp.addHeader(h[0], h[1]);//from w  w  w.  ja va 2 s .co  m
    }
    resp.setCharacterEncoding("UTF-8");

    String serviceName = getServiceName(request);

    JsonRpcRequest req = null;
    if (request.getMethod().equals("GET")) {
        req = decodeFromPC(new URLParameterContext(request.getQueryString()));
    } else {
        req = JSON.decode(StreamUtil.readAsString(request.getInputStream(), "UTF-8"), JsonRpcRequest.class);
        String cb = request.getParameter("callback");
        if (cb != null) {
            req.setCallback(cb);
        }
        if (req.getHeaders() == null) {
            req.setHeaders(new RpcHeader[] {});
        }
    }
    // The handler is acquired from the service name.
    JsonRpcHandler h = handlers.get(serviceName);
    // Execution of service
    if (h == null) {
        h = new JsonRpcDynamicHandler();
    }
    ServiceContext sc = new ServletServiceContext(getServletConfig(), request, Arrays.asList(req.getHeaders()));
    ServiceLoader loader = new ServiceLoader(sc, defaultLoaders);
    OutputStream os = resp.getOutputStream();
    h.handle(sc, loader, serviceName, req, resp, os);
    os.flush();
}

From source file:com.imaginary.home.cloud.api.call.DeviceCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/* w  w  w .  j a  v  a2  s.co m*/
        String deviceId = (path.length > 1 ? path[1] : null);
        Device device = null;

        if (deviceId != null) {
            device = Device.getDevice(deviceId);
        }
        if (device == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "The device " + deviceId + " does not exist.");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equals("flipOn") || action.equals("flipOff")) {
            if (userId == null) {
                throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.RELAY_NOT_ALLOWED,
                        "Invalid relay actiojn: " + action);
            }
            HashMap<String, Object> json = new HashMap<String, Object>();
            TimePeriod p = null;

            if (object.has("timeout") && !object.isNull("timeout")) {
                try {
                    p = TimePeriod.valueOf(object.getString("timeout"));
                } catch (Throwable ignore) {
                    // ignore
                }
            }
            if (p == null) {
                p = new TimePeriod<Minute>(5, TimePeriod.MINUTE);
            }
            json.put("command", action);
            json.put("arguments", new HashMap<String, Object>());
            PendingCommand[] cmds = PendingCommand.queue(userId, p,
                    new String[] { (new JSONObject(json)).toString() }, device);

            ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            for (PendingCommand cmd : cmds) {
                list.add(CommandCall.toJSON(cmd));
            }
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            resp.getWriter().println((new JSONArray(list)).toString());
            resp.getWriter().flush();
        }
        /*
        else if( action.equalsIgnoreCase("modify") ) {
        if( object.has("device") ) {
            object = object.getJSONObject("device");
        }
        else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT, "No device was specified in the PUT");
        }
        String name, description;
        TimeZone timeZone;
                
        if( object.has("name") && !object.isNull("name") ) {
            name = object.getString("name");
        }
        else {
            name = location.getName();
        }
        if( object.has("description") && !object.isNull("description") ) {
            description = object.getString("description");
        }
        else {
            description = location.getName();
        }
        if( object.has("timeZone") && !object.isNull("timeZone") ) {
            String tz = object.getString("timeZone");
                
            timeZone = TimeZone.getTimeZone(tz);
        }
        else {
            timeZone = location.getTimeZone();
        }
        location.modify(name, description, timeZone);
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
        */
        else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in request");
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

From source file:biz.taoconsulting.dominodav.methods.LOCK.java

/**
 * Extracts the XML Document than contains the lock request
 * /*from www.  jav  a  2  s .  c  o m*/
 * @param req
 */
private String getOwnerFromXMLLockRequest(HttpServletRequest req) {
    // We don't treat XML as XML here, but we just need a string
    // Not terrible good code
    String result = null;
    /*
     * Looks like this <?xml version="1.0" encoding="UTF-8" ?> <lockinfo
     * xmlns="DAV:"> <locktype> <write/> </locktype> <lockscope>
     * <exclusive/> </lockscope> <owner>Administrator</owner> </lockinfo>
     */

    boolean found = false;
    String curLine = null;
    BufferedReader in = null;
    // byte[] data = new byte[req.getContentLength()];
    // int len = 0, totalLen = 0;

    try {
        // LOGGER.info("1.1");
        // in = req.getReader();
        InputStream ins = req.getInputStream();
        // InputStream in= new
        // FileInputStream("d:/forChml/PunchOutSetupRequest.xml");
        StringBuffer xmlStr = new StringBuffer();
        int d;
        while ((d = ins.read()) != -1) {
            xmlStr.append((char) d);
        }
        // LOGGER.info("1.2");
        // do {
        // curLine = in.readLine();
        curLine = xmlStr.toString();
        // LOGGER.info("1.3="+curLine);
        if (curLine != null && curLine.contains("<owner>")) {
            found = true;

        } else {
            // LOGGER.info("1.4");
            if (curLine != null && curLine.contains("<D:owner>")) {
                found = true;
            }
        }
        // } while (!found && curLine != null);

        if (found) {
            // curLine=curLine.substring(startIndex);
            int start = curLine.indexOf(">");
            int stop = curLine.lastIndexOf("<");
            result = curLine.substring(start + 1, stop);
            // LOGGER.info("1.5="+result);
            start = result.indexOf(">");
            stop = result.lastIndexOf("<");

            if (start > 0) {
                result = result.substring(start + 1, stop);
                start = result.indexOf("href>");
                stop = result.lastIndexOf("<");

                if (start > 0) {
                    if (stop > 0) {
                        result = result.substring(start + 5, stop);
                    } else {
                        result = result.substring(start + 5);
                    }
                }

                // LOGGER.info("1.6="+result);
            }
        }

    } catch (Exception e) {
        LOGGER.error(e);
        result = null;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            LOGGER.error(e);
        }
    }

    return result;

}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  {@inheritDoc}//  w w w .j  a va  2s  . c  o m
 */
public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad happened, Upload should be able to take care of most stuff

    String p = new String(req.getPathInfo().getBytes("ISO-8859-1"), "UTF-8");
    DavPath path = new DavPath(p);

    try {
        InputStream data = req.getInputStream();

        WikiContext context = m_engine.createContext(req, WikiContext.UPLOAD);

        String wikipage = path.get(0);

        errorPage = context.getURL(WikiContext.UPLOAD, wikipage);

        String changeNote = null; // FIXME: Does not quite work

        boolean created = executeUpload(context, data, path.getName(), errorPage, wikipage, changeNote,
                req.getContentLength());

        if (created)
            res.sendError(HttpServletResponse.SC_CREATED);
        else
            res.sendError(HttpServletResponse.SC_OK);
    } catch (ProviderException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (RedirectException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:com.sdl.odata.controller.AbstractODataController.java

/**
 * Converts an {@code HttpServletRequest} to an {@code ODataRequest}.
 *
 * @param servletRequest The {@code HttpServletRequest}.
 * @return An {@code ODataRequest} containing the request information.
 * @throws java.io.IOException If an I/O error occurs.
 *///from  w  ww .j  a  va 2 s.co  m
private ODataRequest buildODataRequest(HttpServletRequest servletRequest) throws IOException {
    ODataRequest.Builder builder = new ODataRequest.Builder();

    builder.setMethod(ODataRequest.Method.valueOf(servletRequest.getMethod()));

    // Unfortunately, HttpServletRequest makes it difficult to get the full URI
    StringBuilder sb = getRequestURL(servletRequest);
    String queryString = servletRequest.getQueryString();
    if (!isNullOrEmpty(queryString)) {
        sb.append('?').append(queryString);
    }
    builder.setUri(sb.toString());

    // Unfortunately, HttpServletRequest has a very old-style API to iterate the headers
    Enumeration e = servletRequest.getHeaderNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        String value = servletRequest.getHeader(name);
        builder.setHeader(name, value);
    }

    // Read the request body
    InputStream in = servletRequest.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int count;
    byte[] buffer = new byte[BUFFER_SIZE];
    while ((count = in.read(buffer)) != -1) {
        out.write(buffer, 0, count);
    }
    builder.setBody(out.toByteArray());

    return builder.build();
}