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.scripts.ScriptSingleClient.java

@Override
public Map<String, ScriptRunStatus> getRunsStatus(Boolean local, String group, Integer msTimeout) {
    UBuilder uriBuilder = new UBuilder(SCRIPT_PREFIX_STATUS).setParameters(local, group, msTimeout);
    Request request = Request.Get(uriBuilder.build());
    return commonServiceRequest(request, null, null, MapRunStatusTypeRef, 200);
}

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

@Test
public void testPostCollectionInt() throws Exception {
    try {/*  ww w.j a  v a2 s.co  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);

        URI collectionTmpUriInt = buildURI("/" + dbTmpName + "/" + collectionTmpName,
                new NameValuePair[] { new BasicNameValuePair(DOC_ID_TYPE_KEY, DOC_ID_TYPE.NUMBER.name()) });

        // *** POST tmpcoll
        resp = adminExecutor.execute(Request.Post(collectionTmpUriInt).bodyString("{_id:100, 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();

        //assertTrue("check location header value", location.endsWith("/100?id_type=NUMBER"));
        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());
        assertTrue("check created doc content", content.get("_id").asInt() == 100);
        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);
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}

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

public static <T, G> T get(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Class... responseTypes) {
    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

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

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

    Response resp = null;//  w  w w  .  java2s .  com
    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.qwazr.cluster.client.ClusterSingleClient.java

@Override
public TreeMap<String, ClusterServiceStatusJson.StatusEnum> getServiceMap(String group) {
    UBuilder uriBuilder = new UBuilder("/cluster/services").setParameter("group", group);
    Request request = Request.Get(uriBuilder.build());
    return commonServiceRequest(request, null, null, MapStringStatusEnumTypeRef, 200);
}

From source file:io.gravitee.gateway.standalone.QueryParametersTest.java

@Test
public void call_get_query_accent() throws Exception {
    String query = "poupe";

    URI target = new URIBuilder("http://localhost:8082/test/my_team").addParameter("q", query).build();

    Response response = Request.Get(target).execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(query, responseContent);
}

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

public static <T, G> T get(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Class... responseTypes) {
    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

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

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

    Response resp = null;/*from   www  .j  a v  a 2  s. c o m*/
    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:com.datazuul.iiif.presentation.backend.repository.impl.PresentationRepositoryImpl.java

@Override
public Manifest getManifest(String identifier) throws NotFoundException {
    Manifest manifest = null;// w  w  w. j  a  va  2s.c  o  m

    LOGGER.debug("Try to get manifest for: " + identifier);

    LOGGER.debug("START getManifest() for " + identifier);
    PresentationResolver resolver = getManifestResolver(identifier);
    URI manifestUri = resolver.getURI(identifier);

    String json;
    try {
        if (manifestUri.getScheme().equals("file")) {
            json = IOUtils.toString(manifestUri);
            manifest = objectMapper.readValue(json, Manifest.class);
        } else if (manifestUri.getScheme().equals("classpath")) {
            Resource resource = applicationContext.getResource(manifestUri.toString());
            InputStream is = resource.getInputStream();
            json = IOUtils.toString(is);
            manifest = objectMapper.readValue(json, Manifest.class);
        } else if (manifestUri.getScheme().startsWith("http")) {
            String cacheKey = getCacheKey(identifier);
            manifest = httpCache.getIfPresent(cacheKey);
            if (manifest == null) {
                LOGGER.debug("HTTP Cache miss!");
                json = httpExecutor.execute(Request.Get(manifestUri)).returnContent().asString();
                manifest = objectMapper.readValue(json, Manifest.class);
                httpCache.put(cacheKey, manifest);
            } else {
                LOGGER.debug("HTTP Cache hit!");
            }
        }
    } catch (IOException e) {
        throw new NotFoundException(e);
    }
    LOGGER.debug("DONE getManifest() for " + identifier);

    if (manifest == null) {
        throw new NotFoundException("No manifest for identifier: " + identifier);
    }

    return manifest;
}

From source file:photosharing.api.conx.SearchTagsDefinition.java

/**
 * searches for tags based in the IBM Connections Cloud - Files service, and limit results to documents only
 * /*from w ww. ja v a2 s  .c  o  m*/
 * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void run(HttpServletRequest request, HttpServletResponse response) {

    /**
     * check if query is empty, send SC_PRECONDITION_FAILED 412
     */
    String query = request.getParameter("q");
    if (query == null || query.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
    }

    /**
     * get the users bearer token
     */
    HttpSession session = request.getSession(false);
    OAuth20Data data = (OAuth20Data) session.getAttribute(OAuth20Handler.CREDENTIALS);
    String bearer = data.getAccessToken();

    /**
     * The query should be cleansed before passing it to the backend
     * 
     * Example 
     * http://localhost:9080/photoSharing/api/searchTags?q=s
     * maps to 
     * https://apps.collabservnext.com/files/oauth/api/tags/feed?format=json&scope=document&pageSize=16&filter=a
     * 
     * Response Data
     * {"pageSize":2,"startIndex":1,"hasMore":true,"items":[{"name":"a","weight":482}]}
     */
    Request get = Request.Get(getApiUrl(query));
    get.addHeader("Authorization", "Bearer " + bearer);

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

        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Content is returned
        else if (code == HttpStatus.SC_OK) {
            ServletOutputStream out = response.getOutputStream();
            InputStream in = hr.getEntity().getContent();
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        // Unexpected status
        else {
            JSONObject obj = new JSONObject();
            obj.put("error", "unexpected content");

        }

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

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

    }

}

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

@Override
public Set<String> getIndexes(String schema_name) {
    UBuilder uriBuilder = new UBuilder("/indexes/" + schema_name);
    Request request = Request.Get(uriBuilder.build());
    return commonServiceRequest(request, null, null, SetStringTypeRef, 200);
}

From source file:com.difference.historybook.importer.crawler.Crawler.java

/**
 * Fetch the body for a given HistoryRecord and add it to the record
 * //from w w  w  . j a  v  a 2s.  com
 * @param record HistoryRecord containing a URL to fetch
 * @return
 */
protected static HistoryRecord fetchBody(HistoryRecord record) {
    try {
        Content content = Request.Get(encodeSpecialChars(record.getUrl())).execute().returnContent();
        if (content != null) {
            record.setBody(content.asString(Charsets.UTF_8));
        }
    } catch (IOException e) {
        System.err.println("Failed to fetch " + record.getUrl() + ": " + e.getLocalizedMessage());
    }
    return record;
}