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:com.google.wave.api.AbstractRobotServlet.java

private String getRequestBody(HttpServletRequest req) throws IOException {
    StringBuilder json = new StringBuilder();
    BufferedReader reader = req.getReader();
    String line;/*from  w w w.  j  av a  2  s  .  c o  m*/
    while ((line = reader.readLine()) != null) {
        json.append(line);
    }
    return json.toString();
}

From source file:com.google.wave.api.AbstractRobot.java

/**
 * Reads the given HTTP request's input stream into a string.
 *
 * @param req the HTTP request to be read.
 * @return a string representation of the given HTTP request's body.
 *
 * @throws IOException if there is a problem reading the body.
 *//*from ww  w.  java  2 s  .  c o  m*/
private static String readRequestBody(HttpServletRequest req) throws IOException {
    StringBuilder json = new StringBuilder();
    BufferedReader reader = req.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        json.append(line);
    }
    return json.toString();
}

From source file:org.atmosphere.samples.pubsub.PubSubController.java

private void processPost(String topic, HttpServletRequest req, AtmosphereResource resource) throws IOException {

    String restOfTheUrl = (String) req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

    Broadcaster b = lookupBroadcaster(topic, restOfTheUrl);

    String message = req.getReader().readLine();
    resource.resume();//from w w  w  .  j a  v  a  2  s . c o m
    if (message != null && message.indexOf("message") != FORE_EVER) {
        b.broadcast(message.substring("message=".length()));
    }
}

From source file:gwap.game.quiz.PlayNHighscoreCommunicationResource.java

private QuizHighscore readOutJSONData(HttpServletRequest request) throws IOException {
    QuizHighscore quizHighscore = null;/* w w w.  j ava2 s  .c  o m*/
    BufferedReader reader = request.getReader();
    StringBuilder sb = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
        sb.append(line + "\n");
        line = reader.readLine();
    }
    reader.close();
    String data = sb.toString();
    if (data.equals("")) {
        return null;
    }

    JSONParser parser = new JSONParser();

    quizHighscore = new QuizHighscore();

    quizHighscore.setCreated(new Date());

    Object obj;
    try {
        obj = parser.parse(data);
        JSONObject jsonObject = (JSONObject) obj;

        for (Object k : jsonObject.keySet()) {

            Object value = jsonObject.get(k);
            String key = (String) k;

            if (key.equals("Name")) {
                quizHighscore.setUsername((String) value);
            } else if (key.equals("PunkteAnzahl")) {
                quizHighscore.setScore(((Long) value).intValue());
            } else if (key.equals("Joker")) {
                quizHighscore.setJoker(((Long) value).intValue());
            } else if (key.equals("Frage")) {
                quizHighscore.setQuestion(((Long) value).intValue());
            } else if (key.equals("Action")) {
                this.action = (String) value;
            } else if (key.equals("HighScoreMode")) {
                this.mode = (String) value;
            }

        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return quizHighscore;
}

From source file:servlets.Signin.java

/**
 * Processing POST requests on /signup//w  w w .j a v  a  2  s .  c  o m
 *
 * @param request servlet request in JSON
 * @param response servlet response inJSON
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // JSON ?  ?
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
    } catch (IOException ex) {

    }
    String sourceJson = jb.toString();
    ObjectMapper mapper = new ObjectMapper();
    InsertUserTemplate userToAdd = mapper.readValue(sourceJson, InsertUserTemplate.class);
    // JSON    ?    
    int status = UserActions.loginUser(userToAdd, request.getSession().getId());
    try (PrintWriter out = response.getWriter()) {
        if (status == 200) {
            InsertedUserTemplate userTempl = new InsertedUserTemplate(status, request.getSession().getId());
            mapper.writeValue(out, userTempl);
        } else {
            response.setStatus(status);
            ErrorTemplate error = new ErrorTemplate(status);
            mapper.writeValue(out, error);
        }

    } catch (Exception e) {
        //do somthing
    }
}

From source file:org.openhab.binding.neeo.internal.handler.NeeoForwardActionsServlet.java

/**
 * Processes the post action from the NEEO brain. Simply get's the specified json and then forwards it on (if
 * needed)// ww  w .  j a v a 2 s  .co  m
 *
 * @param req the non-null request
 * @param resp the non-null response
 */
@Override
protected void doPost(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
        throws ServletException, IOException {
    Objects.requireNonNull(req, "req cannot be null");
    Objects.requireNonNull(resp, "resp cannot be null");

    final String json = IOUtils.toString(req.getReader());
    logger.debug("handleForwardActions {}", json);

    callback.post(json);

    final String fc = forwardChain;
    if (fc != null && StringUtils.isNotEmpty(fc)) {
        scheduler.execute(() -> {
            try (final HttpRequest request = new HttpRequest()) {
                for (final String forwardUrl : fc.split(",")) {
                    if (StringUtils.isNotEmpty(forwardUrl)) {
                        final HttpResponse httpResponse = request.sendPostJsonCommand(forwardUrl, json);
                        if (httpResponse.getHttpCode() != HttpStatus.OK_200) {
                            logger.debug("Cannot forward event {} to {}: {}", json, forwardUrl,
                                    httpResponse.getHttpCode());
                        }
                    }
                }
            }
        });
    }
}

From source file:org.betaconceptframework.astroboa.console.security.ResourceApiProxy.java

private String getBody(HttpServletRequest httpServletRequest) throws Exception {

    BufferedReader bufferedReader = null;
    StringBuilder stringBuilder = new StringBuilder();

    try {/*from  w ww . j  ava 2  s.  c o m*/
        bufferedReader = httpServletRequest.getReader();

        char[] buffer = new char[4 * 1024]; // 4 KB char buffer  

        int len;

        while ((len = bufferedReader.read(buffer, 0, buffer.length)) != -1) {
            stringBuilder.append(buffer, 0, len);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                throw e;
            }
        }
    }

    return stringBuilder.toString();
}

From source file:au.com.iglooit.shar.servlet.FileServlet.java

/**
 * Create a new file given a JSON representation, and return the JSON
 * representation of the created file./*from  w  w w  . j a v a  2  s  . c om*/
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setHeader("Access-Control-Allow-Origin", "*");
    Drive service = getDriveService(getDefaultCredential(req, resp));
    ClientFile clientFile = new ClientFile(req.getReader());
    File file = clientFile.toFile();

    byte[] imageData = Base64.decodeBase64(clientFile.content);
    ByteArrayContent byteArrayContent = new ByteArrayContent(clientFile.mimeType, imageData);

    if (!clientFile.content.equals("")) {
        if (StringUtils.isBlank(file.getId())) {
            file = service.files().insert(file, byteArrayContent).execute();
        } else {
            file = service.files().update(file.getId(), file, byteArrayContent).execute();
        }
    } else {
        if (StringUtils.isBlank(file.getId())) {
            file = service.files().insert(file).execute();
        } else {
            file = service.files().update(file.getId(), file).execute();
        }
    }
    sendJson(resp, file.getId());
}

