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.thinkberg.moxo.dav.PropPatchHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {/* ww  w.  ja va  2s .c  om*/
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        //      log(propDoc);

        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(SC_MULTI_STATUS);

        if (object.exists()) {
            Document resultDoc = DocumentHelper.createDocument();
            Element multiStatusResponse = resultDoc.addElement("multistatus", "DAV:");
            Element responseEl = multiStatusResponse.addElement("response");
            try {
                URL url = new URL(getBaseUrl(request), URLEncoder.encode(object.getName().getPath(), "UTF-8"));
                log("!! " + url);
                responseEl.addElement("href").addText(url.toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Element propstatEl = responseEl.addElement("propstat");
            Element propEl = propstatEl.addElement("prop");

            Element propertyUpdateEl = propDoc.getRootElement();
            for (Object elObject : propertyUpdateEl.elements()) {
                Element el = (Element) elObject;
                if ("set".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        setProperty(propEl, object, (Element) propObject);
                    }
                } else if ("remove".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        removeProperty(propEl, object, (Element) propObject);
                    }
                }
            }
            propstatEl.addElement("status").addText(DavResource.STATUS_403);

            //        log(resultDoc);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(resultDoc);
            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:edu.unc.lib.dl.admin.controller.AbstractSwordController.java

public String updateDatastream(String pid, String datastream, HttpServletRequest request,
        HttpServletResponse response) {//w  w w  .ja  v a  2  s  .com
    String responseString = null;
    String dataUrl = swordUrl + "object/" + pid;
    if (datastream != null)
        dataUrl += "/" + datastream;

    Abdera abdera = new Abdera();
    Entry entry = abdera.newEntry();
    Parser parser = abdera.getParser();
    Document<FOMExtensibleElement> doc;
    HttpClient client;
    PutMethod method;

    ParserOptions parserOptions = parser.getDefaultParserOptions();
    parserOptions.setCharset(request.getCharacterEncoding());

    try {

        doc = parser.parse(request.getInputStream(), parserOptions);
        entry.addExtension(doc.getRoot());

        client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
        client.getParams().setAuthenticationPreemptive(true);
        method = new PutMethod(dataUrl);
        // Pass the users groups along with the request
        method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());

        Header header = new Header("Content-Type", "application/atom+xml");
        method.setRequestHeader(header);
        StringWriter stringWriter = new StringWriter(2048);
        StringRequestEntity requestEntity;
        entry.writeTo(stringWriter);
        requestEntity = new StringRequestEntity(stringWriter.toString(), "application/atom+xml", "UTF-8");
        method.setRequestEntity(requestEntity);
    } catch (UnsupportedEncodingException e) {
        log.error("Encoding not supported", e);
        return null;
    } catch (IOException e) {
        log.error("IOException while writing entry", e);
        return null;
    }

    try {
        client.executeMethod(method);
        response.setStatus(method.getStatusCode());
        if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            // success
            return "";
        } else if (method.getStatusCode() >= 400 && method.getStatusCode() <= 500) {
            if (method.getStatusCode() == 500)
                log.warn("Failed to upload " + datastream + " " + method.getURI().getURI());
            // probably a validation problem
            responseString = method.getResponseBodyAsString();
            return responseString;
        } else {
            response.setStatus(500);
            throw new Exception("Failure to update fedora content due to response of: "
                    + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI());
        }
    } catch (Exception e) {
        log.error("Error while attempting to stream Fedora content for " + pid, e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return responseString;
}

From source file:com.almende.eve.transport.http.DebugServlet.java

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

    if (!handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }//ww  w.  j  ava  2s .c  o  m
        resp.flushBuffer();
        return;
    }

    // retrieve the url and the request body
    final String body = StringUtil.streamToString(req.getInputStream());
    final String url = req.getRequestURI();
    final String id = getId(url);
    if (id == null || id.equals("") || id.equals(myUrl.toASCIIString())) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Couldn't parse URL, missing 'id'");
        resp.flushBuffer();
        return;
    }

    String sender = req.getHeader("X-Eve-SenderUrl");
    if (sender == null || sender.equals("")) {
        sender = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr();
    }
    URI senderUrl = null;
    try {
        senderUrl = new URI(sender);
    } catch (final URISyntaxException e) {
        LOG.log(Level.WARNING, "Couldn't parse senderUrl:" + sender, e);
    }
    final HttpTransport transport = HttpService.get(myUrl, id);
    if (transport != null) {
        try {
            final String response = transport.receive(body, senderUrl);
            // TODO: It doesn't need to be json, should we handle mime-types
            // better?
            resp.addHeader("Content-Type", "application/json");
            resp.getWriter().println(response);
            resp.getWriter().close();
        } catch (final IOException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Receiver raised exception:" + e.getMessage());
        }
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Couldn't load transport");
    }
    resp.flushBuffer();
}

