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.eclipse.swordfish.registry.WSDLServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    LOGGER.info("Received PUT request:\n" + req.getRequestURL());
    Resource resource = null;/* w  ww.j  av a  2  s.com*/

    try {
        resource = router.getResource(req);
    } catch (IncorrectRequestException e) {
        resp.sendError(e.getErrorCode(), e.getErrorMessage());
        return;
    }

    try {
        resource.put(req.getReader());
    } catch (InvalidFormatException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Body does not contain a valid WSDL.");
        return;
    } catch (VerbNotSupportedException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT is not supported for " + req.getRequestURL());
    }
}

From source file:uk.ac.imperial.presage2.web.SimulationsTreeServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logRequest(req);//w w w. ja v a 2  s .  com
    String path = req.getPathInfo();
    Matcher matcher = ID_REGEX.matcher(path);
    if (matcher.matches()) {
        long simId = Integer.parseInt(matcher.group(1));
        try {
            // get data sent to us
            JSONObject input = new JSONObject(new JSONTokener(req.getReader()));
            if (simId > 0 && (input.getString("parentId").equalsIgnoreCase("root")
                    || input.getLong("parentId") > 0)) {
                PersistentSimulation sim = sto.getSimulationById(simId);
                PersistentSimulation parent = null;
                if (input.getString("parentId").equalsIgnoreCase("root")) {
                    parent = null;
                } else if (input.getLong("parentId") > 0 && input.getLong("parentId") != simId) {
                    parent = sto.getSimulationById(input.getLong("parentId"));
                } else {
                    resp.setStatus(400);
                    return;
                }
                if (sim != null) {
                    sim.setParentSimulation(parent);
                    resp.setStatus(200);
                    return;
                }
            }
            resp.setStatus(400);
        } catch (JSONException e) {
            resp.setStatus(400);
        }
    } else {
        resp.setStatus(400);
    }
}

From source file:io.klerch.alexa.tellask.model.wrapper.AlexaSpeechletServletTest.java

private SpeechletResponseEnvelope doPost(final AlexaSpeechletServlet servlet,
        final SpeechletRequestEnvelope envelope) throws Exception {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);

    final InputStream stream = convertToStream(envelope);

    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override/*  w  w  w  . ja  v  a  2s  .  com*/
        public int read() throws IOException {
            return stream.read();
        }
    };
    when(request.getInputStream()).thenReturn(servletInputStream);
    when(request.getReader()).thenReturn(new BufferedReader(new InputStreamReader(stream)));

    final ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
    final HttpServletResponse response = givenServletResponse(responseStream);
    servlet.doPost(request, response);

    return convertToResponseEnvelope(responseStream);
}

From source file:org.davidmendoza.fileUpload.web.VideoController.java

private void handleSignatureRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    log.info("sigin to S3");
    resp.setContentType("application/json");
    resp.setStatus(200);/*from  w ww  .j  a va  2s .  com*/

    JsonParser jsonParser = new JsonParser();
    JsonElement contentJson = jsonParser.parse(req.getReader());
    JsonObject jsonObject = contentJson.getAsJsonObject();
    JsonElement headers = jsonObject.get("headers");
    JsonObject response = new JsonObject();
    String signature;

    try {
        // If this is not a multipart upload-related request, Fine Uploader will send a policy document
        // as the value of a "policy" property in the request.  In that case, we must base-64 encode
        // the policy document and then sign it. The will include the base-64 encoded policy and the signed policy document.
        if (headers == null) {
            String base64Policy = base64EncodePolicy(contentJson);
            signature = sign(base64Policy);

            // Validate the policy document to ensure the client hasn't tampered with it.
            // If it has been tampered with, set this property on the response and set the status to a non-200 value.
            //                response.addProperty("invalid", true);

            response.addProperty("policy", base64Policy);
        }

        // If this is a request to sign a multipart upload-related request, we only need to sign the headers,
        // which are passed as the value of a "headers" property from Fine Uploader.  In this case,
        // we only need to return the signed value.
        else {
            signature = sign(headers.getAsString());
        }

        response.addProperty("signature", signature);
        resp.getWriter().write(response.toString());
    } catch (Exception e) {
        resp.setStatus(500);
    }
}

