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:photosharing.api.conx.CommentsDefinition.java

/**
 * get nonce as described with nonce <a href="http://ibm.co/1fG83gY">Get a
 * Cryptographic Key</a>//from w w w  . ja  v a  2  s  .  co  m
 * 
 * @param bearer
 *            the access token
 * @return {String} the nonce
 */
private String getNonce(String bearer, HttpServletResponse response) {
    String nonce = "";

    // Build the Request
    Request get = Request.Get(getNonceUrl());
    get.addHeader("Authorization", "Bearer " + bearer);

    try {
        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(get);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes and if 200, convert to String
         */
        int code = hr.getStatusLine().getStatusCode();

        // Checks the Status Code
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else if (code == HttpStatus.SC_OK) {
            // Default to 200
            InputStream in = hr.getEntity().getContent();
            nonce = IOUtils.toString(in);
        } else {
            // SC_BAD_GATEWAY (503)
            response.setStatus(HttpStatus.SC_BAD_GATEWAY);
        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("Issue with get nonce " + e.toString());
    }

    return nonce;
}

From source file:org.exist.extensions.exquery.restxq.impl.IntegrationTest.java

@Ignore
@Test/*from w  ww  .java 2s  . c  o m*/
public void mediaTypeJson1() throws IOException {
    final HttpResponse response = executor.execute(Request.Get(getRestXqUri() + "/media-type-json1")
            .addHeader(new BasicHeader("Accept", "application/json"))).returnResponse();

    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    assertEquals("<success/>", response.getEntity().toString());
}

From source file:org.restheart.test.integration.GetAggreationIT.java

@Test
public void testGetMapReduceWithVariable() throws Exception {
    String uri = "avg_ages";

    String aggregationsMetadata = "{\"aggrs\": [" + "{" + "\"type\":\"mapReduce\"" + "," + "\"uri\": \"" + uri
            + "\","
            + "\"map\": \"function() { var minage = JSON.parse($vars).minage; if (this.age > minage ) { emit(this.name, this.age); }; }\","
            + "\"reduce\":\"function(key, values) { return Array.avg(values); }\"" + ","
            + "\"query\":{\"name\":{\"$var\":\"name\"}}" + "}]}";

    createTmpCollection();//from www .  j  ava  2 s . com
    createMetadataAndTestData(aggregationsMetadata);

    Response resp;

    URI aggrUri = buildURI(
            "/" + dbTmpName + "/" + collectionTmpName + "/" + RequestContext._AGGREGATIONS + "/" + uri,
            new NameValuePair[] { new BasicNameValuePair("avars", "{\"name\": \"a\", \"minage\": 20}") });

    resp = adminExecutor.execute(Request.Get(aggrUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
        json = JsonObject.readFrom(content);
    } catch (Throwable t) {
        fail("parsing received json");
    }

    assertNotNull("check not null json response", json);
    assertNotNull("check not null _embedded", json.get("_embedded"));
    assertTrue("check _embedded", json.get("_embedded").isObject());

    assertNotNull("", json.get("_embedded").asObject().get("rh:result"));
    assertTrue("check _embedded[\"rh:results\"]", json.get("_embedded").asObject().get("rh:result").isArray());

    JsonArray results = json.get("_embedded").asObject().get("rh:result").asArray();

    assertTrue("check we have 2 results", results.size() == 1);

    results.values().stream().map((v) -> {
        assertNotNull("check not null _id property", v.asObject().get("_id"));
        return v;
    }).map((v) -> {
        assertTrue("check results _id property is string", v.asObject().get("_id").isString());
        return v;
    }).map((v) -> {
        assertTrue("check results _id property is a", v.asObject().get("_id").asString().equals("a"));
        return v;
    }).map((v) -> {
        assertNotNull("check not null value property", v.asObject().get("value"));
        return v;
    }).forEach((v) -> {
        assertTrue("check results value property is number", v.asObject().get("value").isNumber());
    });
}

From source file:org.obm.servlet.filter.qos.util.AsyncServletRequestUtils.java

public Request httpGet() {
    count += 1;
    return Request.Get(serviceUri + "?" + "count=" + count);
}

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

public Map<String, Map<String, Object>> retrieveProperties(final String applicationToken,
        ICredentialsProvider credentialsProvider, int pageSize, int page) throws IOException {
    if (pageSize < 1 || pageSize > 100) {
        throw new IllegalArgumentException("pageSize=" + pageSize);
    }// www  .  j a  va  2 s .co m

    if (page < 1) {
        throw new IllegalArgumentException("page=" + page);
    }

    URI uri = StringUtil.newURI(service.getServiceURI(),
            "api/blob/" + applicationToken + "?pagesize=" + pageSize + "&page=" + page);

    return new RequestTemplate<Map<String, Map<String, Object>>>(uri) {
        @Override
        protected Request prepareRequest() throws IOException {
            return configureRequest(Request.Get(uri), uri);
        }

        @Override
        protected Map<String, Map<String, Object>> handleResponse(HttpResponse response,
                HttpEntity responseEntity) throws IOException {
            getStatusCode("GET", uri, response, OK);
            List<Object> array = JSONUtil.parse(responseEntity.getContent(), null);

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

            for (Object element : array) {
                @SuppressWarnings("unchecked")
                Map<String, Object> map = (Map<String, Object>) element;

                Object appToken = map.remove("application_token");
                if (!applicationToken.equals(appToken)) {
                    StatusLine statusLine = response.getStatusLine();
                    String protocolVersion = statusLine == null ? "HTTP" : getProtocolVersion(statusLine);
                    throw new ProtocolException("GET", uri, protocolVersion, BAD_RESPONSE,
                            "Bad Response : Wrong application token: " + appToken);
                }

                map.remove("url");

                String key = (String) map.remove("key");
                result.put(key, map);
            }

            return result;
        }
    }.send(credentialsProvider);
}

From source file:com.dianping.lion.api.http.SetConfigServlet.java

private void httpSetConfig(String querystr) throws IOException {
    String url = "http://lion-api-ppe01.hm:8080/setconfig?";
    String query = querystr.replace("e=prelease", "e=product");
    url = url + query;// ww w  .  j av  a 2 s . c o m
    Content content = Request.Get(url).execute().returnContent();
    String result = content.asString();
    if (result.startsWith("0|")) {
        logger.info("set config to ppe: " + result);
    } else {
        String message = "failed to set config to ppe: " + result;
        logger.error(message);
        throw new RuntimeException(message);
    }
}

From source file:com.rabidgremlin.legalbeagle.util.HttpHelper.java

private Response executeGet(String requestUrl) throws ClientProtocolException, IOException {
    if (proxy != null) {
        return Request.Get(requestUrl).viaProxy(proxy).execute();
    } else {//ww  w  .ja v a 2  s  .co m
        return Request.Get(requestUrl).execute();
    }
}

From source file:com.m3958.apps.anonymousupload.integration.java.ModuleIntegrationTest.java

public void testGetChinese() throws ClientProtocolException, IOException, URISyntaxException {

    File f = new File("README.md");

    Assert.assertTrue(f.exists());//w w  w  . j a  v  a2s  .co m

    HttpResponse r = Request.Get(new URIBuilder().setScheme("http").setHost("localhost")
            .setPath("/web/chinese.html").setPort(8080).build()).execute().returnResponse();

    String c = CharStreams
            .toString(new InputStreamReader(r.getEntity().getContent(), Charset.forName("UTF-8")));

    container.logger().info(c);

    Assert.assertEquals(15, c.length());
    Assert.assertEquals("", c);
    Assert.assertEquals("text/html; charset=UTF-8", r.getEntity().getContentType().getValue());

    testComplete();

}

From source file:org.restheart.test.integration.SecurityAuthTokenIT.java

@Test
public void testAuthTokenResourceLocation() throws Exception {
    Response resp = adminExecutor.execute(Request.Get(rootUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);//from   w ww.j  a  va  2s.c o m

    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode());

    Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString());
    Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());
    Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString());

    assertNotNull("check not null auth token header", _authToken);
    assertNotNull("check not null auth token valid header", _authTokenValid);
    assertNotNull("check not null auth token location header", _authTokenLocation);

    assertTrue("check not empty array auth token header array ", _authToken.length == 1);
    assertTrue("check not empty array auth token valid header", _authTokenValid.length == 1);
    assertTrue("check not empty array auth token location header", _authTokenLocation.length == 1);

    String locationURI = _authTokenLocation[0].getValue();

    URI authTokenResourceUri = rootUri.resolve(locationURI);

    final String host = CLIENT_HOST;
    final int port = conf.getHttpPort();

    Response resp2 = unauthExecutor.authPreemptive(new HttpHost(host, port, HTTP)).auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Get(authTokenResourceUri));

    HttpResponse httpResp2 = resp2.returnResponse();
    assertNotNull(httpResp2);

    StatusLine statusLine2 = httpResp2.getStatusLine();
    assertNotNull(statusLine2);

    HttpEntity entity = httpResp2.getEntity();
    assertNotNull(entity);

    Header[] _authTokenValid2 = httpResp2.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());

    assertEquals("check auth token resource URI", HttpStatus.SC_OK, statusLine2.getStatusCode());

    assertNotNull("content type not null", entity.getContentType());
    assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("check content of auth token resource", content);

    JsonObject json = null;

    try {
        json = JsonObject.readFrom(content);
    } catch (Throwable t) {
        fail("parsing received json");
    }

    assertNotNull("check content - auth_token not null", json.get("auth_token"));
    assertNotNull("check content - auth_token_valid_until not null", json.get("auth_token_valid_until"));

    assertTrue("check content - auth_token not empty", !json.get("auth_token").asString().isEmpty());
    assertTrue("check content - auth_token_valid_until not empty",
            !json.get("auth_token_valid_until").asString().isEmpty());

    assertEquals(json.get("auth_token").asString(), _authToken[0].getValue());
    assertEquals(json.get("auth_token_valid_until").asString(), _authTokenValid2[0].getValue());
}

From source file:com.qwazr.scripts.ScriptSingleClient.java

@Override
public String getRunErr(String run_id, Boolean local, String group, Integer msTimeout) {
    try {/*  w  w  w.j a  v  a2  s  .  co m*/
        UBuilder uriBuilder = new UBuilder(SCRIPT_PREFIX_STATUS, run_id, "/err").setParameters(local, group,
                msTimeout);
        Request request = Request.Get(uriBuilder.build());
        HttpResponse response = execute(request, null, null);
        return HttpUtils.checkTextPlainEntity(response, 200);
    } catch (HttpResponseEntityException e) {
        throw e.getWebApplicationException();
    } catch (IOException e) {
        throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR);
    }
}