From source file:com.aipo.container.protocol.AipoDataServiceServlet.java

private String getBodyAsString(HttpServletRequest request) {
    if (request.getContentLength() == 0) {
        return "";
    }/* w  w w . j a va2  s .co  m*/
    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) {
        // ignore
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.streamsets.pipeline.lib.http.HttpReceiverServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
    if (isShuttingDown()) {
        LOG.debug("Shutting down, discarding incoming request from '{}'", requestor);
        resp.setStatus(HttpServletResponse.SC_GONE);
    } else {/*  w w  w  .j  a  v  a 2s  .  c  o m*/
        if (validatePostRequest(req, resp)) {
            long start = System.currentTimeMillis();
            LOG.debug("Request accepted from '{}'", requestor);
            try (InputStream in = req.getInputStream()) {
                InputStream is = in;
                String compression = req.getHeader(HttpConstants.X_SDC_COMPRESSION_HEADER);
                if (compression == null) {
                    compression = req.getHeader(HttpConstants.CONTENT_ENCODING_HEADER);
                }
                if (compression != null) {
                    switch (compression) {
                    case HttpConstants.SNAPPY_COMPRESSION:
                        is = new SnappyFramedInputStream(is, true);
                        break;
                    case HttpConstants.GZIP_COMPRESSION:
                        is = new GZIPInputStream(is);
                        break;
                    default:
                        throw new IOException(
                                Utils.format("It shouldn't happen, unexpected compression '{}'", compression));
                    }
                }
                LOG.debug("Processing request from '{}'", requestor);
                processRequest(req, is, resp);
            } catch (Exception ex) {
                errorQueue.offer(ex);
                errorRequestMeter.mark();
                LOG.warn("Error while processing request payload from '{}': {}", requestor, ex.toString(), ex);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
            } finally {
                requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
            }

        } else {
            invalidRequestMeter.mark();
        }
    }
}

From source file:au.org.ala.layers.web.IntersectService.java

@RequestMapping(value = WS_INTERSECT_BATCH, method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody/*w ww.  ja  v  a2  s.com*/
public Map batch(@RequestParam(value = "fids", required = false, defaultValue = "") String fids,
        @RequestParam(value = "points", required = false, defaultValue = "") String pointsString,
        @RequestParam(value = "gridcache", required = false, defaultValue = "0") String gridcache,
        HttpServletRequest request, HttpServletResponse response) {

    BatchConsumer.start(layerIntersectDao, userProperties.getProperty("batch_path"));

    //help get params when they don't pick up automatically from a POST
    try {
        if ("POST".equalsIgnoreCase(request.getMethod()) && fids.isEmpty() && pointsString.isEmpty()) {
            Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
            String body = s.hasNext() ? s.next() : "";

            for (String param : body.split("&")) {
                if (param.startsWith("fids=")) {
                    fids = param.substring(5);
                } else if (param.startsWith("points=")) {
                    pointsString = param.substring(7);
                }
            }
        }
    } catch (Exception e) {
        logger.error("failed to read POST body for: " + WS_INTERSECT_BATCH, e);
    }

    if (pointsString == null || pointsString.isEmpty()) {
        return null;
    }

    Map map = new HashMap();
    String batchId = null;
    try {

        // get limits
        int pointsLimit, fieldsLimit;

        String[] passwords = userProperties.getProperty("batch_sampling_passwords").split(",");
        pointsLimit = Integer.parseInt(userProperties.getProperty("batch_sampling_points_limit"));
        fieldsLimit = Integer.parseInt(userProperties.getProperty("batch_sampling_fields_limit"));

        String password = request.getParameter("pw");
        for (int i = 0; password != null && i < passwords.length; i++) {
            if (passwords[i].equals(password)) {
                pointsLimit = Integer.MAX_VALUE;
                fieldsLimit = Integer.MAX_VALUE;
            }
        }

        // count fields
        int countFields = 1;
        int p = 0;
        while ((p = fids.indexOf(',', p + 1)) > 0)
            countFields++;

        // count points
        int countPoints = 1;
        p = 0;
        while ((p = pointsString.indexOf(',', p + 1)) > 0)
            countPoints++;

        if (countPoints / 2 > pointsLimit) {
            map.put("error", "Too many points.  Maximum is " + pointsLimit);
        } else if (countFields > fieldsLimit) {
            map.put("error", "Too many fields.  Maximum is " + fieldsLimit);
        } else {
            batchId = BatchProducer.produceBatch(userProperties.getProperty("batch_path"),
                    "request address:" + request.getRemoteAddr(), fids, pointsString, gridcache);

            map.put("batchId", batchId);
            BatchProducer.addInfoToMap(userProperties.getProperty("batch_path"), batchId, map);
            map.put("statusUrl", userProperties.getProperty("layers_service_url")
                    + WS_INTERSECT_BATCH_STATUS.replace("{id}", batchId));
        }

        return map;
    } catch (Exception e) {
        e.printStackTrace();
    }

    map.put("error", "failed to create new batch");
    return map;
}

From source file:com.voa.weixin.filter.AuthorFilter.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String signature = request.getParameter("signature");// ??
    String timestamp = request.getParameter("timestamp");// 
    String nonce = request.getParameter("nonce");// ?
    String echostr = request.getParameter("echostr");// ?
    try {/*  ww  w  . ja  v  a2  s  . co  m*/
        logger.debug("signatrue : " + signature);
        logger.debug("timestamp : " + timestamp);

        boolean checked = WeixinUtils.checkAuthentication(signature, timestamp, nonce, echostr, token);
        if (checked) {
            String requestStr = IOUtils.toString(request.getInputStream(), "UTF-8");
            logger.debug("requestStr : " + requestStr);
            SessionManager.getInstance().buildSession(requestStr, response);

        } else {
            logger.warn("host:" + request.getRemoteHost() + " request content cant't checked.");

        }
    } catch (Exception e) {
        e.printStackTrace();
        e.printStackTrace(LogUtil.getErrorStream(logger));
    }

}

