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.performance.LoadGetPT.java

public void getPagesLinearly() throws Exception {
    Integer _page = threadPages.get(Thread.currentThread().getId());

    if (_page == null) {
        threadPages.put(Thread.currentThread().getId(), page);
        _page = page;//  w w w.  j  ava 2 s. c om
    }

    String pagedUrl = url + "?page=" + (_page % 10000);

    _page++;
    threadPages.put(Thread.currentThread().getId(), _page);

    if (printData) {
        System.out.println(Thread.currentThread().getId() + " -> " + pagedUrl);
    }

    Response resp = httpExecutor.execute(Request.Get(new URI(pagedUrl)));

    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());
}

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

@Test
public void responseBuilderIsDifferentFromErrorResponseBuilder() throws Exception {
    final String url = getUrl(responseBuilderAndErrorResponseBuilderNotTheSamePath);
    final Response successfulResponse = Request.Get(url).connectTimeout(100000).socketTimeout(10000000)
            .execute();//  www . j a  va2 s  .c  o m
    assertThat(successfulResponse.returnResponse().getStatusLine().getStatusCode(), is(202));
    final Response failureResponse = Request.Get(url).addHeader("FAIL", "true").connectTimeout(100000)
            .socketTimeout(100000).execute();
    assertThat(failureResponse.returnResponse().getStatusLine().getStatusCode(), is(505));
}

From source file:org.apache.james.jmap.methods.integration.cucumber.DownloadStepdefs.java

private Request authenticatedDownloadRequest(URIBuilder uriBuilder, String blobId, String username)
        throws URISyntaxException {
    AccessToken accessToken = userStepdefs.tokenByUser.get(username);
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    if (attachmentAccessTokens.containsKey(key)) {
        uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    }/*from w ww  .j av  a2s  .  c om*/
    Request request = Request.Get(uriBuilder.build());
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.serialize());
    }
    return request;
}

From source file:org.jboss.arquillian.container.was.wlp_remote_8_5.WLPRestClient.java

/**
 * Queries the rest api for the servers name.
 * /*  w  w  w.  j  a  v  a  2s. c o  m*/
 * @return the name of the running server e.g. defaultServer
 * @throws IOException
 * @throws ClientProtocolException
 */
public String getServerName() throws ClientProtocolException, IOException {
    if (log.isLoggable(Level.FINER)) {
        log.entering(className, "getServerName");
    }

    String restEndpoint = String.format(
            "https://%s:%d%sWebSphere:feature=kernel,name=ServerInfo/attributes/Name",
            configuration.getHostName(), configuration.getHttpsPort(), MBEANS_ENDPOINT);

    String jsonResponse = executor.execute(Request.Get(restEndpoint)).returnContent().asString();
    String serverName = parseJsonResponse(jsonResponse);

    if (log.isLoggable(Level.FINER)) {
        log.exiting(className, "isServerUp");
    }
    return serverName;
}

From source file:eu.eubrazilcc.lvl.oauth2.rest.LinkedInAuthz.java

