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:com.qwazr.graph.test.FullTest.java

private boolean nodeExists(int visiteNodeId) throws IOException {
    HttpResponse response = Request.Get(BASE_URL + '/' + TEST_BASE + "/node/v" + visiteNodeId)
            .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
    Assert.assertThat(response.getStatusLine().getStatusCode(), AnyOf.anyOf(Is.is(200), Is.is(404)));
    Assert.assertThat(response.getEntity().getContentType().getValue(),
            Is.is(ContentType.APPLICATION_JSON.toString()));
    return response.getStatusLine().getStatusCode() == 200;
}

From source file:org.n52.youngs.test.ElasticsearchSinkCswMappingIT.java

@Test
public void mapAndStoreFile() throws Exception {
    SourceRecord sourceRecord = SourceRecordHelper
            .getSourceRecordFromFile("records/csw/Record_94bc9c83-97f6-4b40-9eb8-a8e8787a5c63.xml");
    SinkRecord sinkRecord = mapper.map(sourceRecord);

    boolean stored = sink.store(sinkRecord);
    assertThat("record added", stored);

    String response = Request
            .Get("http://localhost:9200/" + mapping.getIndex() + "/" + mapping.getType()
                    + "/_search?pretty&q=*")
            .setHeader("Accept", "application/json").execute().returnContent().asString();
    assertThat(response, containsString("\"total\" : 1"));
    assertThat(response, containsString("urn:uuid:94bc9c83-97f6-4b40-9eb8-a8e8787a5c63"));
    assertThat(response, containsString("xmldoc"));
    assertThat(response, containsString(
            "<dc:subject scheme=\"http://www.digest.org/2.1\">Vegetation-Cropland</dc:subject>"));
}

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

@Test
public void getWithQueryParams() throws Exception {
    final ImmutableMap<String, Object> queryParams = ImmutableMap.<String, Object>builder()
            .put(QUERY_PARAM_NAME, QUERY_PARAM_VALUE).put(SECOND_QUERY_PARAM_NAME, SECOND_QUERY_PARAM_VALUE)
            .build();/*from  w  w  w  .j a  va 2 s  .co  m*/
    final String uri = "/?" + buildQueryString(queryParams);
    final String url = String.format("http://localhost:%s" + uri, listenPort.getNumber());
    Request.Get(url).connectTimeout(RECEIVE_TIMEOUT).execute();
    final MuleMessage message = muleContext.getClient().request("vm://out", RECEIVE_TIMEOUT);
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_REQUEST_URI), is(uri));
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_REQUEST_PATH_PROPERTY),
            is(BASE_PATH));
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_RELATIVE_PATH),
            is(BASE_PATH));
    Map<String, String> retrivedQueryParams = message
            .getInboundProperty(HttpConstants.RequestProperties.HTTP_QUERY_PARAMS);
    assertThat(retrivedQueryParams, IsNull.notNullValue());
    assertThat(retrivedQueryParams.size(), is(2));
    assertThat(retrivedQueryParams.get(QUERY_PARAM_NAME), is(QUERY_PARAM_VALUE));
    assertThat(retrivedQueryParams.get(SECOND_QUERY_PARAM_NAME), is(SECOND_QUERY_PARAM_VALUE));
}

From source file:com.github.piotrkot.resources.CompilerResourceTest.java

/**
 * Appending logs should add them on the server.
 * @throws Exception If something fails.
 *//*  w  w  w.j  ava  2  s .co  m*/