From source file:bijian.util.upload.MyMultiPartRequest.java

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

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

        public int getContentLength() {
            return req.getContentLength();
        }

        public InputStream getInputStream() throws IOException {
            InputStream in = req.getInputStream();
            if (in == null) {
                throw new IOException("Missing content in the request");
            }
            return req.getInputStream();
        }
    };
}

From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java

private HttpRequestBase getNewHttpRequest(final HttpServletRequest req, final String url) throws IOException {
    HttpRequestBase newReq = null;/*from  w  w w .  j a  v  a2  s .  com*/
    if (req == null || req.getMethod().equalsIgnoreCase("get")) {
        newReq = new HttpGet(url);
    } else {
        final HttpPost post = new HttpPost(url);
        final ByteArrayOutputStream reqBody = new ByteArrayOutputStream();
        copyHeaders(post, req);
        IOUtils.copy(req.getInputStream(), reqBody);
        post.setEntity(new ByteArrayEntity(reqBody.toByteArray()));
        newReq = post;
    }

    return newReq;
}

From source file:com.bstek.dorado.idesupport.resolver.RobotResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    DoradoContext context = DoradoContext.getCurrent();
    Document document = null;/*  w ww .j  ava 2  s  .co m*/
    List<Element> resultElements = null;
    Exception error = null;

    String robotName = getRobotName(request);
    Assert.notEmpty(robotName, "\"robotName\" undefined.");

    Robot robot = robotRegistry.getRobot(robotName);
    if (robot == null) {
        throw new IllegalArgumentException("Unknown robotName \"" + robotName + "\".");
    }

    ServletInputStream in = request.getInputStream();
    try {
        String charset = request.getCharacterEncoding();
        document = getXmlDocumentBuilder(context)
                .loadDocument(new InputStreamResource(in, request.getRequestURI()), charset);
    } catch (Exception e) {
        logger.error(e, e);
        error = e;
    } finally {
        in.close();
    }

    Element documentElement = document.getDocumentElement();

    Element contentElement = DomUtils.getChildByTagName(documentElement, "Content");
    List<Element> elements = DomUtils.getChildElements(contentElement);

    Properties properties = null;
    Element propertiesElement = DomUtils.getChildByTagName(documentElement, "Properties");
    if (propertiesElement != null) {
        List<Element> propertieElements = DomUtils.getChildElements(propertiesElement);
        if (!propertieElements.isEmpty()) {
            properties = new Properties();
            for (Element propertyElement : propertieElements) {
                properties.setProperty(propertyElement.getAttribute("name"),
                        DomUtils.getTextContent(propertyElement));
            }
        }
    }

    resultElements = new ArrayList<Element>();
    for (Element element : elements) {
        resultElements.add((Element) robot.execute(element, properties));
    }

    // Output
    document = getXmlDocumentBuilder(context).newDocument();
    Element responseElement = document.createElement("Response");
    document.appendChild(responseElement);
    if (error == null) {
        assembleContent(document, responseElement, resultElements);
    } else {
        responseElement.setAttribute("failed", "true");
        assembleError(document, responseElement, error);
    }

    PrintWriter writer = null;
    TransformerFactory transFactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("encoding", Constants.DEFAULT_CHARSET);
        transformer.setOutputProperty("indent", "yes");

        DOMSource source = new DOMSource(document);
        writer = getWriter(request, response);
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}