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.surevine.alfresco.audit.listeners.UpdateDocumentMetadataAuditEventListener.java

@Override
public void setSpecificAuditMetadata(final Auditable auditable, final HttpServletRequest request,
        final JSONObject json, final BufferedHttpServletResponse response) throws JSONException {
    setMetadataFromNodeRef(auditable, nodeRefResolver.getNodeRef(request.getRequestURI()));

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setHeaderEncoding("UTF-8");

    final StringBuilder postContent = new StringBuilder();
    String line;//from w w  w. j  av a  2 s.  c om
    try {
        final BufferedReader br = request.getReader();
        while ((line = br.readLine()) != null) {
            postContent.append(line);
        }
    } catch (final IOException e) {
        logger.error("Failed to update audit record with tags.", e);
    }

    if (postContent.length() > 0) {
        final JSONObject jsonContent = new JSONObject(postContent.toString());

        if (jsonContent.has("prop_cm_taggable")) {
            final String[] tags = jsonContent.getString("prop_cm_taggable").split(",");
            final List<String> tagList = new ArrayList<String>(tags.length);

            final NodeService nodeService = getNodeService();
            for (final String tag : tags) {
                final NodeRef nodeRef = nodeRefResolver.getNodeRefFromGUID(tag);
                final String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);

                tagList.add(name);
            }

            auditable.setTags(StringUtils.join(tagList.iterator(), ","));
        }
    }
}

From source file:org.opendaylight.vtn.webapi.utils.VtnServiceWebUtil.java

/**
 * Prepare request json.//from   w  w w.ja v a  2  s .co m
 * 
 * @param request
 *            the request
 * @param contentType
 *            the content type
 * @return the json object
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws VtnServiceWebAPIException
 *             the vtn service web api exception
 */
public JsonObject prepareRequestJson(final HttpServletRequest request, final String contentType)
        throws IOException, VtnServiceWebAPIException {
    LOG.trace("Start VtnServiceWebUtil#prepareRequestJson()");
    JsonObject serviceRequest = null;
    StringBuilder requestStr = null;
    BufferedReader reader = request.getReader();
    requestStr = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
        requestStr.append(line).append(ApplicationConstants.NEW_LINE);
        line = reader.readLine();
    }
    reader.close();
    /*
     * exceptional case handle for router-creation operation. 
     * POST is allowed with no request body
     */
    if (VtnServiceCommonUtil.getResourceURI(request.getRequestURI()).endsWith(ApplicationConstants.ROUTERS)) {
        requestStr = new StringBuilder();
        requestStr.append(ApplicationConstants.EMPTY_JSON);
    }

    try {
        serviceRequest = DataConverter.getConvertedRequestObject(requestStr.toString(), contentType);
    } catch (ClassCastException e) {
        /*
         * exceptional case handle for tenant-creation operation. POST is
         * allowed with no request body
         */
        if (VtnServiceCommonUtil.getResourceURI(request.getRequestURI())
                .endsWith(ApplicationConstants.TENANTS)) {
            requestStr = new StringBuilder();
            requestStr.append(ApplicationConstants.EMPTY_JSON);
            serviceRequest = DataConverter.getConvertedRequestObject(requestStr.toString(), contentType);
        } else {
            throw e;
        }
    }
    LOG.debug("Request String : " + requestStr.toString());

    LOG.debug("Request Json : " + serviceRequest);
    LOG.trace("Complete VtnServiceWebUtil#prepareRequestJson()");
    return serviceRequest;

}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handleMultiPartPut(HttpServletRequest request, HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, JSONException, NoSuchAlgorithmException {
    String typeHeader = request.getHeader(ProtocolConstants.HEADER_CONTENT_TYPE);
    String boundary = typeHeader.substring(typeHeader.indexOf("boundary=\"") + 10, typeHeader.length() - 1); //$NON-NLS-1$
    BufferedReader requestReader = request.getReader();
    handlePutMetadata(requestReader, boundary, file);
    // next come the headers for the content
    Map<String, String> contentHeaders = new HashMap<String, String>();
    String line;/*from w w  w  . j  a va  2  s. co m*/
    while ((line = requestReader.readLine()) != null && line.length() > 0) {
        String[] header = line.split(":"); //$NON-NLS-1$
        if (header.length == 2)
            contentHeaders.put(header[0], header[1]);
    }
    // now for the file contents
    handlePutContents(request, requestReader, response, file);
}

From source file:org.fao.unredd.portal.ApplicationController.java

private String getRequestBodyAsString(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    StringBuffer body = new StringBuffer();
    String line = null;//from www  .j  ava2s .  c  o  m
    BufferedReader reader;
    try {
        reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            body.append(line);
        }
    } catch (IOException e) { // Error reading response body.
        logger.error(e);
        response.setStatus(ErrorCause.READ_ERROR.status);
        response.getWriter().write(ErrorCause.READ_ERROR.getJson());
    }

    // Validate posted JSON data syntax
    return body.toString();
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.controller.MarketPlacePopulatorController.java

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)//from  w w w .j ava2 s .  c o  m
public void whenPayloadIsStrange(HttpServletRequest request, HttpMessageNotReadableException ex) {

    StringBuilder sb = new StringBuilder("REQUEST PARTS: ");

    LOG.info("************************ JSON ERROR  ************************ ");
    LOG.info("ContentType " + request.getContentType());
    LOG.info("ContentLength " + request.getContentLength());

    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        /*report an error*/ }

    LOG.info("************************ JSON PARSING  ************************ ");
    LOG.info("Payload: " + jb.toString());
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(jb.toString());
        JsonNode actualObj = mapper.readTree(jp);
        LOG.info("JSON OBJECT CREATED: " + actualObj.toString());

        ObjectMapper driverMapper = new ObjectMapper();
        Driver jsonDriver = driverMapper.readValue(actualObj.toString(), Driver.class);

        LOG.info("DRIVER OBJECT CREATED: " + jsonDriver.toString());

    } catch (Exception e) {
        LOG.error("JSON Parsing Exception " + e.getMessage());
    }

}