From source file:com.cloudera.oryx.kmeans.serving.web.AddServlet.java

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

    KMeansGenerationManager generationManager = getGenerationManager();
    Generation generation = generationManager.getCurrentGeneration();
    if (generation == null) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "API method unavailable until model has been built and loaded");
        return;// w w w.  j  a v a2  s  .  co  m
    }

    for (CharSequence line : CharStreams.readLines(request.getReader())) {
        generationManager.append(line);

        RealVector vec = generation.toVector(DelimitedDataUtils.decode(line));
        if (vec == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong column count");
            return;
        }

        // TODO update the centers, along the lines of Meyerson et al.
    }

}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

protected void handlePreview(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("application/json");
    Gson gson = new Gson();

    BufferedReader reader = req.getReader();
    String msg = IOUtils.toString(reader);
    System.out.println("Msg: " + msg);

    Map<String, Object> params = gson.fromJson(msg, Map.class);
    String url = req.getPathInfo();
    System.out.println("Path: " + url);

    params.put(QUEUE_PREPEND + "action", "preview");

    int idx = url.indexOf("/", 1);
    String kernel_name = url.substring(1, idx);

    System.out.println("kernel: " + kernel_name);
    System.out.println("que: " + QUEUE_PREPEND + kernel_name);
    String qurl = queUrlMap.get(QUEUE_PREPEND + kernel_name);

    if (qurl == null) {
        System.out.println("Unknown que");
        issueError("Unknown queue: " + kernel_name, resp);
        return;/*from w w w  .  j  a  va 2 s. co m*/
    }

    // TODO: Need to insure < 64K
    msg = gson.toJson(params);
    SQSEnqueueTask task = new SQSEnqueueTask(sqs, qurl, msg);
    threadPool.submit(task);

    Map<String, Object> result = new HashMap<String, Object>();

    result.put("result", "success");

    String json = gson.toJson(result);

    resp.setContentLength(json.length());
    resp.setStatus(HttpServletResponse.SC_OK);

    ServletOutputStream sos = resp.getOutputStream();
    byte[] ba = json.getBytes();
    sos.write(ba, 0, ba.length);

    resp.flushBuffer();
}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

protected void handleOrder(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("application/json");
    Gson gson = new Gson();

    BufferedReader reader = req.getReader();
    String msg = IOUtils.toString(reader);
    System.out.println("Msg: " + msg);

    Map<String, Object> params = gson.fromJson(msg, Map.class);
    String url = req.getPathInfo();
    System.out.println("Path: " + url);

    params.put(QUEUE_PREPEND + "action", "order");

    int idx = url.indexOf("/", 1);
    String kernel_name = url.substring(1, idx);

    System.out.println("kernel: " + kernel_name);
    System.out.println("que: " + QUEUE_PREPEND + kernel_name);
    String qurl = queUrlMap.get(QUEUE_PREPEND + kernel_name);

    if (qurl == null) {
        System.out.println("Unknown que");
        issueError("Unknown queue: " + kernel_name, resp);
        return;//from  w  w w  . j a v  a  2 s .c  o  m
    }

    // TODO: Need to insure < 64K
    msg = gson.toJson(params);
    SQSEnqueueTask task = new SQSEnqueueTask(sqs, qurl, msg);
    threadPool.submit(task);

    Map<String, Object> result = new HashMap<String, Object>();

    result.put("result", "success");

    String json = gson.toJson(result);

    resp.setContentLength(json.length());
    resp.setStatus(HttpServletResponse.SC_OK);

    ServletOutputStream sos = resp.getOutputStream();
    byte[] ba = json.getBytes();
    sos.write(ba, 0, ba.length);

    resp.flushBuffer();

}

From source file:fr.rktv.iamweb.services.servlets.Register.java

