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.wso2.carbon.dataservices.google.tokengen.servlet.TokenEndpoint.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    AuthCode authCode = CodeHolder.getInstance().getAuthCodeForSession(request.getSession().getId());
    String responseMsg = "";
    JSONObject resJson = new JSONObject();
    int responseStatus;
    if (authCode != null) {
        if (log.isDebugEnabled()) {
            log.debug("Request received for retrieve access token from session - "
                    + request.getSession().getId());
        }/*from  w  w w.j  a  va 2 s .  c om*/
        StringBuffer jb = new StringBuffer();
        JSONObject jsonObject;
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                jb.append(line);
            }

            jsonObject = new JSONObject(new JSONTokener(jb.toString()));
            String clientId = jsonObject.getString(DBConstants.GSpread.CLIENT_ID);
            String clientSecret = jsonObject.getString(DBConstants.GSpread.CLIENT_SECRET);
            String redirectURIs = jsonObject.getString(DBConstants.GSpread.REDIRECT_URIS);

            if (clientId == null || clientId.isEmpty()) {
                responseStatus = HttpStatus.SC_BAD_REQUEST;
                responseMsg = "ClientID is null or empty";
            } else if (clientSecret == null || clientSecret.isEmpty()) {
                responseStatus = HttpStatus.SC_BAD_REQUEST;
                responseMsg = "Client Secret is null or empty";
            } else if (redirectURIs == null || redirectURIs.isEmpty()) {
                responseStatus = HttpStatus.SC_BAD_REQUEST;
                responseMsg = "Redirect URIs is null or empty";
            } else {
                HttpTransport httpTransport = new NetHttpTransport();
                JacksonFactory jsonFactory = new JacksonFactory();

                // Step 2: Exchange auth code for tokens
                GoogleTokenResponse googleTokenResponse = new GoogleAuthorizationCodeTokenRequest(httpTransport,
                        jsonFactory, "https://www.googleapis.com/oauth2/v3/token", clientId, clientSecret,
                        authCode.getAuthCode(), redirectURIs).execute();
                resJson.append(DBConstants.GSpread.ACCESS_TOKEN, googleTokenResponse.getAccessToken());
                resJson.append(DBConstants.GSpread.REFRESH_TOKEN, googleTokenResponse.getRefreshToken());
                responseMsg = resJson.toString();
                responseStatus = HttpStatus.SC_OK;
                if (log.isDebugEnabled()) {
                    log.debug("Access token request successfully served for client id " + clientId);
                }
            }
        } catch (JSONException e) {
            responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
            responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage();
            log.error(responseMsg, e);
        } catch (IOException e) {
            responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
            responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage();
            log.error(responseMsg, e);
        } catch (Exception e) {
            responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
            responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage();
            log.error(responseMsg, e);
        }
    } else {
        responseStatus = HttpStatus.SC_ACCEPTED;
        responseMsg = resJson.toString();
    }
    try {
        PrintWriter out = response.getWriter();
        out.println(responseMsg);
        response.setStatus(responseStatus);
    } catch (IOException e) {
        log.error("Error Getting print writer to write http response Error - " + e.getMessage(), e);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as was sent in the
 * given {@link HttpServletRequest}./*from   w  w  w. j  a  v  a2  s  .  c  o m*/
 *
 * @param postMethodProxyRequest    The {@link PostMethod} that we are configuring to send a standard POST request
 * @param httpServletRequest        The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod}
 */
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

        // Replace more completely if destination server is https :
        if (targetSsl) {
            clientUrl = "http://" + clientUrl;
            serverUrl = "https://" + serverUrl;
        }
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace("POST Content Type: {} Encoding: {} Content: {}",
            new Object[] { contentType, encoding, postContent });
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:org.geoserver.opensearch.rest.ProductsController.java