@GET
@Path("callback")
public Response authorize(final @Context HttpServletRequest request) {
    final String code = parseQuery(request, "code");
    final String state = parseQuery(request, "state");
    final AtomicReference<String> redirectUriRef = new AtomicReference<String>(),
            callbackRef = new AtomicReference<String>();
    if (!LINKEDIN_STATE_DAO.isValid(state, redirectUriRef, callbackRef)) {
        throw new NotAuthorizedException(status(UNAUTHORIZED).build());
    }/*  w w w.  j a va2  s .co m*/
    URI callback_uri = null;
    Map<String, String> map = null;
    try {
        final List<NameValuePair> form = form().add("grant_type", "authorization_code").add("code", code)
                .add("redirect_uri", redirectUriRef.get()).add("client_id", CONFIG_MANAGER.getLinkedInAPIKey())
                .add("client_secret", CONFIG_MANAGER.getLinkedInSecretKey()).build();
        // exchange authorization code for a request token
        final long issuedAt = currentTimeMillis() / 1000l;
        String response = Request.Post("https://www.linkedin.com/uas/oauth2/accessToken")
                .addHeader("Accept", "application/json").bodyForm(form).execute().returnContent().asString();
        map = JSON_MAPPER.readValue(response, new TypeReference<HashMap<String, String>>() {
        });
        final String accessToken = map.get("access_token");
        final long expiresIn = parseLong(map.get("expires_in"));
        checkState(isNotBlank(accessToken), "Uninitialized or invalid access token: " + accessToken);
        checkState(expiresIn > 0l, "Uninitialized or invalid expiresIn: " + expiresIn);
        // retrieve user profile data
        final URIBuilder uriBuilder = new URIBuilder(
                "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,industry,positions,email-address)");
        uriBuilder.addParameter("format", "json");
        response = Request.Get(uriBuilder.build()).addHeader("Authorization", "Bearer " + accessToken).execute()
                .returnContent().asString();
        final LinkedInMapper linkedInMapper = createLinkedInMapper().readObject(response);
        final String userId = linkedInMapper.getUserId();
        final String emailAddress = linkedInMapper.getEmailAddress();
        // register or update user in the database
        final String ownerid = toResourceOwnerId(LINKEDIN_IDENTITY_PROVIDER, userId);
        ResourceOwner owner = RESOURCE_OWNER_DAO.find(ownerid);
        if (owner == null) {
            final User user = User.builder().userid(userId).provider(LINKEDIN_IDENTITY_PROVIDER)
                    .email(emailAddress).password("password").firstname(linkedInMapper.getFirstName())
                    .lastname(linkedInMapper.getLastName()).industry(linkedInMapper.getIndustry().orNull())
                    .positions(linkedInMapper.getPositions().orNull()).roles(newHashSet(USER_ROLE))
                    .permissions(asPermissionSet(userPermissions(ownerid))).build();
            owner = ResourceOwner.builder().user(user).build();
            RESOURCE_OWNER_DAO.insert(owner);
        } else {
            owner.getUser().setEmail(emailAddress);
            owner.getUser().setFirstname(linkedInMapper.getFirstName());
            owner.getUser().setLastname(linkedInMapper.getLastName());
            owner.getUser().setIndustry(linkedInMapper.getIndustry().orNull());
            owner.getUser().setPositions(linkedInMapper.getPositions().orNull());
            RESOURCE_OWNER_DAO.update(owner);
        }
        // register access token in the database
        final AccessToken accessToken2 = AccessToken.builder().token(accessToken).issuedAt(issuedAt)
                .expiresIn(expiresIn).scope(asPermissionList(oauthScope(owner, false))).ownerId(ownerid)
                .build();
        TOKEN_DAO.insert(accessToken2);
        // redirect to default portal endpoint
        callback_uri = new URI(callbackRef.get() + "?email=" + urlEncodeUtf8(emailAddress) + "&access_token="
                + urlEncodeUtf8(accessToken));
    } catch (Exception e) {
        String errorCode = null, message = null, status = null;
        if (e instanceof IllegalStateException && map != null) {
            errorCode = map.get("errorCode");
            message = map.get("message");
            status = map.get("status");
        }
        LOGGER.error("Failed to authorize LinkedIn user [errorCode=" + errorCode + ", status=" + status
                + ", message=" + message + "]", e);
        throw new WebApplicationException(status(INTERNAL_SERVER_ERROR)
                .header("WWW-Authenticate", "Bearer realm='" + RESOURCE_NAME + "', error='invalid-code'")
                .build());
    } finally {
        LINKEDIN_STATE_DAO.delete(state);
    }
    return Response.seeOther(callback_uri).build();
}

From source file:de.elomagic.carafile.client.CaraCloud.java

private FileChangesList getRemoteChangeList(long lastMillis) throws IOException {
    URI uri = CaraFileUtils.buildURI(client.getRegistryURI(), "cloud", "changes", Long.toString(lastMillis));
    HttpResponse response = client.executeRequest(Request.Get(uri)).returnResponse();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("HTTP responce code " + response.getStatusLine().getStatusCode() + " "
                + response.getStatusLine().getReasonPhrase());
    }/* w w w  . ja  va2  s . c  o  m*/

    Charset charset = ContentType.getOrDefault(response.getEntity()).getCharset();

    FileChangesList changeList = JsonUtil
            .read(new InputStreamReader(response.getEntity().getContent(), charset), FileChangesList.class);

    LOG.debug("Folder contains " + changeList.getChangeList() + " item(s)");

    return changeList;
}

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

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

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

    createTmpCollection();//  w w w.j av  a2 s .c om
    createMetadataAndTestData(aggregationsMetadata);

    Response resp;

    URI aggrUri = buildURI(
            "/" + dbTmpName + "/" + collectionTmpName + "/" + RequestContext._AGGREGATIONS + "/" + uri);

    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_BAD_REQUEST, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue());
}

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