From source file:org.thingsboard.server.service.security.auth.rest.RestLoginProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }//from   w ww .j  a  v  a 2  s  . co m
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    LoginRequest loginRequest;
    try {
        loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid login request payload");
    }

    if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
        throw new AuthenticationServiceException("Username or Password not provided");
    }

    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, loginRequest.getUsername());

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
            loginRequest.getPassword());

    return this.getAuthenticationManager().authenticate(token);
}

From source file:org.thingsboard.server.service.security.auth.rest.RestPublicLoginProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }/*  ww w  .j  av a2 s.  c o m*/
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    PublicLoginRequest loginRequest;
    try {
        loginRequest = objectMapper.readValue(request.getReader(), PublicLoginRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid public login request payload");
    }

    if (StringUtils.isBlank(loginRequest.getPublicId())) {
        throw new AuthenticationServiceException("Public Id is not provided");
    }

    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, loginRequest.getPublicId());

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "");

    return this.getAuthenticationManager().authenticate(token);
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryServlet.java

/**
 * Perform an HTTP-POST, which corresponds to the basic CRUD operation
 * "create" according to the generic interaction semantics of HTTP REST.
 * <p>//from  w w  w .  j a  v a  2  s . co  m
 * BODY contains the new RDF/XML content
 * if ( body == null ) -> noop 
 * RANGE ignored for POST
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // CREATE
    String body = IOUtils.readString(request.getReader());
    try {
        if (body != null && body.length() > 0) {
            create(body);
        }
        response.setStatus(HttpStatus.SC_OK);
    } catch (Exception ex) {
        ex.printStackTrace();
        response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }

}

From source file:com.mxgraph.online.drive.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 va2 s .  com
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        CredentialMediator cm = getCredentialMediator(req, resp);
        ClientFile clientFile = new ClientFile(req.getReader());
        //user can initiate a Save from logged out tab, we log out the other users to allow saving any unsaved work
        if (clientFile.userId != null
                && !clientFile.userId.equals(req.getSession().getAttribute(CredentialMediator.USER_ID_KEY))) {
            endSession(req, resp, cm);
        }

        Drive service = getDriveService(req, resp, cm);

        File file = clientFile.toFile();

        if (!clientFile.content.equals("")) {
            file = service.files()
                    .insert(file, ByteArrayContent.fromString(clientFile.mimeType, clientFile.content))
                    .execute();

        } else {
            file = service.files().insert(file).execute();
        }

        resp.setContentType(JSON_MIMETYPE);
        resp.getWriter().print(new Gson().toJson(file.getId()).toString());
    } catch (Exception e) {
        resp.setStatus(500);
        if (e instanceof GoogleJsonResponseException) {
            GoogleJsonResponseException e2 = (GoogleJsonResponseException) e;
            resp.setStatus(e2.getStatusCode());
        }
        try {
            resp.getWriter().write(getAuthorizationUrl(req, true));
        } catch (Exception ex) {
            throw new RuntimeException("Failed to redirect for authorization.");
        }
    }
}

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

/**
 * REST CREATE simulation/*from w w  w. j  av  a2  s.  c o m*/
 */
@Override
protected synchronized void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    logRequest(req);
    try {
        // parse posted simulation json object
        JSONObject request = new JSONObject(new JSONTokener(req.getReader()));
        // validate data
        String name = request.getString("name");
        String classname = request.getString("classname");
        String state = request.getString("state");
        int finishTime = request.getInt("finishTime");
        PersistentSimulation sim = sto.createSimulation(name, classname, state, finishTime);
        resp.setStatus(201);
        if (!state.equalsIgnoreCase("GROUP")) {
            // add finishTime as a parameter
            sim.addParameter("finishTime", Integer.toString(finishTime));
        }
        if (request.has("parameters")) {
            JSONObject parameters = request.getJSONObject("parameters");
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = parameters.keys(); iterator.hasNext();) {
                String key = (String) iterator.next();
                sim.addParameter(key, parameters.getString(key));
            }
        }
        // set simulation parent
        if (request.has("parent")) {
            try {
                long parentId = request.getLong("parent");
                PersistentSimulation parent = sto.getSimulationById(parentId);
                if (parent != null)
                    sim.setParentSimulation(parent);
            } catch (JSONException e) {
                // ignore non number parent.
            }
        }

        // clear sim cache
        this.cachedSimulations = null;

        // return created simulation object
        JSONObject response = new JSONObject();
        response.put("success", true);
        response.put("message", "Created simulation");
        response.put("data", simulationToJSON(sim));
        resp.getWriter().write(response.toString());
    } catch (JSONException e) {
        // bad request
        resp.setStatus(400);
        logger.warn("Couldn't create new simulation", e);
    }
}