@PutMapping(path = "{product:.+}/metadata", consumes = MediaType.TEXT_XML_VALUE)
public void putCollectionMetadata(@PathVariable(name = "collection", required = true) String collection,
        @PathVariable(name = "product", required = true) String product, HttpServletRequest request)
        throws IOException {
    // check the product exists
    queryProduct(collection, product, q -> {
    });//w  w  w  . j av a  2s .c om

    // TODO: validate it's actual O&M metadata
    String metadata = IOUtils.toString(request.getReader());
    checkWellFormedXML(metadata);

    // prepare the update
    Filter filter = getProductFilter(collection, product);
    runTransactionOnProductStore(
            fs -> fs.modifyFeatures(OpenSearchAccess.METADATA_PROPERTY_NAME, metadata, filter));
}

From source file:org.pentaho.platform.web.servlet.HttpWebService.java

public String getPayloadAsString(final HttpServletRequest request) throws IOException {
    BufferedReader reader = request.getReader();
    StringBuffer stringBuffer = new StringBuffer();
    char[] buffer = new char[2048];
    int b = reader.read(buffer);
    while (b > 0) {
        stringBuffer.append(buffer, 0, b);
    }//from  w w w  .j a v a2s. com
    return stringBuffer.toString();
}

From source file:org.kalypso.ogc.core.service.OGCRequest.java

/**
 * This function initializes the body./*w w w.j a v  a2 s.c  o  m*/
 * 
 * @param request
 *          The servlet request.
 * @return The body.
 */
private String initBody(final HttpServletRequest request) {
    /* The reader. */
    BufferedReader reader = null;

    try {
        /* If the request was not sent via the POST method, no body is available. */
        if (!m_post)
            return null;

        /* Only xml bodies may be handled. */
        final String contentType = request.getContentType();
        if (contentType == null || !contentType.contains("text/xml")) //$NON-NLS-1$
            return null;

        /* Memory for the results. */
        final StringBuffer buffer = new StringBuffer();

        /* Get the reader. */
        reader = request.getReader();

        /* Read the body. */
        String line = ""; //$NON-NLS-1$
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append(System.getProperty("line.separator", "\n\r")); //$NON-NLS-1$ //$NON-NLS-2$
        }

        return buffer.toString();
    } catch (final IOException ex) {
        /* Print the exception. */
        ex.printStackTrace();
        return null;
    } finally {
        /* Close the reader. */
        IOUtils.closeQuietly(reader);
    }
}

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

/**
 * REST UPDATE simulation//from   ww w .  j  ava2  s. c om
 */
@Override
protected synchronized void doPut(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    logRequest(req);
    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()));
            // validate fields
            if (Integer.parseInt(input.get("id").toString()) != simId || input.getString("state").length() < 1
                    || input.getInt("currentTime") < 0 || input.getInt("finishTime") < 0) {
                resp.setStatus(400);
                return;
            }

            PersistentSimulation sim = sto.getSimulationById(simId);
            String state = input.getString("state");
            if (!(sim.getState().equals(state))) {
                sim.setState(state);
            }
            int currentTime = input.getInt("currentTime");
            if (!(sim.getCurrentTime() == currentTime)) {
                sim.setCurrentTime(currentTime);
            }
            int finishTime = input.getInt("finishTime");
            if (!(sim.getFinishTime() == finishTime)) {
                sim.setCurrentTime(finishTime);
            }
            JSONObject parameters = input.getJSONObject("parameters");
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = parameters.keys(); iterator.hasNext();) {
                String key = (String) iterator.next();
                sim.addParameter(key, parameters.getString(key));
            }
            // parent simulation
            try {
                long parentId = input.getLong("parent");
                PersistentSimulation parent = sim.getParentSimulation();
                if (parentId == 0 && parent != null) {
                    sim.setParentSimulation(null);
                } else if (parentId > 0 && parent.getID() != parentId) {
                    parent = sto.getSimulationById(parentId);
                    if (parent != null) {
                        sim.setParentSimulation(parent);
                    }
                }
            } catch (JSONException e) {
            }

            JSONObject response = new JSONObject();
            response.put("success", true);
            response.put("data", simulationToJSON(sim));
            resp.getWriter().write(response.toString());
            // clear sim cache
            this.cachedSimulations = null;
        } catch (JSONException e) {
            resp.setStatus(400);
        }
    } else {
        resp.setStatus(400);
    }
}

