Example usage for javax.servlet.http HttpServletRequest getReader

List of usage examples for javax.servlet.http HttpServletRequest getReader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getReader.

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:org.b3log.solo.processor.LoginProcessorTestCase.java

/**
 * forgot.//from www.  ja v  a  2  s  . co m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void forgot() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/forgot");
    when(request.getMethod()).thenReturn("POST");

    final JSONObject requestJSON = new JSONObject();
    requestJSON.put(User.USER_EMAIL, "test@gmail.com");

    final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString()));
    when(request.getReader()).thenReturn(reader);

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "succeed\":true"));
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

/**
 * dumpBody outputs the contents of the request message body to the
 * designated logger.  Note that the use of this method will render the
 * request object inoperable for and subsequent calls.
 * /*from w ww .j  a  v a  2  s .  c o  m*/
 * @param req 
 *          the HttpServletRequest object.
 * @param contentLength 
 *          the content length that was specified in the 
 *          request headers, possibly null
 */
private void dumpBody(HttpServletRequest req, Integer contentLength) {

    if (contentLength != null) {

        try {
            BufferedReader br = req.getReader();
            String line = null;

            logger.info("Request message body:\n");

            if (br.markSupported()) {

                br.mark(contentLength + 1);

                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }

                br.reset();

            }

            br.close();

        } catch (IOException e) {
            logger.error("dumpBody: " + e);
            e.printStackTrace();
        }

    }

}

From source file:org.openhab.io.neeo.internal.servletservices.BrainDashboardService.java

/**
 * Handles the post for the 'updatedevice', 'restoredevice' or 'refreshdevice'.
 *
 * @see DefaultServletService#handlePost(HttpServletRequest, String[], HttpServletResponse)
 *///from ww w  .  ja  va 2s . c  om
@Override
public void handlePost(HttpServletRequest req, String[] paths, HttpServletResponse resp) throws IOException {
    Objects.requireNonNull(req, "req cannot be null");
    Objects.requireNonNull(paths, "paths cannot be null");
    Objects.requireNonNull(resp, "resp cannot be null");
    if (paths.length == 0) {
        throw new IllegalArgumentException("paths cannot be empty");
    }

    try {
        if (StringUtils.equalsIgnoreCase(paths[0], "removebrain")) {
            final BrainInfo info = gson.fromJson(req.getReader(), BrainInfo.class);
            final String brainId = info.getBrainId();
            if (brainId == null) {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainID not specified")));
            } else if (service.removeBrain(brainId)) {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus(true)));
            } else {
                NeeoUtil.write(resp,
                        gson.toJson(new ReturnStatus("BrainID (" + brainId + ") could not be removed")));
            }
        } else if (StringUtils.equalsIgnoreCase(paths[0], "addbrain")) {
            final BrainInfo info = gson.fromJson(req.getReader(), BrainInfo.class);
            final String brainIp = info.getBrainIp();
            if (brainIp == null) {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainIP not specified")));
            } else if (service.addBrain(brainIp)) {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus(true)));
            } else {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus(
                        "Brain (" + brainIp + ") could not be added - no brain at that IP Address")));
            }
        } else {
            logger.debug("Unknown get path: {}", StringUtils.join(paths, ','));
        }
    } catch (JsonParseException | IllegalArgumentException | NullPointerException e) {
        logger.debug("Exception handling get: {}", e.getMessage(), e);
        NeeoUtil.write(resp, gson.toJson(new ReturnStatus(e.getMessage())));
    }
}

