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.jspare.jsdbc.JsdbcTransportImpl.java

@Override
public String execute(DataSource datasource, Credential credential, Optional<Domain> domain, String operation,
        int method, String data) throws JsdbcException {

    if (datasource == null) {

        throw new JsdbcException("DataSource not loaded");
    }/*from  w  ww  . j a v  a2s .  c  o m*/

    try {

        Request request = null;
        org.apache.http.client.fluent.Response response = null;

        String uriAddress = getUrlConnection(datasource, operation,
                Optional.of(domain.orElse(Domain.of(StringUtils.EMPTY)).domain()));
        if (method == RETRIEVE) {
            request = Request.Get(new URIBuilder(uriAddress).build().toString());
        } else if (method == SEND) {
            request = Request.Post(new URIBuilder(uriAddress).build().toString()).bodyString(data,
                    ContentType.APPLICATION_JSON);
        } else {
            throw new JsdbcException("Method called is not mapped");
        }
        request.addHeader(AGENT_KEY, AGENT);

        response = buildAuthentication(request, datasource, credential).execute();

        HttpResponse httpResponse = response.returnResponse();

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {

            if (statusCode == HttpStatus.SC_BAD_REQUEST) {

                throw new JsdbcException("Authorization error, validate your credentials.");
            }
            if (statusCode == HttpStatus.SC_FORBIDDEN) {

                throw new JsdbcException("Forbidden access, validate your user roles.");
            }

            String content = IOUtils.toString(httpResponse.getEntity().getContent());

            ErrorResult result = my(Serializer.class).fromJSON(content, ErrorResult.class);
            throw new CommandFailException(result);
        }

        return IOUtils.toString(httpResponse.getEntity().getContent());

    } catch (Exception e) {

        log.error(e.getMessage(), e);
        throw new JsdbcException("JSDB Server Error");
    }
}

From source file:org.wildfly.swarm.microprofile.jwtauth.ContentTypesTest.java

@RunAsClient
@Test/*w  w w.j  a va  2 s . c  o m*/
public void shouldGetPlainForAllowedUser() throws Exception {
    String response = Request.Get("http://localhost:8080/mpjwt/content-types")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole"))
            .setHeader("Accept", MediaType.TEXT_PLAIN).execute().returnContent().asString();
    Assert.assertEquals(ContentTypesResource.PLAIN_RESPONSE, response);
}

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

/**
 * Fetch the PCT 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
 */// w  ww  .j  ava  2s . co  m
@Override
public String process() throws Exception {
    googleKey = config.getString("GOOGLE_API_KEY");
    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 to {0}", new Object[] { url });
        String response = Request.Get(context.getProperties().getProperty(url) + "?key=" + googleKey).execute()
                .returnContent().asString();
        File outputFile = new File(outputDir.getAbsolutePath() + File.separator + url + ".json");
        FileUtils.writeStringToFile(outputFile, response, Charsets.UTF_8);
    }

    /*
     * curl -o $od/pct-CA-A.json
     * https://sheets.googleapis.com/v4/spreadsheets/1gEyz3bw__aPvNXpqqHcs7KRwmwYrTH2L0DEMW3RbHes/values/Campo%20-%
     * 20Idyllwild!A11:G1000?key=$apik
     * curl -o $od/pct-CA-C.json
     * https://sheets.googleapis.com/v4/spreadsheets/1gEyz3bw__aPvNXpqqHcs7KRwmwYrTH2L0DEMW3RbHes/values/Idyllwild%20-
     * %20Agua%20Dulce!A11:G1000?key=$apik
     * curl -o $od/pct-CA-E.json
     * https://sheets.googleapis.com/v4/spreadsheets/1gEyz3bw__aPvNXpqqHcs7KRwmwYrTH2L0DEMW3RbHes/values/Agua%20Dulce%
     * 20-%20Cottonwood%20Pass!A11:G100?key=$apik
     * curl -o $od/pct-CA-M.json
     * https://sheets.googleapis.com/v4/spreadsheets/1gEyz3bw__aPvNXpqqHcs7KRwmwYrTH2L0DEMW3RbHes/values/Northern%20CA
     * !A9:G1000?key=$apik
     * curl -o $od/pct-OR-B.json
     * https://sheets.googleapis.com/v4/spreadsheets/1gEyz3bw__aPvNXpqqHcs7KRwmwYrTH2L0DEMW3RbHes/values/Oregon!A9:
     * G1000?key=$apik
     * curl -o $od/pct-WA-H.json
     * https://sheets.googleapis.com/v4/spreadsheets/1gEyz3bw__aPvNXpqqHcs7KRwmwYrTH2L0DEMW3RbHes/values/Washington!A9
     * :G1000?key=$apik
     */
    return BatchStatus.COMPLETED.toString();
}

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

