Example usage for org.apache.http.client.fluent Request Get

List of usage examples for org.apache.http.client.fluent Request Get

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request Get.

Prototype

public static Request Get(final String uri) 

Source Link

Usage

From source file:net.bluemix.newsaggregator.api.AuthenticationServlet.java

private User getProfileWithAccessToken(String accessToken) {
    User result = null;/*from  w w w.  j  a va2s .c o  m*/
    String output = null;

    try {
        configureSSL();

        org.apache.http.client.fluent.Request req = Request
                .Get("https://idaas.ng.bluemix.net/idaas/resources/profile.jsp");

        req.addHeader("Authorization", "bearer " + accessToken);

        org.apache.http.client.fluent.Response res = req.execute();

        output = res.returnContent().asString();

        Gson gson = new Gson();
        result = gson.fromJson(output, User.class);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

From source file:api.WebServiceCommand.java

@Override
public CommandStatus execute() {
    CommandStatus status = new CommandStatus();
    try {/*w  w w  .  j a  v a  2 s  .  c  om*/
        switch (this.httpVerb) {
        case "POST":
            status = Request.Post(this.uri).version(this.version).useExpectContinue()
                    .connectTimeout(this.connectionTimeout).socketTimeout(this.socketTimeout)
                    .bodyString(this.postString, this.contentType).execute()
                    .handleResponse(new ResponseHandler<HTTPCommandStatus>() {
                        @Override
                        public HTTPCommandStatus handleResponse(HttpResponse hr)
                                throws ClientProtocolException, IOException {
                            HTTPCommandStatus cs = new HTTPCommandStatus();
                            StatusLine statusLine = hr.getStatusLine();
                            HttpEntity entity = hr.getEntity();
                            cs.setHttpCode(statusLine.getStatusCode());
                            cs.setEntity(entity);
                            cs.setStderr(statusLine.getReasonPhrase());
                            return cs;
                        }
                    });
        case "GET":
        default:
            status = Request.Get(this.uri).version(this.version).connectTimeout(this.connectionTimeout)
                    .socketTimeout(this.socketTimeout).execute()
                    .handleResponse(new ResponseHandler<HTTPCommandStatus>() {
                        @Override
                        public HTTPCommandStatus handleResponse(HttpResponse hr)
                                throws ClientProtocolException, IOException {
                            HTTPCommandStatus cs = new HTTPCommandStatus();
                            StatusLine statusLine = hr.getStatusLine();
                            HttpEntity entity = hr.getEntity();
                            cs.setHttpCode(statusLine.getStatusCode());
                            cs.setEntity(entity);
                            cs.setStderr(statusLine.getReasonPhrase());
                            return cs;
                        }
                    });
            break;
        }
        if (this.debug) {
            System.out.println("   CODE RETURNED: '" + status.getStatus() + "'.");
            System.out.println("CONTOUT RETURNED: '" + status.getStdout() + "'.");
            System.out.println("CONTERR RETURNED: '" + status.getStderr() + "'.");
        }
    } catch (ClientProtocolException ex) {
        status.setEnded(ResponseTypes.CONFIG_ERROR.ordinal());
        System.out.println(ex.getMessage());
    } catch (IOException ex) {
        status.setEnded(ResponseTypes.FAIL.ordinal());
        System.out.println(ex.getMessage());
    }
    return status;
}

From source file:org.eclipse.userstorage.internal.Session.java

public InputStream retrieveBlob(String applicationToken, String key, final Map<String, String> properties,
        final boolean useETag, ICredentialsProvider credentialsProvider) throws IOException {
    URI uri = StringUtil.newURI(service.getServiceURI(), "api/blob/" + applicationToken + "/" + key);

    return new RequestTemplate<InputStream>(uri) {
        @Override/*w  w  w .  j  a  va 2 s.c o m*/
        protected Request prepareRequest() throws IOException {
            Request request = configureRequest(Request.Get(uri), uri);

            if (useETag) {
                String eTag = properties.get(Blob.ETAG);

                if (DEBUG) {
                    System.out.println("Retrieving etag = " + eTag);
                }

                if (!StringUtil.isEmpty(eTag)) {
                    request.setHeader(IF_NONE_MATCH, "\"" + eTag + "\"");
                }
            }

            return request;
        }

        @Override
        protected InputStream handleResponse(HttpResponse response, HttpEntity responseEntity)
                throws IOException {
            int statusCode = getStatusCode("GET", uri, response, OK, NOT_MODIFIED, NOT_FOUND);

            String eTag = getETag(response);
            if (eTag != null) {
                if (DEBUG) {
                    System.out.println("Retrieved etag = " + eTag);
                }

                properties.put(Blob.ETAG, eTag);
            }

            if (statusCode == OK) {
                Map<String, Object> object = JSONUtil.parse(responseEntity.getContent(), "value");
                InputStream stream = (InputStream) object.remove("value");

                for (Map.Entry<String, Object> entry : object.entrySet()) {
                    Object value = entry.getValue();
                    properties.put(entry.getKey(), String.valueOf(value));
                }

                return stream;
            }

            if (statusCode == NOT_MODIFIED) {
                return Blob.NOT_MODIFIED;
            }

            // Blob wasn't found.
            properties.clear();

            StatusLine statusLine = response.getStatusLine();
            throw new NotFoundException("GET", uri, getProtocolVersion(statusLine),
                    statusLine.getReasonPhrase());
        }
    }.send(credentialsProvider);
}

From source file:com.qwazr.search.index.IndexSingleClient.java

@Override
public FieldDefinition getField(String schema_name, String index_name, String field_name) {
    UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/fields/", field_name);
    Request request = Request.Get(uriBuilder.build());
    return commonServiceRequest(request, null, null, FieldDefinition.class, 200);
}

From source file:org.mule.module.http.functional.listener.HttpListenerHttpMessagePropertiesTestCase.java

@Test
public void getWithQueryParamMultipleValues() throws Exception {
    final ImmutableMap<String, Object> queryParams = ImmutableMap.<String, Object>builder()
            .put(QUERY_PARAM_NAME, Arrays.asList(QUERY_PARAM_VALUE, QUERY_PARAM_SECOND_VALUE)).build();
    final String url = String.format("http://localhost:%s/?" + buildQueryString(queryParams),
            listenPort.getNumber());//from w w  w  .ja v  a2  s  . co  m
    Request.Get(url).connectTimeout(RECEIVE_TIMEOUT).execute();
    final MuleMessage message = muleContext.getClient().request("vm://out", RECEIVE_TIMEOUT);
    ParameterMap retrivedQueryParams = message
            .getInboundProperty(HttpConstants.RequestProperties.HTTP_QUERY_PARAMS);
    assertThat(retrivedQueryParams, IsNull.notNullValue());
    assertThat(retrivedQueryParams.size(), is(1));
    assertThat(retrivedQueryParams.get(QUERY_PARAM_NAME), is(QUERY_PARAM_SECOND_VALUE));
    assertThat(retrivedQueryParams.getAll(QUERY_PARAM_NAME).size(), is(2));
    assertThat(retrivedQueryParams.getAll(QUERY_PARAM_NAME),
            Matchers.containsInAnyOrder(new String[] { QUERY_PARAM_VALUE, QUERY_PARAM_SECOND_VALUE }));
}

From source file:com.adobe.acs.commons.http.impl.HttpClientFactoryImpl.java

@Override
public Request get(String partialUrl) {
    String url = baseUrl + partialUrl;
    return Request.Get(url);
}

From source file:org.apache.james.jmap.methods.integration.cucumber.UploadStepdefs.java

@Then("^\"([^\"]*)\" should be able to retrieve the content$")
public void contentShouldBeRetrievable(String username) throws Exception {
    AccessToken accessToken = userStepdefs.tokenByUser.get(username);
    Request request = Request
            .Get(mainStepdefs.baseUri().setPath("/download/" + _1M_ZEROED_FILE_BLOB_ID).build());
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.serialize());
    }/*  w  w  w.jav a2s . c o m*/
    response = request.execute().returnResponse();
    httpAuthorizedStatus();
}