@Test
public void testAppendLogs() throws Exception {
    final String req = "log";
    final String mesg = "message";
    final String uri = String.format("http://localhost:%d/compiler/logs/0",
            CompilerResourceTest.APP_RULE.getLocalPort());
    Assert.assertTrue(HTTP_RESP_OK.contains(
            Request.Delete(uri).setHeader(OK_AUTH).execute().returnResponse().getStatusLine().getStatusCode()));
    Assert.assertTrue(HTTP_RESP_OK
            .contains(Request.Post(uri).setHeader(OK_AUTH).bodyForm(Form.form().add(req, mesg).build())
                    .execute().returnResponse().getStatusLine().getStatusCode()));
    Assert.assertTrue(HTTP_RESP_OK
            .contains(Request.Post(uri).setHeader(OK_AUTH).bodyForm(Form.form().add(req, mesg).build())
                    .execute().returnResponse().getStatusLine().getStatusCode()));
    Assert.assertEquals(Joiner.on(System.lineSeparator()).join(mesg, mesg),
            Request.Get(uri).setHeader(OK_AUTH).execute().returnContent().asString());
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsBinarySyncImpl.java

/**
 * Fetch binary from URL and set into the asset rendition.
 * @param remoteUrl String//from   w  ww. j ava 2  s  . c o  m
 * @param assetRendition Rendition
 * @param asset Asset
 * @param renditionName String
 * @throws FileNotFoundException exception
 */
private void setRenditionOnAsset(String remoteUrl, Rendition assetRendition, Asset asset, String renditionName)
        throws IOException {

    LOG.debug("Syncing from remote asset url: {}", remoteUrl);
    Executor executor = this.remoteAssetsConfig.getRemoteAssetsHttpExecutor();
    try (InputStream inputStream = executor.execute(Request.Get(remoteUrl)).returnContent().asStream()) {
        asset.addRendition(renditionName, inputStream, assetRendition.getMimeType());
    } catch (HttpResponseException fne) {
        if (DamConstants.ORIGINAL_FILE.equals(renditionName) || fne.getStatusCode() != HTTP_NOT_FOUND) {
            throw fne;
        }

        asset.removeRendition(renditionName);
        LOG.warn("Rendition '{}' not found on remote environment. Removing local rendition.", renditionName);
    }
}

From source file:org.kie.smoke.wb.util.RestUtil.java

public static <T, G> T getQuery(URL deploymentUrl, String relativeUrl, String mediaType, int status,
        String user, String password, Map<String, String> queryParams, Class... responseTypes) {
    URIBuilder uriBuilder = null;//from  w  w  w.java  2s  .com
    try {
        String uriStr = createBaseUriString(deploymentUrl, relativeUrl);
        uriBuilder = new URIBuilder(uriStr);
    } catch (URISyntaxException urise) {
        logAndFail("Invalid uri :" + deploymentUrl.toString(), urise);
    }

    for (Entry<String, String> paramEntry : queryParams.entrySet()) {
        uriBuilder.addParameter(paramEntry.getKey(), paramEntry.getValue());
    }

    URI uri = null;
    String uriStr = null;
    try {
        uri = uriBuilder.build();
        uriStr = uri.toString();
    } catch (URISyntaxException urise) {
        logAndFail("Invalid uri!", urise);
    }

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    // @formatter:off
    Request request = Request.Get(uri).addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:off

    Response resp = null;
    try {
        logOp("GET", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        logAndFail("[GET] " + uriStr, e);
    }

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        logAndFail("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:org.kie.remote.tests.base.RestUtil.java

public static <T, G> T getQuery(URL deploymentUrl, String relativeUrl, String mediaType, int status,
        String user, String password, Map<String, String> queryParams, Class... responseTypes) {
    URIBuilder uriBuilder = null;/*from  w ww .j ava2  s.c om*/
    try {
        String uriStr = createBaseUriString(deploymentUrl, relativeUrl);
        uriBuilder = new URIBuilder(uriStr);
    } catch (URISyntaxException urise) {
        failAndLog("Invalid uri :" + deploymentUrl.toString(), urise);
    }

    for (Entry<String, String> paramEntry : queryParams.entrySet()) {
        String param = paramEntry.getKey();
        String value = paramEntry.getValue();
        uriBuilder.addParameter(paramEntry.getKey(), paramEntry.getValue());
    }

    URI uri = null;
    String uriStr = null;
    try {
        uri = uriBuilder.build();
        uriStr = uri.toString();
    } catch (URISyntaxException urise) {
        failAndLog("Invalid uri!", urise);
    }

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    // @formatter:off
    Request request = Request.Get(uri).addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:off

    Response resp = null;
    try {
        logOp("GET", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        failAndLog("[GET] " + uriStr, e);
    }

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        failAndLog("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:com.softinstigate.restheart.integrationtest.GetDBIT.java

private void testGetDb(URI uri) throws Exception {
    Response resp = adminExecutor.execute(Request.Get(uri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);//from w  ww.  j a  v  a  2  s  . c o  m
    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 json not null", json);
    assertNotNull("check not null _created_on property", json.get("_created_on"));
    assertNotNull("check not null _etag property", json.get("_etag"));
    assertNotNull("check not null _lastupdated_on property", json.get("_lastupdated_on"));
    assertNotNull("check not null _db-props-cached property", json.get("_db-props-cached"));
    assertNotNull("check not null _returned property", json.get("_returned"));
    assertNotNull("check not null _size property", json.get("_size"));
    assertNotNull("check not null _total_pages property", json.get("_total_pages"));

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

    assertTrue("check _embedded to be a json object", (json.get("_embedded") instanceof JsonObject));

    JsonObject embedded = (JsonObject) json.get("_embedded");

    assertNotNull("check not null _embedded.rh:coll", embedded.get("rh:coll"));

    assertTrue("check _embedded.rh:coll to be a json array", (embedded.get("rh:coll") instanceof JsonArray));

    JsonArray rhcoll = (JsonArray) embedded.get("rh:coll");

    assertNotNull("check not null _embedded.rh:coll[0]", rhcoll.get(0));

    assertTrue("check _embedded.rh:coll[0] to be a json object", (rhcoll.get(0) instanceof JsonObject));

    JsonObject rhcoll0 = (JsonObject) rhcoll.get(0);

    assertNotNull("check not null _embedded.rh:coll[0]._id", rhcoll0.get("_id"));

    assertNotNull("check not null _embedded.rh:coll[0]._links", rhcoll0.get("_links"));

    assertTrue("check _embedded.rh:coll[0]._links to be a json object",
            (rhcoll0.get("_links") instanceof JsonObject));

    JsonObject rhcoll0Links = (JsonObject) rhcoll0.get("_links");

    assertNotNull("check not null _embedded.rh:coll[0]._links.self", rhcoll0Links.get("self"));

    assertTrue("check _embedded.rh:coll[0]._links.self  to be a json object",
            (rhcoll0Links.get("self") instanceof JsonObject));

    JsonObject rhdb0LinksSelf = (JsonObject) rhcoll0Links.get("self");

    assertNotNull("check not null _embedded.rh:coll[0]._links.self.href", rhdb0LinksSelf.get("href"));

    assertTrue("check _embedded.rh:coll[0]._links.self.href to be a string",
            (rhdb0LinksSelf.get("href").isString()));

    try {
        URI _uri = new URI(rhdb0LinksSelf.get("href").asString());
    } catch (URISyntaxException use) {
        fail("check _embedded.rh:coll[0]._links.self.href to be a valid URI");
    }

    assertNotNull("check not null _link", json.get("_links"));
    assertTrue("check _link to be a json object", (json.get("_links") instanceof JsonObject));

    JsonObject links = (JsonObject) json.get("_links");

    assertNotNull("check not null self", links.get("self"));
    assertNotNull("check not null rh:root", links.get("rh:root"));
    assertNotNull("check not null rh:paging", links.get("rh:paging"));
    assertNotNull("check not null curies", links.get("curies"));
}

From source file:com.qwazr.cluster.client.ClusterSingleClient.java

@Override
public String getActiveNodeMasterByService(String service_name, String group) {
    try {/*from   w ww  .  j a  va  2 s  . c o  m*/
        UBuilder uriBuilder = new UBuilder("/cluster/services/" + service_name + "/active/master")
                .setParameter("group", group);
        Request request = Request.Get(uriBuilder.build());
        HttpResponse response = execute(request, null, null);
        HttpUtils.checkStatusCodes(response, 200);
        return IOUtils.toString(HttpUtils.checkIsEntity(response, ContentType.TEXT_PLAIN).getContent());
    } catch (IOException e) {
        throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.mule.module.oauth2.internal.authorizationcode.functional.AuthorizationCodeMultitenantTestCase.java

private void executeForUserWithAccessToken(String userId, String accessToken, String state) throws IOException {
    wireMockRule.stubFor(get(urlMatching(AUTHORIZE_PATH + ".*")).willReturn(aResponse().withStatus(200)));

    final String expectedState = (state == null ? "" : state) + ":resourceOwnerId=" + userId;

    final ImmutableMap.Builder localAuthorizationUrlParametersBuilder = new ImmutableMap.Builder().put("userId",
            userId);//  w  w w.  j  a  va 2  s . c om
    if (state != NO_STATE) {
        localAuthorizationUrlParametersBuilder.put("state", state);
    }

    Request.Get(localAuthorizationUrl.getValue() + "?"
            + HttpParser.encodeQueryString(localAuthorizationUrlParametersBuilder.build()))
            .connectTimeout(REQUEST_TIMEOUT).socketTimeout(REQUEST_TIMEOUT).execute();

    AuthorizationRequestAsserter.create((findAll(getRequestedFor(urlMatching(AUTHORIZE_PATH + ".*"))).get(0)))
            .assertStateIs(expectedState);

    wireMockRule.stubFor(post(urlEqualTo(TOKEN_PATH))
            .willReturn(aResponse().withBody("{" + "\"" + OAuthConstants.ACCESS_TOKEN_PARAMETER + "\":\""
                    + accessToken + "\"," + "\"" + OAuthConstants.EXPIRES_IN_PARAMETER + "\":" + EXPIRES_IN
                    + "," + "\"" + OAuthConstants.REFRESH_TOKEN_PARAMETER + "\":\"" + REFRESH_TOKEN + "\"}")));

    final String redirectUrlQueryParams = HttpParser.encodeQueryString(
            new ImmutableMap.Builder().put(OAuthConstants.CODE_PARAMETER, AUTHENTICATION_CODE)
                    .put(OAuthConstants.STATE_PARAMETER, expectedState).build());
    Request.Get(redirectUrl.getValue() + "?" + redirectUrlQueryParams).connectTimeout(REQUEST_TIMEOUT)
            .socketTimeout(REQUEST_TIMEOUT).execute();
}