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.apache.hadoop.hbase.rest.Dispatcher.java

protected byte[] readInputBuffer(HttpServletRequest request) throws HBaseRestException {
    try {/*from   ww w  . j  a va 2  s .co  m*/
        String resultant = "";
        BufferedReader r = request.getReader();

        int defaultmaxlength = 10 * 1024 * 1024;
        int maxLength = this.conf == null ? defaultmaxlength
                : this.conf.getInt("hbase.rest.input.limit", defaultmaxlength);
        int bufferLength = 640;

        // TODO make s maxLength and c size values in configuration
        if (!r.ready()) {
            Thread.sleep(1000); // If r is not ready wait 1 second
            if (!r.ready()) { // If r still is not ready something is wrong, return
                // blank.
                return new byte[0];
            }
        }
        char[] c;// 40 characters * sizeof(UTF16)
        while (true) {
            c = new char[bufferLength];
            int n = r.read(c, 0, bufferLength);
            if (n == -1)
                break;
            resultant += new String(c, 0, n);
            if (resultant.length() > maxLength) {
                resultant = resultant.substring(0, maxLength);
                break;
            }
        }
        return Bytes.toBytes(resultant.trim());
    } catch (Exception e) {
        throw new HBaseRestException(e);
    }
}

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

/**
 * Save the given instance of {@link net.bhira.sample.model.Department}. It will create a new
 * instance of the department does not exist, otherwise it will update the existing instance.
 * /*from   w w  w.j  a  v  a  2 s.  c  o 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 = "/department", method = RequestMethod.POST)
@ResponseBody
public Callable<String> saveDepartment(HttpServletRequest request, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing POST department");
                Gson gson = JsonUtil.createGson();
                Department department = gson.fromJson(request.getReader(), Department.class);
                LOG.debug("POST department received json = {}", gson.toJson(department));
                departmentService.save(department);
                HashMap<String, Long> map = new HashMap<String, Long>();
                map.put("id", department.getId());
                body = gson.toJson(map);
                LOG.debug("POST department/ successful with return ID = {}", department.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 department. {}", body);
                LOG.debug("Save error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:servlets.StudentServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w ww  . j  a  v a2  s.  c o m
 * @param response servlet response
 * @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 {
    try (PrintWriter out = response.getWriter()) {
        try {
            StudentDAO stDao = new StudentDAO();
            Student st = new Student();
            IdCard idCard = new IdCard();
            JSONParser parser = new JSONParser();
            try {
                JSONObject jsonObj = (JSONObject) parser.parse(new BufferedReader(request.getReader()));
                st.setName((String) jsonObj.get("name"));
                idCard.setIdNumber((String) jsonObj.get("idCard"));
                st.setIdCard(idCard);
                stDao.addStudent(st);
            } catch (Exception e) {
                out.println(e.getCause());
            }
        } catch (Exception e) {
            out.println(e.getCause());
        }
    }
}

From source file:jetbrains.buildServer.projectPush.PostProjectToSandboxController.java

@Nullable
@Override/* ww w .  j a  v  a  2  s  .  co  m*/
protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws Exception {
    if (!isPost(request)) {
        response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value());
        return null;
    }

    final StringBuilder stringBuffer = new StringBuilder();
    try {
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            stringBuffer.append(line);
    } catch (Exception e) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
        return null;
    }

    final String projectName = stringBuffer.toString();
    if (projectName.isEmpty()) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "Project name is empty.");
        return null;
    }

    if (mySettings.isDisabled()) {
        response.sendError(HttpStatus.FORBIDDEN.value(), "Sandbox disabled.");
        return null;
    }

    SUser user;
    user = SessionUser.getUser(request);
    if (user == null) {
        user = myAuthHelper.getAuthenticatedUser(request, response);
    }
    if (user == null)
        return null;

    final Role projectAdminRole = myRolesHelper.findProjectAdminRole();
    if (projectAdminRole == null) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Failed to locate Project Admin role on the server.");
        return null;
    }

    final SProject project;
    try {
        final String sandboxProjectId = mySettings.getSandboxProjectId();
        final SProject sandboxProject = myProjectManager.findProjectByExternalId(sandboxProjectId);
        if (sandboxProject == null) {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                    "Failed to locate sandbox project by ID " + sandboxProjectId);
            return null;
        }

        if (sandboxProject.findProjectByName(projectName) != null) {
            response.sendError(HttpStatus.CONFLICT.value(),
                    "Project with name " + projectName + " already exists.");
            return null;
        }

        project = sandboxProject.createProject(
                myProjectIdentifiersManager.generateNewExternalId(null, projectName, null), projectName);
        project.persist();
    } catch (Exception e) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return null;
    }

    try {
        myRolesHelper.addRole(user, RoleScope.projectScope(project.getProjectId()), projectAdminRole);
    } catch (Throwable throwable) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), throwable.getMessage());
        return null;
    }

    response.setStatus(HttpStatus.CREATED.value());
    response.setHeader(HttpHeaders.LOCATION, RESTApiHelper.getProjectURI(project));

    return null;
}

