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:edu.slu.tpen.servlet.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method by logging in using the given credentials.  Credentials
 * should be specified as a JSON object in the request body.  There is also a deprecated way of passing
 * the credentials as query parameters./*from www .  jav a 2 s.  c om*/
 *
 * @param req servlet request
 * @param resp servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String mail = null, password = null;
        if (req.getContentLength() > 0) {
            String contentType = getBaseContentType(req);
            if (contentType.equals("application/json")) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> creds = mapper.readValue(req.getInputStream(),
                        new TypeReference<Map<String, String>>() {
                        });
                mail = creds.get("mail");
                password = creds.get("password");
            }
        } else {
            // Deprecated approach where user-name and password are passed on the query string.
            mail = req.getParameter("uname");
            password = req.getParameter("password");
        }
        if (mail != null && password != null) {
            User u = new User(mail, password);
            if (u.getUID() > 0) {
                HttpSession sess = req.getSession(true);
                sess.setAttribute("UID", u.getUID());
            } else {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        } else if (mail == null && password == null) {
            // Passing null data indicates a logout.
            HttpSession sess = req.getSession(true);
            sess.removeAttribute("UID");
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            // Only supplied one of user-id and password.
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (NoSuchAlgorithmException ex) {
        reportInternalError(resp, ex);
    }
}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private byte[] copyPostedData(HttpServletRequest req) throws IOException {
    int size = req.getContentLength();
    if (req.getMethod().equalsIgnoreCase("GET") || size <= 0) {
        return null;
    }//from ww  w  . ja  v  a  2s .c  o m
    InputStream is = req.getInputStream();
    ByteArrayOutputStream baos = null;
    try {
        if (size < 0)
            size = 0;
        baos = new ByteArrayOutputStream(size);
        byte[] buffer = new byte[8192];
        int num;
        while ((num = is.read(buffer)) != -1) {
            baos.write(buffer, 0, num);
        }
        return baos.toByteArray();
    } finally {
        ByteUtil.closeStream(baos);
    }
}

From source file:com.tc.webshell.servlets.RestSimple.java

/**
 * Processes requests for both HTTP/*from   www  . ja va2 s. co m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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 {
    response.setContentType("application/json;charset=UTF-8");

    try {
        Database db = ContextInfo.getUserDatabase();
        String json = null;

        if ("POST".equals(request.getMethod())) {
            json = IOUtils.toString(request.getInputStream());

        } else if ("GET".equals(request.getMethod())) {
            json = request.getParameter(WebshellConstants.PARAM_JSON);

        } else {
            json = IOUtils.toString(request.getInputStream());
        }

        if (StrUtils.isNull(json)) {
            Prompt error = new Prompt();
            error.setMessage("No json data found");
            error.setTitle("ERROR");
            json = MapperFactory.mapper().writeValueAsString(error);
            this.compressResponse(request, response, json);
            return;
        }

        Document doc = new DocFactory().buildDocument(request, db, json);
        String message = doc.getItemValueString("Form") + " created successfully";

        Prompt prompt = new Prompt();

        prompt.setMessage(message);
        prompt.setTitle("info");

        prompt.addProperty(WebshellConstants.PARAM_NOTEID, doc.getNoteID());
        prompt.addProperty(WebshellConstants.PARAM_UNID, doc.getUniversalID());

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd G 'at' HH:mm:ss z");
        String strdate = formatter.format(doc.getCreated().toJavaDate());

        prompt.addProperty(WebshellConstants.PARAM_CREATED, strdate);

        //lets add all the fields from the doc as a property
        for (Object o : doc.getItems()) {
            Item item = (Item) o;
            prompt.addProperty(item.getName(), item.getText());
        }
        json = MapperFactory.mapper().writeValueAsString(prompt);

        this.compressResponse(request, response, json);

        doc.recycle();

    } catch (NotesException e) {
        logger.log(Level.SEVERE, null, e);
    }
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

private void consumeInputFully(HttpServletRequest req) {
    try {/*from  w w w. j  a  v  a2  s  . c  o  m*/
        ServletInputStream is = req.getInputStream();
        while (!is.isFinished() && is.read() != -1) {
        }
    } catch (IOException e) {
        log.info("Could not consume full client request", e);
    }
}

From source file:com.centurylink.mdw.hub.servlet.SoapServlet.java

private String getRequestString(HttpServletRequest request) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuffer requestBuffer = new StringBuffer();
    String line = null;//from   w  w w  . j a va  2 s  .  co m
    while ((line = reader.readLine()) != null) {
        requestBuffer.append(line).append('\n');
    }
    return requestBuffer.toString();

}

From source file:com.adaptris.core.http.jetty.JettyMessageConsumer.java