From source file:org.apromore.plugin.deployment.yawl.YAWLDeploymentPluginIntgTest.java

private boolean checkYAWLServerAvailable() {
    try {/*from  w  w  w  . j  a  v  a 2  s .c o m*/
        return Request.Get("http://localhost:8080/yawl/ia").useExpectContinue()
                .addHeader("Accept-Charset", "UTF-8").version(HttpVersion.HTTP_1_1).execute().returnContent()
                .asString().startsWith("<response><failure><reason>");
    } catch (IOException e) {
        return false;
    }
}

From source file:com.amazonaws.sample.entitlement.authorization.FacebookOAuth2AuthorizationHandler.java

/**
 * Fetch profile information via the Facebook graph API and return an Identity object.
 * @param accessToken// www . j  av  a  2s  .  c  o  m
 * @return an Identity object containing the user's email
 * @throws AuthorizationException
 */
@Override
Identity getIdentity(String accessToken) throws AuthorizationException {
    try {
        // exchange the access token for user profile
        ResponseContent r = Request
                .Get("https://graph.facebook.com/v2.3/me?access_token="
                        + URLEncoder.encode(accessToken, "UTF-8"))
                .execute().handleResponse(new AllStatusesContentResponseHandler());

        int statusCode = r.getStatusCode();

        Map<String, Object> m = new ObjectMapper().readValue(r.getContent("{}"), new TypeReference<Object>() {
        });

        if (statusCode == HttpStatus.SC_OK) {
            if (!m.containsKey("email")) {
                throw new RuntimeException("Expected response to include email but it does not.");
            }
            return new Identity(m.get("id").toString(), m.get("email").toString());
        }
        if (statusCode == HttpStatus.SC_BAD_REQUEST) {
            throw new OAuthBadRequestException(buildErrorMessageFromResponse(m, statusCode),
                    AUTHORIZATION_TYPE);
        }
        if (statusCode >= 500) {
            throw new RuntimeException(PROVIDER_NAME + " encountered an error. Status code: " + statusCode);
        }

        throw new RuntimeException(
                "Unanticipated response from " + PROVIDER_NAME + ". Status code: " + statusCode);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}