Example usage for org.apache.http.client.methods CloseableHttpResponse getFirstHeader

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getFirstHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getFirstHeader.

Prototype

Header getFirstHeader(String str);

Source Link

Usage

From source file:com.erudika.para.security.FacebookAuthFilter.java

/**
 * Calls the Facebook API to get the user profile using a given access token.
 * @param appid app identifier of the parent app, use null for root app
 * @param accessToken access token/*ww  w .  ja v  a 2s  .co  m*/
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
@SuppressWarnings("unchecked")
public UserAuthentication getOrCreateUser(String appid, String accessToken) throws IOException {
    UserAuthentication userAuth = null;
    if (accessToken != null) {
        User user = new User();
        user.setAppid(appid);
        HttpGet profileGet = new HttpGet(PROFILE_URL + accessToken);
        CloseableHttpResponse resp2 = httpclient.execute(profileGet);
        HttpEntity respEntity = resp2.getEntity();
        String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

        if (respEntity != null && Utils.isJsonType(ctype)) {
            Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

            if (profile != null && profile.containsKey("id")) {
                String fbId = (String) profile.get("id");
                Map<String, Object> pic = (Map<String, Object>) profile.get("picture");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.FB_PREFIX.concat(fbId));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                    //user is new
                    user = new User();
                    user.setActive(true);
                    user.setEmail(StringUtils.isBlank(email) ? fbId + "@facebook.com" : email);
                    user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                    user.setPassword(new UUID().toString());
                    user.setPicture(getPicture(fbId, pic));
                    user.setIdentifier(Config.FB_PREFIX.concat(fbId));
                    String id = user.create();
                    if (id == null) {
                        throw new AuthenticationServiceException(
                                "Authentication failed: cannot create new user.");
                    }
                } else {
                    String picture = getPicture(fbId, pic);
                    if (!StringUtils.equals(user.getPicture(), picture)) {
                        user.setPicture(picture);
                        user.update();
                    }
                }
                userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
            }
            EntityUtils.consumeQuietly(resp2.getEntity());
        }
    }
    return userAuth;
}

From source file:com.erudika.para.security.GoogleAuthFilter.java

/**
 * Calls the Google+ API to get the user profile using a given access token.
 * @param appid app identifier of the parent app, use null for root app
 * @param accessToken access token/*ww  w  . j  ava  2 s. c  o m*/
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
public UserAuthentication getOrCreateUser(String appid, String accessToken) throws IOException {
    UserAuthentication userAuth = null;
    if (accessToken != null) {
        User user = new User();
        user.setAppid(appid);
        HttpGet profileGet = new HttpGet(PROFILE_URL);
        profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        CloseableHttpResponse resp2 = httpclient.execute(profileGet);
        HttpEntity respEntity = resp2.getEntity();
        String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

        if (respEntity != null && Utils.isJsonType(ctype)) {
            Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

            if (profile != null && profile.containsKey("sub")) {
                String googleSubId = (String) profile.get("sub");
                String pic = (String) profile.get("picture");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.GPLUS_PREFIX.concat(googleSubId));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                    //user is new
                    user = new User();
                    user.setActive(true);
                    user.setEmail(StringUtils.isBlank(email) ? googleSubId + "@google.com" : email);
                    user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                    user.setPassword(new UUID().toString());
                    user.setPicture(getPicture(pic));
                    user.setIdentifier(Config.GPLUS_PREFIX.concat(googleSubId));
                    String id = user.create();
                    if (id == null) {
                        throw new AuthenticationServiceException(
                                "Authentication failed: cannot create new user.");
                    }
                } else {
                    String picture = getPicture(pic);
                    if (!StringUtils.equals(user.getPicture(), picture)) {
                        user.setPicture(picture);
                        user.update();
                    }
                }
                userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
            }
            EntityUtils.consumeQuietly(resp2.getEntity());
        }
    }
    return userAuth;
}

From source file:com.erudika.para.security.GitHubAuthFilter.java