/**
 * Fetch the San Gorgonio 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 w  w .  j a va  2s  .c o m*/
@Override
public String process() throws Exception {
    System.out.println("config=" + config);
    System.out.println("context=" + context);
    outputDir = new File(config.getString(WatermapConfig.OUTPUT_DIR));

    // curl -o $od/datafile.txt http://www.howlingduck.com/triterra/gorgonio/datafile.txt
    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 to {0}", new Object[] { url });
        String response = Request.Get(context.getProperties().getProperty(url)).execute().returnContent()
                .asString();
        File outputFile = new File(outputDir.getAbsolutePath() + File.separator + "datafile.txt");
        FileUtils.writeStringToFile(outputFile, response, Charsets.UTF_8);
    }

    return BatchStatus.COMPLETED.toString();
}

From source file:com.seekret.data.flickr.FlickrRequestHandler.java

public Set<PointOfInterest> getPOIsForSpot(Spot spot) {

    Set<PointOfInterest> result = new HashSet<PointOfInterest>();

    HashMap<LatLng, Double> calculateNewPoint = calculateNewPoint(spot);

    List<String> picture_ids = new ArrayList<String>();

    for (Entry<LatLng, Double> entry : calculateNewPoint.entrySet()) {
        int requestedPage = 1;
        int logBarrier = 1;
        int numberPages = 1;
        int maxViewCount = 0;

        LatLng position = entry.getKey();
        double radiusInKm = entry.getValue().doubleValue();
        do {//from  w w  w.  ja va2  s .c o m
            String urlForRequest = buildPhotoRequestURL(requestedPage, position, radiusInKm, LicenseEnum.ALL);

            JsonObject photosObject;

            try {
                if (requestedPage == logBarrier) {
                    logBarrier *= 2;
                    log.log(Level.INFO, "Retrieving all images for spot " + spot + " (page=" + requestedPage
                            + ",numberPages=" + numberPages + ") -> " + urlForRequest);
                }
                String jsonResponse = Request.Get(urlForRequest.toString()).execute().returnContent()
                        .asString();
                requestedPage++;
                photosObject = JsonObject.readFrom(jsonResponse);
                numberPages = handleFlickrPictureResult(result, picture_ids, numberPages, maxViewCount,
                        photosObject);
            } catch (Exception e) {
                log.log(Level.WARNING, "Could not load picture page from flickr", e);
            }
            // We need to make this algorithm more efficient
        } while ((requestedPage < numberPages) && (requestedPage < MAX_NUMBER_PAGES_TO_CRAWL)
                && result.size() < 10000);
        log.log(Level.INFO, "NUMBER OF PICTURES " + picture_ids.size());
    }
    return result;
}

From source file:com.twosigma.beakerx.AutotranslationServiceImpl.java