From source file:petascope.wcs2.Wcs2Servlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {

    long startTime = System.currentTimeMillis();

    setServletURL(req);//w  w  w. j a v  a 2s .  c  o m
    meta.clearCache();

    String request = null;
    try {
        try {
            request = IOUtils.toString(req.getReader());

            log.trace("POST request length: " + req.getContentLength());
            log.trace("GET query string: " + req.getQueryString());
            log.trace("POST request body:\n" + request + "\n----------------------------------------\n");

            Map<String, String> params = buildParameterDictionary(request);
            if (params.containsKey("request")) {
                request = params.get("request");
            }
            request = StringUtil.urldecode(request, req.getContentType());
            if (request == null || request.length() == 0) {
                if (req.getQueryString() != null && req.getQueryString().length() > 0) {
                    request = req.getQueryString();
                    request = StringUtil.urldecode(request, req.getContentType());
                } else {
                    printUsage(res, request);
                    return;
                }
            }

            log.debug("Petascope Request: \n------START REQUEST--------\n" + request
                    + "\n------END REQUEST------\n");

            handleWcs2Request(request, res, req);
        } catch (WCSException e) {
            throw e;
        } catch (PetascopeException e) {
            throw new WCSException(e.getExceptionCode(), e.getMessage());
        } catch (SecoreException e) {
            throw new WCSException(e.getExceptionCode(), e);
        } catch (Exception e) {
            log.error("Runtime error : {}", e.getMessage());
            throw new WCSException(ExceptionCode.RuntimeError, "Runtime error while processing request", e);
        }
    } catch (WCSException e) {
        printError(res, request, e);
    }
    long elapsedTimeMillis = System.currentTimeMillis() - startTime;
    log.debug("Total Petascope Processing Time : " + elapsedTimeMillis);
}

From source file:org.waveprotocol.box.server.robots.dataapi.BaseApiServlet.java

/**
 *  Executes operations.//from w w  w  . j a  v a  2  s  . co  m
 *
 * @param req the request.
 * @param resp the response.
 * @param participant the author for which to perform the robot operations.
 * @throws IOException if encountered errors during writing of a response.
 */
protected final void processOpsRequest(HttpServletRequest req, HttpServletResponse resp,
        ParticipantId participant) throws IOException {
    String apiRequest;
    try {
        // message.readBodyAsString() doesn't work due to a NPE in the OAuth
        // libraries.
        BufferedReader reader = req.getReader();
        apiRequest = reader.readLine();
    } catch (IOException e) {
        LOG.warning("Unable to read the incoming request", e);
        throw e;
    }

    List<OperationRequest> operations;
    if (LOG.isFineLoggable()) {
        LOG.fine("Received the following Json: " + apiRequest);
    }
    try {
        operations = robotSerializer.deserializeOperations(apiRequest);
    } catch (InvalidRequestException e) {
        LOG.info("Unable to parse Json to list of OperationRequests: " + apiRequest);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Unable to parse Json to list of OperationRequests: " + apiRequest);
        return;
    }

    // Create an unbound context.
    ProtocolVersion version = OperationUtil.getProtocolVersion(operations);
    OperationContextImpl context = new OperationContextImpl(waveletProvider,
            converterManager.getEventDataConverter(version), conversationUtil);

    executeOperations(context, operations, participant);
    handleResults(operations, context, resp, version);
}

From source file:com.niroshpg.android.gcm.RegisterServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    logger.warning(" start registering doPost");

    String regId = null;/* ww w . jav a 2 s  .c  om*/
    //String regId = getParameter(req, PARAMETER_REG_ID);
    // logger.warning(" start registering " + regId);

    StringBuffer jb = new StringBuffer();
    logger.warning(" start registering : sb created");
    String line = null;
    try {
        BufferedReader reader = req.getReader();
        logger.warning(" start registering : reader created");
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        /*report an error*/ }

    logger.warning(" start registering : jb append completed");
    JSONObject polygonJsonObject = null;

    Double minMagnitude = MIN_MAGNITUDE_DEFAULT; // default

    try {
        String encodeStr = new String(jb.toString().getBytes(), "UTF-8");
        //logger.warning(" start registering : encodeStr = " + encodeStr );
        String decodeStr = URLDecoder.decode(encodeStr, "UTF-8");
        // logger.warning(" start registering : decodeStr = " + decodeStr );
        JSONObject decodedJsonObj = new JSONObject(decodeStr);

        polygonJsonObject = decodedJsonObj.getJSONObject("polygon");
        Double minM = decodedJsonObj.getDouble("minMagnitude");
        if (minM != null) {
            minMagnitude = minM;
        }

        logger.warning(" start registering : from json regId = " + decodedJsonObj.getString("regId")
                + ", minM = " + minMagnitude);
        regId = decodedJsonObj.getString("regId");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        logger.warning(" start registering :json error : " + e.getMessage());
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        logger.warning(" start registering :encoding error");
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (polygonJsonObject == null) {
        logger.warning(" start registering : could not read json data");
    }

    // Work with the data using methods like...
    // int someInt = jsonObject.getInt("intParamName");
    // String someString = jsonObject.getString("stringParamName");
    // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
    // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
    // etc...
    if (regId != null && regId.length() > 0) {
        Datastore.register(regId, polygonJsonObject, minMagnitude);
    } else {
        logger.warning(" regId not found or invalid");
    }
    setSuccess(resp);
}

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