/**
 * Calls the GitHub API to get the user profile using a given access token.
 * @param appid app identifier of the parent app, use null for root app
 * @param accessToken access token/*from  w  w w . jav  a  2 s . co m*/
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
public UserAuthentication getOrCreateUser(String appid, String accessToken) throws IOException {
    UserAuthentication userAuth = null;
    if (accessToken != null) {
        User user = new User();
        user.setAppid(appid);
        HttpGet profileGet = new HttpGet(PROFILE_URL);
        profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        profileGet.setHeader(HttpHeaders.ACCEPT, "application/json");
        CloseableHttpResponse resp2 = httpclient.execute(profileGet);
        HttpEntity respEntity = resp2.getEntity();
        String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

        if (respEntity != null && Utils.isJsonType(ctype)) {
            Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

            if (profile != null && profile.containsKey("id")) {
                Integer githubId = (Integer) profile.get("id");
                String pic = (String) profile.get("avatar_url");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.GITHUB_PREFIX + githubId);
                user = User.readUserForIdentifier(user);
                if (user == null) {
                    //user is new
                    user = new User();
                    user.setActive(true);
                    user.setEmail(StringUtils.isBlank(email) ? githubId + "@github.com" : email);
                    user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                    user.setPassword(new UUID().toString());
                    user.setPicture(getPicture(pic));
                    user.setIdentifier(Config.GITHUB_PREFIX + githubId);
                    String id = user.create();
                    if (id == null) {
                        throw new AuthenticationServiceException(
                                "Authentication failed: cannot create new user.");
                    }
                } else {
                    String picture = getPicture(pic);
                    if (!StringUtils.equals(user.getPicture(), picture)) {
                        user.setPicture(picture);
                        user.update();
                    }
                }
                userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
            }
            EntityUtils.consumeQuietly(resp2.getEntity());
        }
    }
    return userAuth;
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Perform any authentication required (Form or Basic) if the previous request did not
 * succeed.//from w w  w. j a v a 2 s.  co m
 * @param response The response from the previous request. It will be consumed if
 * we are going to do authentication (i.e. not returned by this call).
 * @param httpClient The httpClient to use for authentication
 * @param httpContext The current context for use in request. Required.
 * It may be updated with authentication info if necessary.
 * @param serverURI The URI for the server
 * @param userId The user that is performing the request
 * @param password The user's password
 * @param timeout The timeout for the password
 * @param listener The listener should any messages need to be logged. May be
 * <code>null</code>
 * @return The response from the form based auth, or the original request if no auth is required
 * <code>null</code> if the request needs to be repeated (now that the context has been updated).
 * @throws InvalidCredentialsException Thrown if the user's userid or password are invalid.
 * @throws IOException Thrown if anything else goes wrong.
 * @throws GeneralSecurityException 
 */
private static CloseableHttpResponse authenticateIfRequired(CloseableHttpResponse response,
        CloseableHttpClient httpClient, HttpClientContext httpContext, String serverURI, String userId,
        String password, int timeout, TaskListener listener)
        throws InvalidCredentialsException, IOException, GeneralSecurityException {

    // decide what kind of Auth is required if any
    int statusCode = response.getStatusLine().getStatusCode();
    Header formHeader = response.getFirstHeader(FORM_AUTHREQUIRED_HEADER);
    Header basicHeader = response.getFirstHeader(BASIC_AUTHREQUIRED_HEADER);
    if (formHeader != null && FORM_AUTHREQUIRED_HEADER_VALUE.equals(formHeader.getValue())) {
        closeResponse(response);

        // login using Form based auth
        return handleFormBasedChallenge(httpClient, httpContext, serverURI, userId, password, timeout,
                listener);
    }
    if (statusCode == 401 && basicHeader != null) {
        if (JAUTH_PATTERN.matcher(basicHeader.getValue()).matches()) {
            throw new UnsupportedOperationException();

        } else if (BASIC_PATTERN.matcher(basicHeader.getValue()).matches()) {
            closeResponse(response);

            // setup the context to use Basic auth
            handleBasicAuthChallenge(httpContext, serverURI, userId, password, listener);
            return null;
        }
    }
    return response;
}

From source file:org.gradle.caching.http.internal.HttpBuildCacheService.java

private boolean handleRedirect(URI uri, CloseableHttpResponse response, int statusCode, String defaultMessage,
        String action) {//from w ww . j a v a  2s  .c om
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        return throwHttpStatusCodeException(statusCode, defaultMessage);
    }
    try {
        throw new BuildCacheException(String.format(
                "Received unexpected redirect (HTTP %d) to %s when " + action + " '%s'. "
                        + "Ensure the configured URL for the remote build cache is correct.",
                statusCode, safeUri(new URI(locationHeader.getValue())), safeUri(uri)));
    } catch (URISyntaxException e) {
        return throwHttpStatusCodeException(statusCode, defaultMessage);
    }
}