@Override
public String get(String name) {
    String valueString = "";
    try {/*w  ww  .jav  a 2 s .co  m*/
        valueString = Request.Get(
                LOCALHOST + this.context.getPort() + AUTOTRANSLTION + this.context.getContextId() + "/" + name)
                .addHeader(AUTHORIZATION, auth()).execute().returnContent().asString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return valueString;
}

From source file:aiai.ai.station.actors.DownloadResourceActor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;// w  w w . ja  v  a  2  s  .  c om
    }
    if (!globals.isStationEnabled) {
        return;
    }

    DownloadResourceTask task;
    while ((task = poll()) != null) {
        //            if (Boolean.TRUE.equals(preparedMap.get(task.getId()))) {
        //                continue;
        //            }
        AssetFile assetFile = StationResourceUtils.prepareResourceFile(task.targetDir, task.binaryDataType,
                task.id, null);
        if (assetFile.isError) {
            log.warn("Resource can't be downloaded. Asset file initialization was failed, {}", assetFile);
            continue;
        }
        if (assetFile.isContent) {
            log.info("Resource was already downloaded. Asset file: {}", assetFile.file.getPath());
            //                preparedMap.put(task.getId(), true);
            continue;
        }

        try {
            Request request = Request.Get(targetUrl + '/' + task.getBinaryDataType() + '/' + task.getId())
                    .connectTimeout(5000).socketTimeout(5000);

            Response response;
            if (globals.isSecureRestUrl) {
                response = executor.executor.execute(request);
            } else {
                response = request.execute();
            }
            response.saveContent(assetFile.file);

            //                preparedMap.put(task.getId(), true);
            log.info("Resource #{} was loaded", task.getId());
        } catch (HttpResponseException e) {
            if (e.getStatusCode() == HttpServletResponse.SC_GONE) {
                log.warn("Resource with id {} wasn't found", task.getId());
            } else if (e.getStatusCode() == HttpServletResponse.SC_CONFLICT) {
                log.warn("Resource with id {} is broken and need to be recreated", task.getId());
            } else {
                log.error("HttpResponseException.getStatusCode(): {}", e.getStatusCode());
                log.error("HttpResponseException", e);
            }
        } catch (SocketTimeoutException e) {
            log.error("SocketTimeoutException", e);
        } catch (IOException e) {
            log.error("IOException", e);
        }
    }
}

From source file:org.elasticstore.server.integration.ItemIT.java

@Test
public void testCreateRetrieveAndDeleteItem() throws Exception {
    final Item item = Fixtures.randomItem();
    // create the item
    HttpResponse resp = executor/*from w w w  .j  a va 2 s.c o  m*/
            .execute(Request.Post(serverUrl + "/item").useExpectContinue()
                    .bodyString(mapper.writeValueAsString(item), ContentType.APPLICATION_JSON))
            .returnResponse();

    assertEquals(201, resp.getStatusLine().getStatusCode());

    // retrieve the item
    resp = executor.execute(Request.Get(serverUrl + "/item/" + item.getId()).useExpectContinue())
            .returnResponse();
    assertEquals(200, resp.getStatusLine().getStatusCode());
    final Item fetched = mapper.readValue(resp.getEntity().getContent(), Item.class);
    assertEquals(item.getId(), fetched.getId());
    assertEquals(item.getLabel(), fetched.getLabel());
    assertNotNull(fetched.getCreated());
    assertNotNull(fetched.getLastModified());

    // delete the item
    resp = executor.execute(Request.Delete(serverUrl + "/item/" + item.getId()).useExpectContinue())
            .returnResponse();
    Assert.assertEquals(200, resp.getStatusLine().getStatusCode());

    //retrieve the item again and assert a 404
    resp = executor.execute(Request.Get(serverUrl + "/item/" + item.getId()).useExpectContinue())
            .returnResponse();
    assertEquals(404, resp.getStatusLine().getStatusCode());
}

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

@Test
public void testPutDocument() throws Exception {
    try {/* www  .j av  a2  s  .  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);

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

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

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

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

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

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

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

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

        content = JsonObject.readFrom(resp.returnContent().asString());
        assertNull("check put content", content.get("a"));
        assertNotNull("check put content", content.get("b"));
        assertTrue("check put content", content.get("b").asInt() == 2);
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}

From source file:info.losd.galen.client.ApiClient.java

private Request request(ApiRequest req) {
    switch (req.getMethod()) {
    case GET://from  w w  w .  ja  v  a 2 s .  c  om
        return Request.Get(req.getUrl());
    case POST:
        return Request.Post(req.getUrl());
    default:
        throw new RuntimeException("Unimplemented ApiRequest type");
    }
}