@Override
public AdaptrisMessage createMessage(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    AdaptrisMessage msg = null;//from   w  ww  .j  a  va  2  s  .co  m
    try {
        logHeaders(request);
        if (getEncoder() != null) {
            msg = getEncoder().readMessage(request);
        } else {
            msg = defaultIfNull(getMessageFactory()).newMessage();
            try (InputStream in = request.getInputStream(); OutputStream out = msg.getOutputStream()) {
                if (request.getContentLength() == -1) {
                    IOUtils.copy(request.getInputStream(), out);
                } else {
                    StreamUtil.copyStream(request.getInputStream(), out, request.getContentLength());
                }
            }
        }
        msg.setContentEncoding(request.getCharacterEncoding());
        addParamMetadata(msg, request);
        addHeaderMetadata(msg, request);
    } catch (CoreException e) {
        throw new IOException(e.getMessage(), e);
    }
    return msg;
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTUser.java

protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {/*  ww w  .j a  v  a  2s  .c om*/
        String userName = restUtils.extractResourceName(req.getPathInfo());

        WSUser user = restUtils.populateServiceObject(restUtils.unmarshal(WSUser.class, req.getInputStream()));
        if (log.isDebugEnabled()) {
            log.debug("un Marshaling OK");
        }

        if (validateUserForPutOrUpdate(user)) {
            if (!isAlreadyAUser(user)) {
                userAndRoleManagementService.putUser(user);
                restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");
            } else {
                throw new ServiceException(HttpServletResponse.SC_FORBIDDEN,
                        "user " + user.getUsername() + "already exists");
            }
        } else
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters");

    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }

}

From source file:com.erudika.scoold.controllers.ReportsController.java

@PostMapping("/cspv")
@SuppressWarnings("unchecked")
public String createCSPViolationReport(HttpServletRequest req) throws IOException {
    if (Config.getConfigBoolean("csp_reports_enabled", false)) {
        Report rep = new Report();
        rep.setDescription("CSP Violation Report");
        rep.setSubType(Report.ReportType.OTHER);
        rep.setLink("-");
        rep.setAuthorName("Scoold");
        Map<String, Object> body = ParaObjectUtils.getJsonReader(Map.class).readValue(req.getInputStream());
        if (body != null && !body.isEmpty()) {
            rep.setProperties(/* ww  w  .  ja  va2 s.co m*/
                    (Map<String, Object>) (body.containsKey("csp-report") ? body.get("csp-report") : body));
        }
        rep.create();
    }
    return "redirect:/";
}

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

private void add(HttpServletRequest request, String pathInfo, HttpServletResponse response) throws Exception {
    String eventType = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);

    UTF8InputStreamReaderWrapper reader;

    if (request.getCharacterEncoding() != null) {
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream(), request.getCharacterEncoding());
    } else {/* w ww  .  j  a v  a 2s.  c  om*/
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream());
    }

    Map<String, Object> values = mapper.readValue(reader, TYPE_FLATMAP);

    if (validator != null) {
        ValidationResult result = validator.validate(values, eventType);
        if (result == null || result.isSuccess()) {
            JetstreamEvent event = createEvent(values, eventType);
            inboundChannel.onMessage(event);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().print(validateReusltWriter.writeValueAsString(result));
        }
    } else {
        JetstreamEvent event = createEvent(values, eventType);
        inboundChannel.onMessage(event);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

From source file:eu.city4ageproject.delivery.HTTPService.java

/**{@inheritDoc} */
@Override// www. j a  va  2  s  .c  o m
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getContentType() != null && req.getContentType().toLowerCase().contains("application/json")
    //            && req.getCharacterEncoding() != null
    //            && req.getCharacterEncoding().toLowerCase().contains("utf")
    //            && req.getCharacterEncoding().toLowerCase().contains("8")
    ) {
        ServletInputStream is = req.getInputStream();
        String request = IOUtils.toString(is, "UTF-8");
        try {
            DeliveryRequest drequest = gsonBuilder.create().fromJson(request, DeliveryRequest.class);
            if (drequest.getPilotID() != null && !drequest.getPilotID().isEmpty()
                    && drequest.getUserID() != null && !drequest.getUserID().isEmpty()
                    && drequest.getIntervention() != null) {
                //connect to uAAL
                if (delivery.sendIntervention(drequest))
                    resp.setStatus(HttpServletResponse.SC_ACCEPTED);
                else
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            //TODO get parameters into the Actual delivery
        } catch (JsonSyntaxException e) {
            e.printStackTrace();

        }
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.\n cotnent is not compliant to schema.");
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.<br> " + "Content-Type: application/json <br>"
        //               +" Content-Encoding: UTF-8"
        );
    }
}