/**
 * Save the given instance of {@link net.bhira.sample.model.Employee}. It will create a new
 * instance of the employee does not exist, otherwise it will update the existing instance.
 * //from w w  w  .  j ava  2  s  . c om
 * @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 = "/employee", method = RequestMethod.POST)
@ResponseBody
public Callable<String> saveEmployee(HttpServletRequest request, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing POST employee");
                Gson gson = JsonUtil.createGson();
                Employee employee = gson.fromJson(request.getReader(), Employee.class);
                LOG.debug("POST employee received json = {}", gson.toJson(employee));
                employeeService.save(employee);
                HashMap<String, Long> map = new HashMap<String, Long>();
                map.put("id", employee.getId());
                body = gson.toJson(map);
                LOG.debug("POST employee/ successful with return ID = {}", employee.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 employee. {}", body);
                LOG.debug("Save error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.vmware.appfactory.common.base.AbstractController.java

/**
 * Read the body from an HTTP request./*from w  w w  .  jav a  2s.co  m*/
 */
protected String readRequest(HttpServletRequest request) throws IOException {
    StringBuffer sb = new StringBuffer();
    String line;

    /* Read the entire message */
    while ((line = request.getReader().readLine()) != null) {
        sb.append(line);
    }

    String s = sb.toString();
    return s;
}

From source file:org.commonjava.maven.ext.io.rest.handler.AddSuffixJettyHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    LOGGER.info("Handling with AddSuffixJettyHandler: {} {}", request.getMethod(), request.getPathInfo());

    if (target.startsWith(this.endpoint)) {
        // Get Request Body
        StringBuilder jb = new StringBuilder();
        try {//  w w  w . ja  v a  2s. c om
            String line;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                jb.append(line);
            }
        } catch (Exception e) {
            LOGGER.warn("Error reading request body. {}", e.getMessage());
            return;
        }
        LOGGER.info("Read request body '{}' and read parameters '{}'.", jb, request.getParameterMap());

        List<Map<String, Object>> requestBody;
        List<Map<String, Object>> responseBody = new ArrayList<>();

        if (target.equals(DEFAULT_ENDPOINT)) {
            // Protocol analysis
            GAVSchema gavSchema = objectMapper.readValue(jb.toString(), GAVSchema.class);
            requestBody = gavSchema.gavs;

            // Prepare Response
            for (Map<String, Object> gav : requestBody) {
                List<String> availableVersions = new ArrayList<>();

                String version = (String) gav.get("version");
                String bestMatchVersion;

                // Specific to certain integration tests. For the SNAPSHOT test we want to verify it can handle
                // a already built version. The PME code should remove SNAPSHOT before sending it.
                if (((String) gav.get("artifactId")).startsWith("rest-dependency-version-manip-child-module")) {
                    bestMatchVersion = version + "-" + EXTENDED_SUFFIX;
                } else if (((String) gav.get("artifactId")).startsWith("depMgmt2")) {
                    bestMatchVersion = "1.0.0-" + EXTENDED_SUFFIX;
                } else if (((String) gav.get("artifactId"))
                        .startsWith("rest-version-manip-suffix-strip-increment")) {
                    if (version.contains("jbossorg")) {
                        bestMatchVersion = "";
                    } else {
                        bestMatchVersion = version + "." + EXTENDED_SUFFIX;
                    }
                } else {
                    bestMatchVersion = version + "-" + this.suffix;
                }
                LOGGER.info("For GA {}, requesting version {} and got bestMatch {} ", gav, version,
                        bestMatchVersion);

                availableVersions.add(bestMatchVersion);

                gav.put("bestMatchVersion", bestMatchVersion);
                gav.put("whitelisted", false);
                gav.put("blacklisted", false);
                gav.put("availableVersions", availableVersions);

                responseBody.add(gav);
            }
        } else {
            Map<String, Object> gav = new HashMap<>();
            gav.put("groupId", request.getParameter("groupid"));
            gav.put("artifactId", request.getParameter("artifactid"));
            if (isEmpty(blacklistVersion)) {
                gav.put("version", "1.0" + '.' + suffix);
            } else {
                gav.put("version", blacklistVersion);
            }
            responseBody.add(gav);
        }

        // Set Response
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println(objectMapper.writeValueAsString(responseBody));
    } else {
        LOGGER.info(
                "Handling: {} {} with AddSuffixJettyHandler failed,"
                        + " because expected method was {} and endpoint {}",
                request.getMethod(), request.getPathInfo(), this.endpoint);
    }
}