From source file:com.github.patrickianwilson.blogs.testing.induction.integration.JaxRsIntegrationRunner.java

@Test
public void verifyJaxRsGETAndParamsWorkAsAssumed() throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpGet getStatus = new HttpGet("http://localhost:8080/testing?url=http://input.com/long/url");

    CloseableHttpResponse statusResp = client.execute(getStatus);

    Assert.assertThat("Non 200 status response received", statusResp.getStatusLine().getStatusCode(), is(200));
    Assert.assertThat("X-Testing-Orignal-URL header was not present in the response",
            statusResp.getFirstHeader("X-Testing-Orignal-URL").getValue(), is("http://input.com/long/url"));
    Assert.assertThat("Location header was not present in the response",
            statusResp.getFirstHeader("Location").getValue(), is("http://g.og/shortened"));
}

From source file:co.paralleluniverse.fibers.servlet.FiberHttpServletTest.java

@Test
public void testRedirect() throws IOException, InterruptedException, Exception {
    for (int i = 0; i < 10; i++) {
        final HttpGet httpGet = new HttpGet("http://localhost:8080/redirect");
        final CloseableHttpResponse res = HttpClients.custom().disableRedirectHandling().build()
                .execute(httpGet);//from w ww. j a v a2  s  . c o  m
        assertEquals(302, res.getStatusLine().getStatusCode());
        assertTrue(res.getFirstHeader("Location").getValue().endsWith("/foo"));
    }
}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testHttpRedirect() throws IOException, InterruptedException, ExecutionException {
    final HttpGet httpGet = new HttpGet("http://localhost:8080/redirect");
    try (final CloseableHttpClient client = HttpClients.custom().disableRedirectHandling()
            .setDefaultRequestConfig(requestConfig).build()) {
        final CloseableHttpResponse res = client.execute(httpGet);
        final String s = EntityUtils.toString(res.getEntity());
        System.out.println(s);// w w w  .ja va  2 s . c om
        assertEquals(302, res.getStatusLine().getStatusCode());
        assertTrue(res.getFirstHeader("Location").getValue().endsWith("/foo"));
    }
}

From source file:com.cloud.network.nicira.NiciraRestClient.java

private String responseToErrorMessage(final CloseableHttpResponse response) {
    String errorMessage = response.getStatusLine().toString();
    if (response.containsHeader(CONTENT_TYPE)
            && TEXT_HTML_CONTENT_TYPE.equals(response.getFirstHeader(CONTENT_TYPE).getValue())) {
        try {/* w  w w.j ava 2s. co  m*/
            final HttpEntity entity = response.getEntity();
            final String respobnseBody = EntityUtils.toString(entity);
            errorMessage = respobnseBody.subSequence(0, maxResponseErrorMesageLength).toString();
        } catch (final IOException e) {
            s_logger.debug("Could not read repsonse body. Response: " + response, e);
        }
    }

    return errorMessage;
}

From source file:com.xx_dev.apn.proxy.test.TestProxyWithHttpClient.java

private void test(String uri, int exceptCode, String exceptHeaderName, String exceptHeaderValue) {
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(2000);/* w w  w . j  ava  2  s. com*/
    cm.setDefaultMaxPerRoute(40);
    cm.setDefaultConnectionConfig(connectionConfig);

    CloseableHttpClient httpClient = HttpClients.custom()
            .setUserAgent("Mozilla/5.0 xx-dev-web-common httpclient/4.x").setConnectionManager(cm)
            .disableContentCompression().disableCookieManagement().build();

    HttpHost proxy = new HttpHost("127.0.0.1", ApnProxyConfig.getConfig().getPort());

    RequestConfig config = RequestConfig.custom().setProxy(proxy).setExpectContinueEnabled(true)
            .setConnectionRequestTimeout(5000).setConnectTimeout(10000).setSocketTimeout(10000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpGet request = new HttpGet(uri);
    request.setConfig(config);

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(request);

        Assert.assertEquals(exceptCode, httpResponse.getStatusLine().getStatusCode());
        if (StringUtils.isNotBlank(exceptHeaderName) && StringUtils.isNotBlank(exceptHeaderValue)) {
            Assert.assertEquals(exceptHeaderValue, httpResponse.getFirstHeader(exceptHeaderName).getValue());
        }

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseHandler.handleResponse(httpResponse);

        httpResponse.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

}