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.bennavetta.appsite.serve.ResourceServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.info("Handling request {}", req);
    URI actual = base.relativize(URI.create(req.getRequestURI()));
    try {//from   w  ww .j  ava2 s.  com
        processor.handle(new RedirectedRequest(actual, new HttpServletReq(req)), new HttpServletResp(resp),
                req.getInputStream(), resp.getOutputStream());
    } catch (Exception e) {
        log.error("Error handling request", e);
        resp.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
    }
}

From source file:com.ebay.pulsar.metric.servlet.MetricRestServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletInputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        inputStream.mark(Integer.MAX_VALUE);
    }/*ww  w.  j  av  a2  s  .  c o  m*/
    try {
        String pathInfo = request.getPathInfo();
        if (pathInfo.startsWith(PATH_PING)) {
            ping(request, pathInfo, response);
        } else if (pathInfo.startsWith(PATH_COUNTER)) {
            stats.incQueryRequestCount();
            getCounters(request, pathInfo, response);
        } else if (pathInfo.startsWith(PATH_METRICGROUP)) {
            stats.incQueryRequestCount();
            getMetrics(request, pathInfo, response);
        } else {
            stats.incInvalidRequestCount();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (Throwable ex) {
        String requestTxt = readRequest(request);
        stats.setLastFailedRequest(readRequestHead(request) + requestTxt);
        stats.registerError(ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    }
}

From source file:Controllers.OCSPController.java

/**
 * Method to deal with a ocsp query request. The OCSP request method can be GET or POST.
 *
 * @return a valid OCSP response./*from   ww  w  .  j  a v  a 2  s .com*/
 */
@RequestMapping(value = "/verify-mocked-auto", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/ocsp-response")
@ResponseBody
public byte[] doOCSPAuto(HttpServletRequest httpServletRequest) throws IOException {
    InputStream inputStream = httpServletRequest.getInputStream();
    byte[] requestBytes = new byte[10000];
    int requestSize = inputStream.read(requestBytes);
    LOG.info("Received OCSP request, size: " + requestSize);
    byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.AUTO);
    return responseBytes;
}

From source file:Controllers.OCSPController.java

/**
 * Mocked method to deal with a ocsp query request. The OCSP request method can be GET or POST.
 *
 * @return a valid OCSP response to tell the client OCSP is <b>Good</b>!
 *///from   ww  w.j a  v  a 2 s .com
@RequestMapping(value = "/verify-mocked-good", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/ocsp-response")
@ResponseBody
public byte[] doOCSPGood(HttpServletRequest httpServletRequest) throws IOException {
    InputStream inputStream = httpServletRequest.getInputStream();
    byte[] requestBytes = new byte[10000];
    int requestSize = inputStream.read(requestBytes);
    LOG.info("Received OCSP request, size: " + requestSize);
    byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.GOOD);
    return responseBytes;
}

From source file:Controllers.OCSPController.java

/**
 * Mocked method to deal with a ocsp query request. The OCSP request method can be GET or POST.
 *
 * @return a valid OCSP response to tell the client OCSP is <b>Revoked</b>!
 *///from ww w .j av  a 2s.  c o m
@RequestMapping(value = "/verify-mocked-revoked", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/ocsp-response")
@ResponseBody
public byte[] doOCSPRevoked(HttpServletRequest httpServletRequest) throws IOException {
    InputStream inputStream = httpServletRequest.getInputStream();
    byte[] requestBytes = new byte[10000];
    int requestSize = inputStream.read(requestBytes);
    LOG.info("Received OCSP request, size: " + requestSize);
    byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.REVOKED);
    return responseBytes;
}

From source file:Controllers.OCSPController.java

/**
 * Mocked method to deal with a ocsp query request. The OCSP request method can be GET or POST.
 *
 * @return a valid OCSP response to tell the client OCSP is <b>Unknown</b>!
 */// ww  w.jav  a2  s.  c  om
@RequestMapping(value = "/verify-mocked-unknown", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/ocsp-response")
@ResponseBody
public byte[] doOCSPUnknown(HttpServletRequest httpServletRequest) throws IOException {
    InputStream inputStream = httpServletRequest.getInputStream();
    byte[] requestBytes = new byte[10000];
    int requestSize = inputStream.read(requestBytes);
    LOG.info("Received OCSP request, size: " + requestSize);
    byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.UNKNOWN);
    return responseBytes;
}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletInputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        inputStream.mark(Integer.MAX_VALUE);
    }/* ww  w .  j a  va2s.  co m*/
    try {
        String pathInfo = request.getPathInfo();
        if (pathInfo.startsWith(PATH_INGEST)) {
            stats.incIngestRequestCount();
            add(request, pathInfo, response);
        } else if (pathInfo.startsWith(PATH_BATCH_INGEST)) {
            stats.incBatchIngestRequestCount();
            batchAdd(request, pathInfo, response);
        } else {
            stats.incInvalidRequestCount();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (Throwable ex) {
        String requestTxt = readRequest(request);
        stats.setLastFailedRequest(readRequestHead(request) + requestTxt);
        stats.registerError(ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.servicemix.http.endpoints.SerializedMarshaler.java

public MessageExchange createExchange(HttpServletRequest request, ComponentContext context) throws Exception {
    MessageExchange me = context.getDeliveryChannel().createExchangeFactory().createExchange(getDefaultMep());
    NormalizedMessage in = me.createMessage();
    in.setContent(marshal(request.getInputStream()));
    me.setMessage(in, "in");
    return me;/* www  .  ja v  a2 s.  c  om*/
}

From source file:io.kamax.mxisd.controller.auth.v1.AuthController.java

@RequestMapping(value = logV1Url, method = RequestMethod.POST)
public String login(HttpServletRequest req) {
    try {//  w  w w.jav a 2s . c  o m
        JsonObject reqJsonObject = parser.parse(req.getInputStream());

        // find 3PID in main object
        GsonUtil.findPrimitive(reqJsonObject, "medium").ifPresent(medium -> {
            GsonUtil.findPrimitive(reqJsonObject, "address").ifPresent(address -> {
                log.info("Login request with medium '{}' and address '{}'", medium.getAsString(),
                        address.getAsString());
                strategy.findLocal(medium.getAsString(), address.getAsString()).ifPresent(lookupDataOpt -> {
                    reqJsonObject.addProperty("user", lookupDataOpt.getMxid().getLocalPart());
                    reqJsonObject.remove("medium");
                    reqJsonObject.remove("address");
                });
            });
        });

        // find 3PID in 'identifier' object
        GsonUtil.findObj(reqJsonObject, "identifier").ifPresent(identifier -> {
            GsonUtil.findPrimitive(identifier, "type").ifPresent(type -> {

                if (StringUtils.equals(type.getAsString(), "m.id.thirdparty")) {
                    GsonUtil.findPrimitive(identifier, "medium").ifPresent(medium -> {
                        GsonUtil.findPrimitive(identifier, "address").ifPresent(address -> {
                            log.info("Login request with medium '{}' and address '{}'", medium.getAsString(),
                                    address.getAsString());
                            strategy.findLocal(medium.getAsString(), address.getAsString())
                                    .ifPresent(lookupDataOpt -> {
                                        identifier.addProperty("type", "m.id.user");
                                        identifier.addProperty("user", lookupDataOpt.getMxid().getLocalPart());
                                        identifier.remove("medium");
                                        identifier.remove("address");
                                    });
                        });
                    });
                }

                if (StringUtils.equals(type.getAsString(), "m.id.phone")) {
                    GsonUtil.findPrimitive(identifier, "number").ifPresent(number -> {
                        GsonUtil.findPrimitive(identifier, "country").ifPresent(country -> {
                            log.info("Login request with phone '{}'-'{}'", country.getAsString(),
                                    number.getAsString());
                            try {
                                PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
                                Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(number.getAsString(),
                                        country.getAsString());
                                String canon_phoneNumber = phoneUtil
                                        .format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164)
                                        .replace("+", "");
                                String medium = "msisdn";
                                strategy.findLocal(medium, canon_phoneNumber).ifPresent(lookupDataOpt -> {
                                    identifier.addProperty("type", "m.id.user");
                                    identifier.addProperty("user", lookupDataOpt.getMxid().getLocalPart());
                                    identifier.remove("country");
                                    identifier.remove("number");
                                });
                            } catch (NumberParseException e) {
                                throw new RuntimeException(e);
                            }
                        });
                    });
                }
            });
        });

        // invoke 'login' on homeserver
        HttpPost httpPost = RestClientUtils.post(resolveProxyUrl(req), gson, reqJsonObject);
        try (CloseableHttpResponse httpResponse = client.execute(httpPost)) {
            // check http status
            int status = httpResponse.getStatusLine().getStatusCode();
            log.info("http status = {}", status);
            if (status != 200) {
                // try to get possible json error message from response
                // otherwise just get returned plain error message
                String errcode = String.valueOf(httpResponse.getStatusLine().getStatusCode());
                String error = EntityUtils.toString(httpResponse.getEntity());
                if (httpResponse.getEntity() != null) {
                    try {
                        JsonObject bodyJson = new JsonParser().parse(error).getAsJsonObject();
                        if (bodyJson.has("errcode")) {
                            errcode = bodyJson.get("errcode").getAsString();
                        }
                        if (bodyJson.has("error")) {
                            error = bodyJson.get("error").getAsString();
                        }
                        throw new RemoteLoginException(status, errcode, error, bodyJson);
                    } catch (JsonSyntaxException e) {
                        log.warn("Response body is not JSON");
                    }
                }
                throw new RemoteLoginException(status, errcode, error);
            }

            /// return response
            JsonObject respJsonObject = parser.parseOptional(httpResponse).get();
            return gson.toJson(respJsonObject);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.motechproject.mobile.web.OXDFormDownloadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww w. j a  v a2 s  .  c o m
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
@RequestMapping(method = RequestMethod.POST)
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Get our raw input and output streams
    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    // Wrap the streams for compression
    ZOutputStream zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);

    // Wrap the streams so we can use logical types
    DataInputStream dataInput = new DataInputStream(input);
    DataOutputStream dataOutput = new DataOutputStream(zOutput);

    try {

        // Read the common submission data from mobile phone
        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO: add authentication, possible M6 enhancement

        log.info("downloading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Perform the action specified by the mobile phone
        try {
            if (action == ACTION_DOWNLOAD_STUDY_LIST) {
                serObj.serializeStudies(baos, studyService.getStudies());
            } else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS) {

                serObj.serializeUsers(baos, userService.getUsers());

                int studyId = dataInput.readInt();
                String studyName = studyService.getStudyName(studyId);
                List<String> studyForms = formService.getStudyForms(studyId);

                serObj.serializeForms(baos, studyForms, studyId, studyName);

            }
        } catch (Exception e) {
            dataOutput.writeByte(RESPONSE_ERROR);
            throw new ServletException("failed to serialize data", e);
        }

        // Write out successful upload response
        dataOutput.writeByte(RESPONSE_SUCCESS);
        dataOutput.write(baos.toByteArray());
        response.setStatus(HttpServletResponse.SC_OK);

    } finally {
        // Should always do this
        dataOutput.flush();
        zOutput.finish();
        response.flushBuffer();
    }
}