From source file:org.geowebcache.rest.controller.ReloadController.java

@RequestMapping(value = "/reload", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<?> doPost(HttpServletRequest request, HttpServletResponse resp)
        throws GeoWebCacheException, RestException, IOException {

    String data;//from w  w w  .  j  a va 2  s  .c o m

    try {
        StringBuilder buffer = new StringBuilder();
        BufferedReader formReader = request.getReader();
        String line;
        while ((line = formReader.readLine()) != null) {
            buffer.append(line);
        }
        data = buffer.toString();
    } catch (IOException e) {
        data = null;
    }

    Map<String, String> params = splitToMap(data);

    if (data == null || !params.containsKey("reload_configuration")) {
        throw new RestException(
                "Unknown or malformed request. Please try again, somtimes the form "
                        + "is not properly received. This frequently happens on the first POST "
                        + "after a restart. The POST was to " + request.getRequestURI(),
                HttpStatus.BAD_REQUEST);
    }

    StringBuilder doc = new StringBuilder();

    doc.append("<html>\n" + ServletUtils.gwcHtmlHeader("../", "GWC Reload") + "<body>\n"
            + ServletUtils.gwcHtmlLogoLink("../"));

    try {
        layerDispatcher.reInit();
        String info = "Configuration reloaded. Read " + layerDispatcher.getLayerCount()
                + " layers from configuration resources.";

        log.info(info);
        doc.append("<p>" + info + "</p>");

        doc.append("<p>Note that this functionality has not been rigorously tested,"
                + " please reload the servlet if you run into any problems."
                + " Also note that you must truncate the tiles of any layers that have changed.</p>");

    } catch (Exception e) {
        doc.append("<p>There was a problem reloading the configuration:<br>\n" + e.getMessage() + "\n<br>"
                + " If you believe this is a bug, please submit a ticket at "
                + "<a href=\"http://geowebcache.org\">GeoWebCache.org</a>" + "</p>");
    }

    doc.append("<p><a href=\"../demo\">Go back</a></p>\n");
    doc.append("</body></html>");

    return new ResponseEntity<Object>(doc.toString(), HttpStatus.OK);
}

From source file:org.opennms.protocols.http.TestServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    LOG.info("JUnit Test Request: {}", req.getRequestURI());
    LOG.info("JUnit Test Content Type: {}", req.getContentType());
    String requestContent = IOUtils.toString(req.getReader());
    if (req.getRequestURI().equals("/junit/test/sample")) {
        resp.getWriter().write("OK!");
    }//from w  w w  .  j  a  v  a  2 s .c  om
    if (req.getRequestURI().equals("/junit/test/post")) {
        if (req.getContentType().startsWith("application/xml")) {
            resp.setContentType("application/xml");
            Person p = JaxbUtils.unmarshal(Person.class, requestContent);
            SampleData data = new SampleData();
            data.addParameter("firstName", p.getFirstName());
            data.addParameter("lastName", p.getLastName());
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else if (req.getContentType().startsWith("application/json")) {
            resp.setContentType("application/json");
            JSONObject object = JSONObject.fromObject(requestContent);
            SampleData data = new SampleData();
            data.addParameter("firstName", object.getJSONObject("person").getString("firstName"));
            data.addParameter("lastName", object.getJSONObject("person").getString("lastName"));
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else if (req.getContentType().startsWith("application/x-www-form-urlencoded")) {
            resp.setContentType("application/xml");
            StringTokenizer st = new StringTokenizer(requestContent, "&");
            SampleData data = new SampleData();
            while (st.hasMoreTokens()) {
                String[] pair = ((String) st.nextToken()).split("=");
                data.addParameter(pair[0], pair[1]);
            }
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else {
            resp.setContentType("text/plain");
            resp.getWriter().write("ERROR!");
        }
    }
    if (req.getRequestURI().equals("/junit/test/post-data")) {
        Person p = JaxbUtils.unmarshal(Person.class, requestContent);
        if ("Alejandro".equals(p.getFirstName()) && "Galue".equals(p.getLastName())) {
            SampleData data = new SampleData();
            data.addParameter("contributions", "500");
            data.addParameter("applications", "2");
            data.addParameter("frameworks", "25");
            resp.setContentType("application/xml");
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid request");
        }
    }
}