/**
 * @see Register#doPost(HttpServletRequest request, 
 * HttpServletResponse response)//from  w w  w  . ja v a 2s. c  om
 *  @param request -HttpServletRequest
 *  @param response -HttpServletResponse
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String resString = "Succesfully Created Administrative Account in";
    try {
        StringBuffer buffReq = new StringBuffer();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            buffReq.append(line);

        Credentail user = new ObjectMapper().readValue(buffReq.toString(), Credentail.class);
        if (authenticationDAO.licensedUserAlreadyExist(user.getLicense())) {
            resString = "Licensed Account already Exists.Contact Admin for new License";
        } else {
            if (authenticationDAO.checkValidLicense(user.getLicense())) {
                authenticationDAO.addUser(user);
            } else {
                resString = "Invalid License.Contact Admin for correct License";
                LogManager.log("Invalid License.Contact Admin for correct License", this.getClass(),
                        Level.ERROR);
            }
        }
    } catch (Exception exp) {
        resString = "Error while creating Account. Contact Admin";
        LogManager.log(exp.getMessage(), this.getClass(), Level.ERROR);
    } finally {
        out.write(resString);
        out.flush();
        out.close();
    }

}

From source file:net.bhira.sample.api.controller.CompanyController.java

/**
 * Save the given instance of {@link net.bhira.sample.model.Company}. It will create a new
 * instance of the company does not exist, otherwise it will update the existing instance.
 * /*from w ww . j a  v a2 s.  co  m*/
 * @param request
 *            the http request containing JSON payload in its body.
 * @param response
 *            the http response to which the results will be written.
 * @return the error message, if save was not successful.
 */
@RequestMapping(value = "/company", method = RequestMethod.POST)
@ResponseBody
public Callable<String> saveCompany(HttpServletRequest request, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing POST company");
                Gson gson = JsonUtil.createGson();
                Company company = gson.fromJson(request.getReader(), Company.class);
                LOG.debug("POST company received json = {}", gson.toJson(company));
                companyService.save(company);
                HashMap<String, Long> map = new HashMap<String, Long>();
                map.put("id", company.getId());
                body = gson.toJson(map);
                LOG.debug("POST company/ successful with return ID = {}", company.getId());
            } catch (Exception ex) {
                if (ex instanceof JsonSyntaxException) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }
                body = ex.getLocalizedMessage();
                LOG.warn("Error saving company. {}", body);
                LOG.debug("Save error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.flaptor.indextank.api.resources.Docs.java

/**
 * @see java.lang.Runnable#run()//from  w  w  w. java 2  s .  c o m
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    HttpServletResponse res = res();
    HttpServletRequest req = req();

    String characterEncoding = api.getCharacterEncoding();
    try {
        req.setCharacterEncoding(characterEncoding);
        res.setCharacterEncoding(characterEncoding);
        res.setContentType("application/json");
    } catch (UnsupportedEncodingException ignored) {
    }

    try {
        Object parse = JSONValue.parseWithException(req.getReader());
        if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503
            JSONObject jo = (JSONObject) parse;
            try {
                putDocument(api, jo);
                res.setStatus(200);
                return;

            } catch (Exception e) {
                e.printStackTrace();
                if (LOG_ENABLED)
                    LOG.severe(e.getMessage());
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
        } else if (parse instanceof JSONArray) {
            JSONArray statuses = new JSONArray();
            JSONArray ja = (JSONArray) parse;
            if (!validateDocuments(ja)) {
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
            boolean hasError = false;
            for (Object o : ja) {
                JSONObject jo = (JSONObject) o;
                JSONObject status = new JSONObject();
                try {
                    putDocument(api, jo);
                    status.put("added", true);
                } catch (Exception e) {
                    status.put("added", false);
                    status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg
                    hasError = true;
                }
                statuses.add(status);
            }
            print(statuses.toJSONString());
            return;
        }
    } catch (IOException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (ParseException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (Exception e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc " + e.getMessage());
    }
    res.setStatus(503);
    print("Service unavailable"); // TODO: descriptive error msg
}