From source file:com.controller.schedule.ScheduleEmailActionsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www  . j a  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 {
    response.setContentType("application/json");
    try {
        if (!AuthenticationUtil.isUserLoggedIn(request)) {
            AuthenticationUtil.printAuthErrorToResponse(response);
            return;
        }
        Integer userId = AuthenticationUtil.getUUID(request);

        Map<String, Object> requestBodyMap = AppConstants.GSON.fromJson(new BufferedReader(request.getReader()),
                Map.class);
        if (requestBodyMap == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Request body is missing");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }

        List<String> errorMsgs = validateRequestBody(requestBodyMap);
        if (!errorMsgs.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        //As of now schedule description is not yet mandatory.
        String schedule_id = (String) requestBodyMap.get("schedule_id");
        String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                ? String.valueOf(requestBodyMap.get("schedule_desc"))
                : null;

        Map<String, Integer> idMap = ScheduleDAO.updatetoScheduledEmailList(userId,
                Integer.parseInt(schedule_id), requestBodyMap.get("email_subject").toString(),
                requestBodyMap.get("email_body").toString(),
                requestBodyMap.get("from_email_address").toString(),
                requestBodyMap.get("email_list").toString(), requestBodyMap.get("from_name").toString(),
                requestBodyMap.get("reply_to_email_address").toString(),
                requestBodyMap.get("to_email_addresses").toString().split(","), scheduleDesc,
                TemplateStatus.template_saved.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(idMap));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Invalid format for schedule time.");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (Exception ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.controller.schedule.ScheduleEmailServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w  . jav  a  2  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    try {
        if (!AuthenticationUtil.isUserLoggedIn(request)) {
            AuthenticationUtil.printAuthErrorToResponse(response);
            return;
        }
        Integer userId = AuthenticationUtil.getUUID(request);

        Map<String, Object> requestBodyMap = AppConstants.GSON.fromJson(new BufferedReader(request.getReader()),
                Map.class);
        if (requestBodyMap == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Request body is missing");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }

        List<String> errorMsgs = validateRequestBody(requestBodyMap);
        if (!errorMsgs.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        Double schedule = (Double) requestBodyMap.get("schedule_time");
        //As of now schedule description is not yet mandatory.
        String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                ? String.valueOf(requestBodyMap.get("schedule_desc"))
                : null;

        Map<String, Integer> idMap = ScheduleDAO.addToScheduledEmailList(userId,
                requestBodyMap.get("email_subject").toString(), requestBodyMap.get("email_body").toString(),
                requestBodyMap.get("from_email_address").toString(),
                requestBodyMap.get("email_list").toString(), requestBodyMap.get("from_name").toString(),
                requestBodyMap.get("reply_to_email_address").toString(),
                requestBodyMap.get("to_email_addresses").toString().split(","),
                requestBodyMap.get("schedule_title").toString(), scheduleDesc,
                new Timestamp(schedule.longValue()), TemplateStatus.template_saved.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(idMap));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Invalid format for schedule time.");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (Exception ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = buildUrl(req);/*from  w  ww  . jav  a2s  .  c om*/
    Map<String, ?> params = new HashMap<String, Object>();

    Map<String, String> resultMap = new HashMap<String, String>();

    try {
        params = deserializer.deserialize(req.getReader());
        if ("/login".equals(path)) {
            SessionService sessionService = (SessionService) findInstance(SessionServiceImpl.class);
            User user = sessionService.login((String) params.get("username"), (String) params.get("password"));
            resultMap.put("outcome", "success");
            req.getSession().setAttribute("user", user);
            if (user != null) {
                resultMap.put("result", serializer.deepSerialize(user));
            }
        } else if ("/logout".equals(path)) {
            req.getSession().removeAttribute("user");
            req.getSession().invalidate();
            resultMap.put("outcome", "success");
        } else {
            Method m = findRestMethod(RESTMethod.POST, path);
            @SuppressWarnings("unchecked")
            Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass());
            Object args[] = new Object[m.getParameterTypes().length];

            int i = 0;

            for (Annotation[] annotations : m.getParameterAnnotations()) {
                RESTParam restAnnotation = null;

                for (Annotation a : annotations) {
                    if (a.annotationType() == RESTParam.class) {
                        restAnnotation = (RESTParam) a;
                        break;
                    }
                }
                if (restAnnotation == null) {
                    throw new RuntimeException("REST method has non REST annotated parameter");
                }
                Class<?> targetClass = m.getParameterTypes()[i];
                Object value;
                if (restAnnotation.session()) {
                    value = convert(req.getSession().getAttribute(restAnnotation.value()), targetClass);
                } else {
                    value = convert(params.get(restAnnotation.value()), targetClass);
                }
                if (value == null) {
                    throw new RuntimeException(
                            "Parameter " + restAnnotation.value() + " not found in request for " + path);
                }
                args[i++] = value;
            }

            Object result = m.invoke(instance, args);
            resultMap.put("outcome", "success");
            if (result != null) {
                resultMap.put("result", serializer.deepSerialize(result));
            }
        }

    } catch (Exception e) {
        Throwable t = e;
        if (e instanceof InvocationTargetException) {
            t = e.getCause();
        }
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);

        t.printStackTrace(writer);

        resultMap.put("outcome", "error");
        resultMap.put("message", t.getMessage());
        resultMap.put("type", t.getClass().getCanonicalName());
        resultMap.put("stacktrace", stringWriter.getBuffer().toString());
    }

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");

    serializer.deepSerialize(resultMap, resp.getWriter());
}

From source file:org.structr.rest.servlet.GraphQLServlet.java

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

    try {//from ww  w . j  a v  a 2 s.  c  om

        assertInitialized();

        // first thing to do!
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        // get reader before initalizing security context
        final String query = IOUtils.toString(request.getReader());

        handleGraphQLRequest(request, response, query);

    } catch (FrameworkException fex) {

        // set status & write JSON output
        response.setStatus(fex.getStatus());

        getGson().toJson(fex, response.getWriter());

        response.getWriter().println();
    }
}

From source file:org.o3project.odenos.remoteobject.rest.servlet.RestServlet.java

protected void doRequestToComponent(HttpServletRequest req, HttpServletResponse resp, Request.Method method)
        throws ServletException, IOException {
    Matcher matcher = RestServlet.PATH_PATTERN.matcher(req.getRequestURI());
    if (!matcher.find()) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*from   w  w w. j  ava 2s. co  m*/
    }
    String objectId = matcher.group(1);
    String path = matcher.group(2);
    if (req.getQueryString() != null) {
        path = path + "?" + URLDecoder.decode(req.getQueryString(), "utf-8");
    }
    Object reqBody = JSONValue.parse(req.getReader());

    RESTTranslator translator = (RESTTranslator) req.getServletContext()
            .getAttribute(Attributes.REST_TRANSLATOR);
    Response odenosResp;
    try {
        odenosResp = translator.request(objectId, method, path, reqBody);
    } catch (Exception e) {
        this.logger.debug("Failed to request [{}, {}, {}, {}]", objectId, method, path, reqBody, e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    resp.setStatus(odenosResp.statusCode);
    if (!odenosResp.isBodyNull()) {
        Value value;
        try {
            byte[] packed = this.messagePack.write(odenosResp);
            value = this.messagePack.read(packed);
        } catch (IOException e) {
            this.logger.debug("Failed to serialize a response body. /req:[{}, {}, {}, {}]", objectId, method,
                    path, reqBody);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        resp.getWriter().write(value.asArrayValue().get(1).toString());
    }
}

From source file:org.b3log.solo.processor.LoginProcessorTestCase.java

/**
 * login./*w ww .j a  v  a 2s . co  m*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void login() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/login");
    when(request.getMethod()).thenReturn("POST");

    final JSONObject requestJSON = new JSONObject();
    requestJSON.put(User.USER_EMAIL, "test@gmail.com");
    requestJSON.put(User.USER_PASSWORD, "pass");

    final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString()));
    when(request.getReader()).thenReturn(reader);

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "isLoggedIn\":true"));
}

From source file:org.venice.beachfront.bfapi.services.IABrokerPassthroughService.java

public ResponseEntity<String> passthroughRequest(HttpMethod method, HttpServletRequest request)
        throws MalformedURLException, IOException, URISyntaxException, UserException {
    // URI to ia-Broker will strip out the /ia prefix that the bf-api uses to denote ia-broker proxying
    // Single data source right now, which is planet. In the future, we will switch on the sensor/item type to
    // determine the source (or have the source just injected)
    String requestPath = request.getRequestURI().replaceAll("/ia/", "/");
    URI uri = new URI(IA_BROKER_PROTOCOL, null, IA_BROKER_SERVER, IA_BROKER_PORT, requestPath,
            request.getQueryString(), null);
    String body = IOUtils.toString(request.getReader());
    piazzaLogger.log(String.format("Proxying request to IA Broker at URI %s", uri.toString()),
            Severity.INFORMATIONAL);
    try {// w  w w. ja va 2 s  . c  o m
        ResponseEntity<String> response = restTemplate.exchange(uri, method, new HttpEntity<String>(body),
                String.class);
        piazzaLogger.log(
                String.format("Received IA Broker response, code=%d, length=%d, for URI %s",
                        response.getStatusCodeValue(),
                        response.getBody() == null ? 0 : response.getBody().length(), uri.toString()),
                Severity.INFORMATIONAL);
        return response;
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        piazzaLogger.log(String.format("Received IA Broker error response, code=%d, length=%d, for URI %s",
                exception.getStatusCode().value(), exception.getResponseBodyAsString().length(),
                uri.toString()), Severity.ERROR);
        if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || exception.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
            throw new UserException(exception.getResponseBodyAsString(), exception,
                    exception.getResponseBodyAsString(), HttpStatus.PRECONDITION_FAILED);
        }
        throw new UserException("Upstream image broker error", exception, exception.getResponseBodyAsString(),
                exception.getStatusCode());
    }
}