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.amazon.speech.speechlet.servlet.SpeechletServlet.java

/**
 * Handles a POST request. Based on the request parameters, invokes the right method on the
 * {@code SpeechletV2}.//from   w w  w  .  ja  v  a  2  s.com
 *
 * @param request
 *            the object that contains the request the client has made of the servlet
 * @param response
 *            object that contains the response the servlet sends to the client
 * @throws IOException
 *             if an input or output error is detected when the servlet handles the request
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    byte[] serializedSpeechletRequest = IOUtils.toByteArray(request.getInputStream());
    byte[] outputBytes = null;

    try {
        if (disableRequestSignatureCheck) {
            log.warn("Warning: Speechlet request signature verification has been disabled!");
        } else {
            // Verify the authenticity of the request by checking the provided signature &
            // certificate.
            SpeechletRequestSignatureVerifier.checkRequestSignature(serializedSpeechletRequest,
                    request.getHeader(Sdk.SIGNATURE_REQUEST_HEADER),
                    request.getHeader(Sdk.SIGNATURE_CERTIFICATE_CHAIN_URL_REQUEST_HEADER));
        }

        outputBytes = speechletRequestHandler.handleSpeechletCall(speechlet, serializedSpeechletRequest);
    } catch (SpeechletRequestHandlerException | SecurityException ex) {
        int statusCode = HttpServletResponse.SC_BAD_REQUEST;
        log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
        response.sendError(statusCode, ex.getMessage());
        return;
    } catch (Exception ex) {
        int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
        response.sendError(statusCode, ex.getMessage());
        return;
    }

    // Generate JSON and send back the response
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
    try (final OutputStream out = response.getOutputStream()) {
        response.setContentLength(outputBytes.length);
        out.write(outputBytes);
    }
}

From source file:com.dalendev.meteotndata.servlet.UpdateStationDataServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w  .  ja v  a2 s. co 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream inputStream = request.getInputStream();
    ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();

    int length;
    byte[] buffer = new byte[1024];
    while ((length = inputStream.read(buffer)) >= 0) {
        byteArrayStream.write(buffer, 0, length);
    }

    if (byteArrayStream.size() > 0) {
        Station station = SerializationUtils.deserialize(byteArrayStream.toByteArray());
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO, station.getCode());

        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(MeasurementList.class);
            Unmarshaller u = jc.createUnmarshaller();
            URL url = new URL(
                    "http://dati.meteotrentino.it/service.asmx/ultimiDatiStazione?codice=" + station.getCode());
            StreamSource src = new StreamSource(url.openStream());
            JAXBElement je = u.unmarshal(src, MeasurementList.class);
            MeasurementList measurementList = (MeasurementList) je.getValue();

            MeasurmentSamplerService mss = new MeasurmentSamplerService();
            mss.mergeMeasurment(station, measurementList);
            List<Measurement> sampledList = mss.getSampledMeasurementList();
            MeasurementDAO.storeStation(sampledList);

            if (sampledList.size() > 0) {
                Measurement lastMeasurement = sampledList.get(sampledList.size() - 1);
                station.setLastUpdate(lastMeasurement.getTimestamp());
                StationDAO.storeStation(station);
            }

            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                    "Station {0} has {1} new measurements",
                    new Object[] { station.getCode(), sampledList.size() });
        } catch (JAXBException ex) {
            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        response.setStatus(200);
    } else {
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                "Cannot retrieve Station's serialization");
    }
}

From source file:io.dfox.junit.http.example.NoteServlet.java

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

    addBasicHeaders(response);/*  w  ww.ja v a2  s  . c  o  m*/

    String name = getNoteName(request);

    try (InputStream stream = request.getInputStream()) {
        repository.saveNote(name, stream);
    }
}

From source file:br.org.indt.ndg.servlets.PostResultsOpenRosa.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress());

    InputStreamReader inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
    boolean success = m_openRosaBD.parseAndPersistResult(inputStreamReader, request.getContentType());

    DataOutputStream dataOutputStream = new DataOutputStream(response.getOutputStream());
    if (success) {
        dataOutputStream.writeInt(SUCCESS);
        log.info("Successfully processed result stream from " + request.getRemoteAddr());
    } else {//from  w w  w .  ja va 2s  .c o  m
        dataOutputStream.writeInt(FAILURE);
        log.error("Failed processing result stream from " + request.getRemoteAddr());
    }
    dataOutputStream.close();
}

From source file:org.commonjava.aprox.core.bind.jaxrs.admin.ReplicationHandler.java