@Test
public void testGetCollectionPaging() throws Exception {
    LOG.info("@@@ testGetCollectionPaging URI: " + docsCollectionUriPaging);

    Response resp = adminExecutor.execute(Request.Get(docsCollectionUriPaging));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);//from w  ww. ja  va  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("@@@ Failed parsing received json");
    }

    assertNotNull("check json not null", json);

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

    assertNotNull("check not null _returned property", json.get("_returned"));
    assertNull("check null _size", json.get("_size"));
    assertNull("check null _total_pages", json.get("_total_pages"));

    assertEquals("check _returned value to be 2", 2, json.get("_returned").asInt());

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

    assertNotNull("check not null self", links.get("self"));
    assertNotNull("check not null rh:db", links.get("rh:db"));
    assertNotNull("check not null rh:paging", links.get("rh:paging"));
    assertNotNull("check not null rh:countandpaging", links.get("rh:countandpaging"));
    assertNotNull("check not null rh:filter", links.get("rh:filter"));
    assertNotNull("check not null rh:sort", links.get("rh:filter"));
    assertNotNull("check not null next", links.get("next"));
    assertNotNull("check not null first", links.get("first"));
    assertNull("check null last", links.get("last"));
    assertNull("check null previous", links.get("previous"));

    Response respSelf = adminExecutor.execute(
            Request.Get(docsCollectionUriPaging.resolve(links.get("self").asObject().get("href").asString())));
    HttpResponse httpRespSelf = respSelf.returnResponse();
    assertNotNull(httpRespSelf);

    Response respDb = adminExecutor.execute(
            Request.Get(docsCollectionUriPaging.resolve(links.get("rh:db").asObject().get("href").asString())));
    HttpResponse httpRespDb = respDb.returnResponse();
    assertNotNull(httpRespDb);

    Response respNext = adminExecutor.execute(
            Request.Get(docsCollectionUriPaging.resolve(links.get("next").asObject().get("href").asString())));
    HttpResponse httpRespNext = respNext.returnResponse();
    assertNotNull(httpRespNext);
}

From source file:me.vertretungsplan.parser.LoginHandler.java

private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse)
        throws JSONException, IOException, CredentialInvalidException {
    if (auth == null)
        return null;
    if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) {
        throw new IllegalArgumentException("Wrong authentication type");
    }//from www .j  a  va 2s.c  om

    String login;
    String password;
    if (auth instanceof UserPasswordCredential) {
        login = ((UserPasswordCredential) auth).getUsername();
        password = ((UserPasswordCredential) auth).getPassword();
    } else {
        login = null;
        password = ((PasswordCredential) auth).getPassword();
    }

    JSONObject data = scheduleData.getData();
    JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG);
    String type = loginConfig.optString(PARAM_TYPE, "post");
    switch (type) {
    case "post":
        List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null;
        if (cookieList != null && !needsResponse) {
            for (Cookie cookie : cookieList)
                cookieStore.addCookie(cookie);

            String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
            String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
            if (checkUrl != null && checkText != null) {
                String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                if (!response.contains(checkText)) {
                    return null;
                }
            } else {
                return null;
            }
        }
        executor.clearCookies();
        Document preDoc = null;
        if (loginConfig.has(PARAM_PRE_URL)) {
            String preUrl = loginConfig.getString(PARAM_PRE_URL);
            String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString();
            preDoc = Jsoup.parse(preHtml);
        }

        String postUrl = loginConfig.getString(PARAM_URL);
        JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA);
        List<NameValuePair> nvps = new ArrayList<>();

        String typo3Challenge = null;

        if (loginData.has("_hiddeninputs") && preDoc != null) {
            for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) {
                nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
                if (hidden.attr("name").equals("challenge")) {
                    typo3Challenge = hidden.attr("value");
                }
            }
        }

        for (String name : JSONObject.getNames(loginData)) {
            String value = loginData.getString(name);

            if (name.equals("_hiddeninputs"))
                continue;

            switch (value) {
            case "_login":
                value = login;
                break;
            case "_password":
                value = password;
                break;
            case "_password_md5":
                value = DigestUtils.md5Hex(password);
                break;
            case "_password_md5_typo3":
                value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge);
                break;
            }

            nvps.add(new BasicNameValuePair(name, value));
        }
        Request request = Request.Post(postUrl);
        if (loginConfig.optBoolean("form-data", false)) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (NameValuePair nvp : nvps) {
                builder.addTextBody(nvp.getName(), nvp.getValue());
            }
            request.body(builder.build());
        } else {
            request.bodyForm(nvps, Charset.forName("UTF-8"));
        }
        String html = executor.execute(request).returnContent().asString();
        if (cookieProvider != null)
            cookieProvider.saveCookies(auth, cookieStore.getCookies());

        String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
        String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
        if (checkUrl != null && checkText != null) {
            String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
            if (response.contains(checkText))
                throw new CredentialInvalidException();
        } else if (checkText != null) {
            if (html.contains(checkText))
                throw new CredentialInvalidException();
        }
        return html;
    case "basic":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "ntlm":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password, null, null);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "fixed":
        String loginFixed = loginConfig.optString(PARAM_LOGIN, null);
        String passwordFixed = loginConfig.getString(PARAM_PASSWORD);
        if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) {
            throw new CredentialInvalidException();
        }
        break;
    }
    return null;
}

From source file:org.restheart.test.performance.LoadGetPT.java

public void getPagesRandomly() throws Exception {

    long rpage = Math.round(Math.random() * 10000);

    String pagedUrl = url + "?page=" + rpage;

    //System.out.println(pagedUrl);
    Response resp = httpExecutor.execute(Request.Get(new URI(pagedUrl)));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);//from  ww  w.j av  a2  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());
}