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:org.restheart.test.integration.PostCollectionIT.java

@Test
public void testPostCollection() throws Exception {
    try {/*from  ww  w. j a  v  a 2 s .  c  o m*/
        Response resp;

        // *** PUT tmpdb
        resp = adminExecutor.execute(Request.Put(dbTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put db", resp, HttpStatus.SC_CREATED);

        // *** PUT tmpcoll
        resp = adminExecutor.execute(Request.Put(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put coll1", resp, HttpStatus.SC_CREATED);

        resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check post coll1", resp, HttpStatus.SC_CREATED);

        // *** POST tmpcoll
        resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        HttpResponse httpResp = check("check post coll1 again", resp, HttpStatus.SC_CREATED);

        Header[] headers = httpResp.getHeaders(Headers.LOCATION_STRING);

        assertNotNull("check loocation header", headers);
        assertTrue("check loocation header", headers.length > 0);

        Header locationH = headers[0];
        String location = locationH.getValue();

        URI createdDocUri = URI.create(location);

        resp = adminExecutor.execute(Request.Get(createdDocUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        JsonObject content = JsonObject.readFrom(resp.returnContent().asString());
        assertNotNull("check created doc content", content.get("_id"));
        assertNotNull("check created doc content", content.get("_etag"));
        assertNotNull("check created doc content", content.get("a"));
        assertTrue("check created doc content", content.get("a").asInt() == 1);

        String _id = content.get("_id").asObject().get("$oid").asString();
        String _etag = content.get("_etag").asObject().get("$oid").asString();

        // try to post with _id without etag
        resp = adminExecutor.execute(
                Request.Post(collectionTmpUri).bodyString("{_id:{\"$oid\":\"" + _id + "\"}, a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check post created doc without etag", resp, HttpStatus.SC_CONFLICT);

        // try to post with wrong etag
        resp = adminExecutor.execute(
                Request.Post(collectionTmpUri).bodyString("{_id:{\"$oid\":\"" + _id + "\"}, a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                        .addHeader(Headers.IF_MATCH_STRING, "pippoetag"));
        check("check put created doc with wrong etag", resp, HttpStatus.SC_PRECONDITION_FAILED);

        // try to post with correct etag
        resp = adminExecutor.execute(
                Request.Post(collectionTmpUri).bodyString("{_id:{\"$oid\":\"" + _id + "\"}, a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                        .addHeader(Headers.IF_MATCH_STRING, _etag));
        check("check post created doc with correct etag", resp, HttpStatus.SC_OK);
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}

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

@Test
public void testPatchCollection() throws Exception {
    try {//from  w  w  w . java 2s.com
        Response resp;

        // *** PUT tmpdb
        resp = adminExecutor.execute(Request.Put(dbTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put db", resp, HttpStatus.SC_CREATED);

        // *** PUT tmpcoll
        resp = adminExecutor.execute(Request.Put(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put coll1", resp, HttpStatus.SC_CREATED);

        // try to patch without body
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));
        check("check patch tmp doc without etag", resp, HttpStatus.SC_NOT_ACCEPTABLE);

        // try to patch without etag
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check patch tmp doc without etag", resp, HttpStatus.SC_CONFLICT);

        // try to patch with wrong etag
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, "pippoetag"));
        check("check patch tmp doc with wrong etag", resp, HttpStatus.SC_PRECONDITION_FAILED);

        resp = adminExecutor.execute(Request.Get(collectionTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        JsonObject content = JsonObject.readFrom(resp.returnContent().asString());

        String etag = content.get("_etag").asString();

        // try to patch with correct etag
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{b:2}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, etag));
        check("check patch tmp doc with correct etag", resp, HttpStatus.SC_OK);

        resp = adminExecutor.execute(Request.Get(collectionTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        content = JsonObject.readFrom(resp.returnContent().asString());
        assertNotNull("check patched content", content.get("a"));
        assertNotNull("check patched content", content.get("b"));
        assertTrue("check patched content", content.get("a").asInt() == 1 && content.get("b").asInt() == 2);
        etag = content.get("_etag").asString();

        // try to patch reserved field name
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{_embedded:\"a\"}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, etag));
        content = JsonObject.readFrom(resp.returnContent().asString());
        assertNotNull("check patched content",
                content.get("_embedded").asObject().get("rh:warnings").asArray());
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}

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

@BeforeClass
public static void storeResourceFunctions() throws IOException {
    executor = Executor.newInstance().auth(TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD)
            .authPreemptive("localhost");

    HttpResponse response = null;//from w  ww. j  av  a2s.  co  m

    response = executor.execute(Request
            .Put(getRestUri() + "/db/system/config" + TEST_COLLECTION + "/"
                    + CollectionConfiguration.DEFAULT_COLLECTION_CONFIG_FILE)
            .bodyString(COLLECTION_CONFIG, ContentType.APPLICATION_XML)).returnResponse();
    assertEquals(HttpStatus.SC_CREATED, response.getStatusLine().getStatusCode());

    response = executor.execute(Request.Put(getRestUri() + TEST_COLLECTION + "/" + XQUERY1_FILENAME)
            .bodyString(XQUERY1, XQUERY_CONTENT_TYPE)).returnResponse();
    assertEquals(HttpStatus.SC_CREATED, response.getStatusLine().getStatusCode());

    response = executor.execute(Request.Get(getRestUri() + "/db/?_query=rest:resource-functions()"))
            .returnResponse();
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    System.out.println(asString(response.getEntity().getContent()));
}

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

@Test
public void testPostCollection() throws Exception {
    try {//w ww.  j  a  v a 2  s  .  c o  m
        Response resp;

        // *** PUT tmpdb
        resp = adminExecutor.execute(Request.Put(dbTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put db", resp, HttpStatus.SC_CREATED);

        // *** PUT tmpcoll
        resp = adminExecutor.execute(Request.Put(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put coll1", resp, HttpStatus.SC_CREATED);

        resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check post coll1", resp, HttpStatus.SC_CREATED);

        // *** POST tmpcoll
        resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        HttpResponse httpResp = check("check post coll1 again", resp, HttpStatus.SC_CREATED);

        Header[] headers = httpResp.getHeaders(Headers.LOCATION_STRING);

        assertNotNull("check loocation header", headers);
        assertTrue("check loocation header", headers.length > 0);

        Header locationH = headers[0];
        String location = locationH.getValue();

        URI createdDocUri = URI.create(location);

        resp = adminExecutor.execute(Request.Get(createdDocUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        JsonObject content = JsonObject.readFrom(resp.returnContent().asString());
        assertNotNull("check created doc content", content.get("_id"));
        assertNotNull("check created doc content", content.get("_etag"));
        assertNotNull("check created doc content", content.get("a"));
        assertTrue("check created doc content", content.get("a").asInt() == 1);

        String _id = content.get("_id").asString();
        String _etag = content.get("_etag").asString();

        // try to post with _id without etag
        resp = adminExecutor
                .execute(Request.Post(collectionTmpUri).bodyString("{_id:\"" + _id + "\", a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check post created doc without etag", resp, HttpStatus.SC_CONFLICT);

        // try to post with wrong etag
        resp = adminExecutor
                .execute(Request.Post(collectionTmpUri).bodyString("{_id:\"" + _id + "\", a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                        .addHeader(Headers.IF_MATCH_STRING, "pippoetag"));
        check("check put created doc with wrong etag", resp, HttpStatus.SC_PRECONDITION_FAILED);

        // try to post with correct etag
        resp = adminExecutor
                .execute(Request.Post(collectionTmpUri).bodyString("{_id:\"" + _id + "\", a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                        .addHeader(Headers.IF_MATCH_STRING, _etag));
        check("check post created doc with correct etag", resp, HttpStatus.SC_OK);
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}

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

@Test
public void get() throws Exception {
    final String url = String.format("http://localhost:%s", 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(BASE_PATH));/*from  w  ww .  j  a v  a  2 s.  c om*/
    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));
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_QUERY_STRING), is(""));
    assertThat(message.getInboundProperty(HttpConstants.RequestProperties.HTTP_URI_PARAMS), notNullValue());
    assertThat(message.<Map>getInboundProperty(HttpConstants.RequestProperties.HTTP_URI_PARAMS).isEmpty(),
            is(true));
    final Map queryParams = message.getInboundProperty(HttpConstants.RequestProperties.HTTP_QUERY_PARAMS);
    assertThat(queryParams, IsNull.notNullValue());
    assertThat(queryParams.size(), is(0));
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_METHOD_PROPERTY),
            is("GET"));
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_VERSION_PROPERTY),
            is(HttpProtocol.HTTP_1_1.asString()));
    assertThat(message.<String>getInboundProperty(HTTP_REMOTE_ADDRESS), is(CoreMatchers.notNullValue()));
}

From source file:net.osten.watermap.batch.FetchPCTWaypointsJob.java

/**
 * Fetch the PCT waypoint files and save in output directory.
 *
 * @see javax.batch.api.Batchlet#process()
 * @return FAILED if the files cannot be downloaded or can't be written to disk; COMPLETED otherwise
 *///from w ww  .j av  a  2  s .  c  om
@Override
public String process() throws Exception {
    outputDir = new File(config.getString("output_dir"));

    if (!outputDir.isDirectory()) {
        log.log(Level.WARNING, "Output directory [{0}] is not a directory.", outputDir);
        return BatchStatus.FAILED.toString();
    } else if (!outputDir.canWrite()) {
        log.log(Level.WARNING, "Output directory [{0}] is not writable.", outputDir);
        return BatchStatus.FAILED.toString();
    }

    for (String url : URLS) {
        log.log(Level.FINE, "Fetching PCT waypoints from {0}", new Object[] { url });

        byte[] response = Request.Get(context.getProperties().getProperty(url)).execute().returnContent()
                .asBytes();
        File outputFile = new File(outputDir.getAbsolutePath() + File.separator + url + "_state_gps.zip");
        FileUtils.writeByteArrayToFile(outputFile, response);

        if (outputFile.exists()) {
            unZipIt(outputFile, outputDir);
        }
    }

    return BatchStatus.COMPLETED.toString();
}

From source file:com.opensearchserver.client.v1.WebCrawlerApi1.java

/**
 * Crawl an URL/*from   w w w .j  av a 2  s  .co  m*/
 * 
 * @param indexName
 *            The name of the index
 * @param url
 *            The URL to crawl
 * @param msTimeOut
 *            The timeout in milliseconds
 * @return the status of the crawl
 * @throws IOException
 *             if any IO error occurs
 * @throws URISyntaxException
 *             if the URI is not valid
 */
public CommonResult crawl(String indexName, String url, Integer msTimeOut)
        throws IOException, URISyntaxException {
    URIBuilder uriBuilder = client.getBaseUrl("index/", indexName, "/crawler/web/crawl")
            .addParameter("url", url).addParameter("returnData", "false");
    Request request = Request.Get(uriBuilder.build());
    return client.execute(request, null, msTimeOut, CommonResult.class, 200);
}

From source file:com.jomp16.google.Google.java

@Override
public void onGenericMessage(GenericMessageEvent event) throws Exception {
    ArrayList<String> args = new ArrayList<>();
    Matcher matcher = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'").matcher(event.getMessage());
    while (matcher.find()) {
        if (matcher.group(1) != null) {
            // Add double-quoted string without the quotes
            args.add(matcher.group(1));/*from   w w w  . j a va2s  .co  m*/
        } else if (matcher.group(2) != null) {
            // Add single-quoted string without the quotes
            args.add(matcher.group(2));
        } else {
            // Add unquoted word
            args.add(matcher.group());
        }
    }
    if (args.get(0).toLowerCase().equals(prefix + "google")) {
        if (args.size() >= 2) {
            String url = String.format(GOOGLE, URLEncoder.encode(args.get(1), "UTF-8"));
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(Request.Get(url).execute().returnContent().asStream()));
            GoogleSearch search = new Gson().fromJson(reader, GoogleSearch.class);

            reader.close();
            if (!search.responseStatus.equals("200")) {
                event.respond(languageManager.getString("Error"));
                return;
            }
            if (search.responseData.results.size() <= 0) {
                event.respond(languageManager.getString("NoResultsFound"));
                return;
            }

            if (args.size() >= 3) {
                for (int i = 0; i < Integer.parseInt(args.get(2)); i++) {
                    String title = StringEscapeUtils
                            .unescapeHtml4(search.responseData.results.get(i).titleNoFormatting);
                    String url2 = URLDecoder.decode(search.responseData.results.get(i).unescapedUrl, "UTF-8");
                    event.respond(languageManager.getString("Result", (i + 1), title, url2));
                }
            } else {
                String title = StringEscapeUtils
                        .unescapeHtml4(search.responseData.results.get(0).titleNoFormatting);
                String url2 = URLDecoder.decode(search.responseData.results.get(0).unescapedUrl, "UTF-8");
                event.respond(languageManager.getString("Result", 1, title, url2));
            }
        } else {
            event.respond(languageManager.getString("CommandSyntax", prefix));
        }
        args.clear();
    }
}

From source file:org.elasticsearch.packaging.util.ServerUtils.java

public static void runElasticsearchTests() throws IOException {
    makeRequest(Request.Post("http://localhost:9200/library/book/1?refresh=true&pretty")
            .bodyString("{ \"title\": \"Book #1\", \"pages\": 123 }", ContentType.APPLICATION_JSON));

    makeRequest(Request.Post("http://localhost:9200/library/book/2?refresh=true&pretty")
            .bodyString("{ \"title\": \"Book #2\", \"pages\": 456 }", ContentType.APPLICATION_JSON));

    String count = makeRequest(Request.Get("http://localhost:9200/_count?pretty"));
    assertThat(count, containsString("\"count\" : 2"));

    makeRequest(Request.Delete("http://localhost:9200/_all"));
}