From source file:com.example.cloud.bigtable.helloworld.JsonServlet.java

/**
 * doPost() - for a given row, get all values from a simple JSON request.
 * (basically a simple map<key,v>)
 *
 * Column Family CF1 is well known and will be what we add columns to that don't have a ':' column
 * prefix.  If you specify a column family, it should have been created as we aren't creating them
 * here./*from  w ww . j  a  v a  2s.  c om*/
 *
 * Bigtable (and hbase) fields are basically blobs, so I've chosen to recognize a few "datatypes"
 * bool is defined as 1 byte (either 0x00 / 0x01) for (false / true)
 * counter (long) 64 bits 8 bytes and the first 4 bytes are either 0 or -128
 * doubles we will keep as text in Bigtable / hbase
 *
 * Since we are in a managed VM, we could use a bufferedMutator
 **/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();

    if (path.length() < 5) {
        log("doPost-bad length-" + path.length());
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // IMPORTANT - This try() is a java7 try w/ resources which will close() the table at the end.
    try (Table t = BigtableHelper.getConnection().getTable(TABLE)) {
        JSONObject json = new JSONObject(new JSONTokener(req.getReader()));
        String[] names = JSONObject.getNames(json);

        Put p = new Put(Bytes.toBytes(path.substring(1)));
        for (String key : names) {
            byte[] col = CF1;
            String[] k = key.split(":"); // Some other column family?
            if (k.length > 1) {
                col = Bytes.toBytes(k[0]);
                key = k[1];
            }
            Object o = json.opt(key);
            if (o == null) {
                continue; // skip null's for Bigtable / hbase
            }
            switch (o.getClass().getSimpleName()) {
            case "Boolean":
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes((boolean) o));
                break;

            case "String":
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes((String) o));
                break;

            case "Double": // Store as Strings
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes(o.toString()));
                break;

            case "Long":
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes((long) o));
                break;
            case "Integer":
                long x = ((Integer) o);
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes(x));
                break;
            }
        }
        t.put(p);
    } catch (Exception io) {
        log("Json", io);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:net.lr.jmsbridge.BridgeServlet.java

/**
 * Forward HTTP request to a jms queue and listen on a temporary queue for the reply.
 * Connects to the jms server by using the username and password from the HTTP basic auth.
 *//*from www.  j  a v a  2s  .c om*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        resp.setHeader("WWW-Authenticate", "Basic realm=\"Bridge\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "auth");
        return;
    }
    UserNameAndPassword auth = extractUserNamePassword(authHeader);
    PrintStream out = new PrintStream(resp.getOutputStream());
    String contextPath = req.getContextPath();
    String uri = req.getRequestURI();
    String queueName = uri.substring(contextPath.length() + 1);
    final StringBuffer reqContent = retrieveRequestContent(req.getReader());

    ConnectionFactory cf = connectionPool.getConnectionFactory(auth);
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(10000);
    final Destination replyDest = connectionPool.getReplyDestination(cf, auth);
    jmsTemplate.send(queueName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(reqContent.toString());
            message.setJMSReplyTo(replyDest);
            return message;
        }

    });
    Message replyMsg = jmsTemplate.receive(replyDest);
    if (replyMsg instanceof TextMessage) {
        TextMessage replyTMessage = (TextMessage) replyMsg;
        try {
            out.print(replyTMessage.getText());
        } catch (JMSException e) {
            JmsUtils.convertJmsAccessException(e);
        }
    }
}

From source file:org.wso2.carbon.identity.oauth.dcr.factory.RegistrationRequestFactory.java

@Override
public void create(IdentityRequest.IdentityRequestBuilder builder, HttpServletRequest request,
        HttpServletResponse response) throws FrameworkClientException {

    RegistrationRequest.RegistrationRequestBuilder registerRequestBuilder = null;
    if (builder instanceof RegistrationRequest.RegistrationRequestBuilder) {
        registerRequestBuilder = (RegistrationRequest.RegistrationRequestBuilder) builder;
        super.create(registerRequestBuilder, request, response);
        try {//from  w  w  w .  j  a v  a  2  s.  c o m
            Reader requestBodyReader = request.getReader();
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonData = (JSONObject) jsonParser.parse(requestBodyReader);
            if (log.isDebugEnabled()) {
                log.debug("DCR request json : " + jsonData.toJSONString());
            }

            RegistrationRequestProfile registrationRequestProfile = registerRequestBuilder
                    .getRegistrationRequestProfile();
            if (registrationRequestProfile == null) {
                registrationRequestProfile = new RegistrationRequestProfile();
            }

            Object obj = jsonData.get(RegistrationRequest.RegisterRequestConstant.GRANT_TYPES);
            if (obj instanceof JSONArray) {
                JSONArray grantTypes = (JSONArray) obj;
                for (Object grantType : grantTypes) {
                    if (grantType instanceof String && IdentityUtil.isNotBlank((String) grantType)) {
                        registrationRequestProfile.getGrantTypes().add((String) grantType);
                    }
                }
            } else if (obj instanceof String) {
                String grantType = (String) obj;
                if (IdentityUtil.isNotBlank(grantType)) {
                    registrationRequestProfile.getGrantTypes().add(grantType);
                }
            }

            obj = jsonData.get(RegistrationRequest.RegisterRequestConstant.REDIRECT_URIS);
            if (obj instanceof JSONArray) {
                JSONArray redirectUris = (JSONArray) obj;
                for (Object redirectUri : redirectUris) {
                    if (redirectUri instanceof String) {
                        registrationRequestProfile.getRedirectUris().add((String) redirectUri);
                    }
                }
            } else if (obj instanceof String) {
                registrationRequestProfile.getRedirectUris().add((String) obj);

            } else if (registrationRequestProfile.getGrantTypes()
                    .contains(DCRConstants.GrantTypes.AUTHORIZATION_CODE)
                    || registrationRequestProfile.getGrantTypes().contains(DCRConstants.GrantTypes.IMPLICIT)) {
                throw IdentityException.error(FrameworkClientException.class,
                        "RedirectUris property must have at least one URI value.");
            }

            registrationRequestProfile.setTokenEndpointAuthMethod((String) jsonData
                    .get(RegistrationRequest.RegisterRequestConstant.TOKEN_ENDPOINT_AUTH_METHOD));

            obj = jsonData.get(RegistrationRequest.RegisterRequestConstant.RESPONSE_TYPES);
            if (obj instanceof JSONArray) {
                JSONArray redirectUris = (JSONArray) obj;
                for (int i = 0; i < redirectUris.size(); i++) {
                    registrationRequestProfile.getResponseTypes().add(redirectUris.get(i).toString());
                }
            } else if (obj instanceof String) {
                registrationRequestProfile.getResponseTypes().add((String) obj);
            }

            // Get client Name if not available generate a uuid
            Object objClient = jsonData.get(RegistrationRequest.RegisterRequestConstant.CLIENT_NAME);
            if (objClient != null) {
                registrationRequestProfile.setClientName((String) objClient);
            } else {
                registrationRequestProfile.setClientName(UUIDGenerator.generateUUID());
            }

            registrationRequestProfile.setClientUri(
                    (String) jsonData.get(RegistrationRequest.RegisterRequestConstant.CLIENT_URI));
            registrationRequestProfile
                    .setLogoUri((String) jsonData.get(RegistrationRequest.RegisterRequestConstant.LOGO_URI));

            obj = jsonData.get(RegistrationRequest.RegisterRequestConstant.SCOPE);
            if (obj instanceof JSONArray) {
                JSONArray redirectUris = (JSONArray) obj;
                for (int i = 0; i < redirectUris.size(); i++) {
                    registrationRequestProfile.getScopes().add(redirectUris.get(i).toString());
                }
            } else if (obj instanceof String) {
                registrationRequestProfile.getScopes().add((String) obj);
            }

            obj = jsonData.get(RegistrationRequest.RegisterRequestConstant.CONTACTS);
            if (obj instanceof JSONArray) {
                JSONArray redirectUris = (JSONArray) obj;
                for (int i = 0; i < redirectUris.size(); i++) {
                    registrationRequestProfile.getContacts().add(redirectUris.get(i).toString());
                }
            } else if (obj instanceof String) {
                registrationRequestProfile.getContacts().add((String) obj);
            }

            registrationRequestProfile
                    .setTosUri((String) jsonData.get(RegistrationRequest.RegisterRequestConstant.TOS_URI));
            registrationRequestProfile.setPolicyUri(
                    (String) jsonData.get(RegistrationRequest.RegisterRequestConstant.POLICY_URI));
            registrationRequestProfile
                    .setJwksUri((String) jsonData.get(RegistrationRequest.RegisterRequestConstant.JWKS_URI));
            registrationRequestProfile
                    .setJkws((String) jsonData.get(RegistrationRequest.RegisterRequestConstant.JWKS));
            registrationRequestProfile.setSoftwareId(
                    (String) jsonData.get(RegistrationRequest.RegisterRequestConstant.SOFTWARE_ID));
            registrationRequestProfile.setSoftwareVersion(
                    (String) jsonData.get(RegistrationRequest.RegisterRequestConstant.SOFTWARE_VERSION));

            //TODO:This parameter is a custom one and we have to remove if we can collect the user name by having
            // some authentication mechanism.
            String username = CarbonContext.getThreadLocalCarbonContext().getUsername();
            if (StringUtils.isBlank(username)) {
                Object objOwner = jsonData.get(RegistrationRequest.RegisterRequestConstant.EXT_PARAM_OWNER);
                if (objOwner != null) {
                    username = (String) objOwner;
                    try {
                        UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
                        if (!userRealm.getUserStoreManager().isExistingUser(username)) {
                            throw IdentityException.error(FrameworkClientException.class,
                                    "Invalid application " + "owner.");
                        }
                    } catch (UserStoreException e) {
                        String errorMessage = "Invalid application owner, " + e.getMessage();
                        throw IdentityException.error(FrameworkClientException.class, errorMessage, e);
                    }
                } else {
                    throw IdentityException.error(FrameworkClientException.class, "Invalid application owner.");
                }
            }
            registrationRequestProfile.setOwner(username);
            registerRequestBuilder.setRegistrationRequestProfile(registrationRequestProfile);

        } catch (IOException e) {
            String errorMessage = "Error occurred while reading servlet request body, " + e.getMessage();
            FrameworkClientException.error(errorMessage, e);
        } catch (ParseException e) {
            String errorMessage = "Error occurred while parsing the json object, " + e.getMessage();
            FrameworkClientException.error(errorMessage, e);
        }
    }
}

From source file:servlets.Install_servlets.java

private void autoInstallPostHandler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   www.j a v  a 2 s .  c  o m*/
        JsonObject settings = readDockerEnvParams();

        JsonObject requestData = (JsonObject) new JsonParser().parse(request.getReader());
        settings.addProperty("installation_type", requestData.get("installation_type").getAsString());
        Thread.sleep(5000); //Wait for MySQL docker to start
        response = install(settings, response);
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Install_servlets.class.getName(), "userLoginPostHandler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}