@POST
@Produces(ApplicationContent.application_json)
public Response replicate(@Context final HttpServletRequest request) {
    Response response;//w ww.j a v a2s.c  o m
    try {
        final String user = (String) request.getSession(true).getAttribute(SecurityParam.user.key());

        final ReplicationDTO dto = serializer.readValue(request.getInputStream(), ReplicationDTO.class);
        final Set<StoreKey> replicated = controller.replicate(dto, user);

        final Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("replicationCount", replicated.size());
        params.put("items", replicated);

        response = formatOkResponseWithJsonEntity(params, serializer);
    } catch (final AproxWorkflowException | IOException e) {
        logger.error(String.format("Replication failed: %s", e.getMessage()), e);
        response = formatResponse(e, true);
    }

    return response;
}

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

@RequestMapping(value = "/_matrix-internal/identity/v1/check_credentials", method = RequestMethod.POST)
public String checkCredentials(HttpServletRequest req) {
    try {/*from   w  w  w  .  j a v  a2  s  .  c  om*/
        JsonObject authData = parser.parse(req.getInputStream(), "user");
        if (!authData.has("id") || !authData.has("password")) {
            throw new JsonMemberNotFoundException("Missing id or password keys");
        }

        String id = authData.get("id").getAsString();
        log.info("Requested to check credentials for {}", id);
        String password = authData.get("password").getAsString();

        UserAuthResult result = mgr.authenticate(id, password);
        CredentialsValidationResponse response = new CredentialsValidationResponse(result.isSuccess());

        if (result.isSuccess()) {
            response.setDisplayName(result.getDisplayName());
            response.getProfile().setThreePids(result.getThreePids());
        }
        JsonElement authObj = gson.toJsonTree(response);

        JsonObject obj = new JsonObject();
        obj.add("auth", authObj);
        obj.add("authentication", authObj); // TODO remove later, legacy support
        return gson.toJson(obj);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ste.web.beanshell.jetty.BeanShellUtils.java

public static void setup(final Interpreter interpreter, final HttpServletRequest request,
        final HttpServletResponse response) throws EvalError, IOException {
    ///*from  www  .ja va2s .  c  om*/
    // Set attributes as script variables
    //
    String k, key;
    for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
        k = (String) e.nextElement();
        key = normalizeVariableName(k);
        interpreter.set(key, request.getAttribute(k));
    }

    //
    // Set request parameters as script variables. Note that parameters
    // override attributes
    //
    for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
        k = (String) e.nextElement();
        key = normalizeVariableName(k);
        interpreter.set(key, request.getParameter(k));
    }

    interpreter.set(VAR_REQUEST, request);
    interpreter.set(VAR_RESPONSE, response);
    interpreter.set(VAR_SESSION, request.getSession(false));
    interpreter.set(VAR_OUT, response.getWriter());
    interpreter.set(VAR_LOG, log);
    if (hasJSONBody(request)) {
        interpreter.set(VAR_BODY, getJSONBody(request.getInputStream()));
    }
}

From source file:foam.nanos.blob.HttpBlobService.java

protected void upload(X x) {
    InputStreamBlob blob = null;//from  ww w.j  a va2  s  .  c o m
    HttpServletRequest req = x.get(HttpServletRequest.class);
    HttpServletResponse resp = x.get(HttpServletResponse.class);

    try {
        int size = req.getContentLength();
        blob = new InputStreamBlob(req.getInputStream(), size);
        new Outputter(resp.getWriter(), OutputterMode.NETWORK).output(getDelegate().put(blob));
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(blob);
    }
}

From source file:com.thinkberg.webdav.PropFindHandler.java

/**
 * Handle a PROPFIND request./*from w w  w. j  a  v a  2  s.  c om*/
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        logXml(propDoc);

        Element propFindEl = propDoc.getRootElement();
        for (Object propElObject : propFindEl.elements()) {
            Element propEl = (Element) propElObject;
            if (VALID_PROPFIND_TAGS.contains(propEl.getName())) {
                FileObject object = VFSBackend.resolveFile(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 = getMultiStatusResponse(object, propEl, getBaseUrl(request),
                            getDepth(request));
                    logXml(multiStatusResponse);

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

                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                break;
            }
        }
    } catch (DocumentException e) {
        LOG.error("invalid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.everis.storage.web.Controller.java

private String getBody(HttpServletRequest request) throws IOException {
    String body = null;// ww w.j a  v  a  2 s . c  om
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }

    body = stringBuilder.toString();
    return body;
}