Example usage for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy

List of usage examples for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy.

Prototype

LaxRedirectStrategy

Source Link

Usage

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

/**
 * Same as sendHttpGet above, except that we return the HttpClient so that it can
 * subsequently be re-used (for e.g. logout)
 */// ww  w  .  ja v a  2  s. c o  m
public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password,
        int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", idpPort),
            new UsernamePasswordCredentials(user, password));

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
    try {
        trustStore.load(instream, "clientpass".toCharArray());
    } finally {
        try {
            instream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
    sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

    SSLContext sslContext = sslContextBuilder.build();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

    httpClient = httpClientBuilder.build();

    HttpGet httpget = new HttpGet(url);

    HttpResponse response = httpClient.execute(httpget);
    HttpEntity entity = response.getEntity();

    Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        return null;
    }

    //            Redirect to a POST is not supported without user interaction
    //            http://www.ietf.org/rfc/rfc2616.txt
    //            If the 301 status code is received in response to a request other
    //            than GET or HEAD, the user agent MUST NOT automatically redirect the
    //            request unless it can be confirmed by the user, since this might
    //            change the conditions under which the request was issued.

    Source source = new Source(EntityUtils.toString(entity));
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    FormFields formFields = source.getFormFields();

    List<Element> forms = source.getAllElements(HTMLElementName.FORM);
    Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
    String postUrl = forms.get(0).getAttributeValue("action");

    Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
    Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

    for (FormField formField : formFields) {
        if (formField.getUserValueCount() != 0) {
            nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
        }
    }
    HttpPost httppost = new HttpPost(postUrl);
    httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

    response = httpClient.execute(httppost);

    entity = response.getEntity();
    Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

    String responseStr = EntityUtils.toString(entity);
    Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0);

    return httpClient;
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    OkHttpClient c = new OkHttpClient();
    c.setFollowRedirects(true);//  w  w w .  j a va  2  s . c o m
    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    c.setCookieHandler(cookieManager);

    c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider,
                authData);
    }

    return client;
}

From source file:gov.medicaid.screening.dao.impl.ChiropracticLicenseDAOBean.java

/**
 * Performs a search for all possible results.
 * /*  w  w  w  .  j a v a2s.  c  om*/
 * @param criteria
 *            The search criteria.
 * @param searchType
 *            the type of search to execute.
 * @return the search result for licenses
 * 
 * @throws URISyntaxException
 *             if an error occurs while building the URL.
 * @throws ClientProtocolException
 *             if client does not support protocol used.
 * @throws IOException
 *             if an error occurs while parsing response.
 * @throws ParseException
 *             if an error occurs while parsing response.
 * @throws ServiceException
 *             for any other problems encountered
 */
private SearchResult<License> getAllResults(ChiropracticLicenseSearchCriteria criteria, String searchType)
        throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());

    URIBuilder uriBuilder = new URIBuilder(getSearchURL());
    uriBuilder.addParameter("strName", Util.defaultString(criteria.getLastName()));
    uriBuilder.addParameter("strSoundex", Util.defaultString(criteria.getLastName()));
    uriBuilder.addParameter("strCity", Util.defaultString(criteria.getCity()));
    uriBuilder.addParameter("strZIP", Util.defaultString(criteria.getZipCode()));
    uriBuilder.addParameter(searchType, TYPES.get(searchType));

    HttpGet search = new HttpGet(uriBuilder.build());
    HttpResponse response = client.execute(search);
    verifyAndAuditCall(getSearchURL(), response);

    Document page = Jsoup.parse(EntityUtils.toString(response.getEntity()));
    List<License> allLicenses = new ArrayList<License>();

    Elements rows = page.select("tr:gt(0)");
    for (Element row : rows) {
        String href = row.select("a").first().attr("href"); // detail link
        String licenseType = row.select("td:eq(2)").text();

        HttpGet getDetails = new HttpGet(Util.replaceLastURLPart(uriBuilder.build().toString(), href));
        response = client.execute(getDetails);
        verifyAndAuditCall(getSearchURL(), response);

        page = Jsoup.parse(EntityUtils.toString(response.getEntity()));
        allLicenses.add(parseLicense(page, licenseType));
    }

    SearchResult<License> searchResult = new SearchResult<License>();
    searchResult.setItems(allLicenses);
    return searchResult;
}

From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java

public static String sendHttpGet(String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort)
        throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*  w  ww .j  a  v  a 2  s .co m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Authorization", "Negotiate " + ticket);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:com.microsoft.windowsazure.management.configuration.ManagementConfiguration.java

/**
 * Creates a service management configuration with specified parameters.
 *
 * @param profile            A <code>String</code> object that represents the profile.
 * @param configuration            A previously instantiated <code>Configuration</code> object.
 * @param uri            A <code>URI</code> object that represents the URI of the
 *            service end point./*  w  w  w  .  j  a  v  a 2 s.c o  m*/
 * @param subscriptionId            A <code>String</code> object that represents the subscription
 *            ID.
 *            the keystore.
 * @param token          The authentication token
 * @return A <code>Configuration</code> object that can be used when
 *         creating an instance of the <code>ManagementContract</code>
 *         class.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static Configuration configure(String profile, Configuration configuration, URI uri,
        String subscriptionId, String token) throws IOException {

    if (profile == null) {
        profile = "";
    } else if (profile.length() != 0 && !profile.endsWith(".")) {
        profile = profile + ".";
    }

    configuration.setProperty(profile + SUBSCRIPTION_ID, subscriptionId);

    configuration.setProperty(profile + SUBSCRIPTION_CLOUD_CREDENTIALS,
            new TokenCloudCredentials(uri, subscriptionId, token));

    configuration.setProperty(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY,
            new LaxRedirectStrategy());

    return configuration;
}

From source file:gov.medicaid.screening.dao.impl.ChiropracticLicenseDAOBean.java

/**
 * Retrieves all the practioners from the disciplined list.
 * //  w  w  w .  j ava 2 s  . com
 * @return the list of practitioners in the disciplined list
 * 
 * @throws URISyntaxException
 *             if an error occurs while building the URL.
 * @throws ClientProtocolException
 *             if client does not support protocol used.
 * @throws IOException
 *             if an error occurs while parsing response.
 * @throws ParseException
 *             if an error occurs while parsing response.
 * @throws ServiceException
 *             for any other problems encountered
 */
private SearchResult<License> getAllDisciplinedResults()
        throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());

    HttpGet search = new HttpGet(new URIBuilder(getDisciplineURL()).build());
    HttpResponse response = client.execute(search);
    verifyAndAuditCall(getDisciplineURL(), response);

    Document page = Jsoup.parse(EntityUtils.toString(response.getEntity()));
    List<License> allLicenses = new ArrayList<License>();

    Elements rows = page.select("blockquote table tr:gt(0)");
    for (Element row : rows) {
        String fullname = row.select("td:eq(0)").text();
        License license = new License();
        ProviderProfile profile = new ProviderProfile();
        license.setProfile(profile);
        profile.setUser(parseDeniedListFullname(fullname));
        LicenseStatus status = new LicenseStatus();
        String action = row.select("td:eq(1)").text();
        status.setName(action);
        String date = row.select("td:eq(2)").text();
        status.setDate(parseDate(date, DATE_FORMAT));
        license.setStatus(status);
        allLicenses.add(license);
    }

    SearchResult<License> searchResult = new SearchResult<License>();
    searchResult.setItems(allLicenses);
    return searchResult;
}

From source file:gov.medicaid.screening.dao.impl.OIGDAOBean.java

/**
 * Verifies if the provided SSN is valid for the given entity id.
 *
 * @param entityId the entity id//from w w  w .  j a v a  2s .c  o  m
 * @param ssn the ssn to be verified
 * @return true if valid, false if not
 * @throws ClientProtocolException if client does not support protocol used.
 * @throws IOException if an error occurs while parsing response.
 * @throws ServiceException for any other problems encountered
 *
 * @deprecated not updated in new site layout.
 */
@Deprecated
private boolean checkSSN(String entityId, String ssn) throws IOException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient(getLaxSSLConnectionManager());
    client.setRedirectStrategy(new LaxRedirectStrategy());
    return executeVerification(client, entityId, ssn, getDetails(client, entityId));
}

From source file:gov.medicaid.screening.dao.impl.NursingLicenseDAOBean.java

/**
 * This method performs login to the configured site.
 *
 * @return the cookies generated by the login process
 *
 * @throws URISyntaxException if an error occurs while building the URL.
 * @throws ClientProtocolException if client does not support protocol used.
 * @throws IOException if an error occurs while parsing response.
 * @throws ServiceException for any other problems encountered
 *///w  w w.j a va 2  s. c  o m
private CookieStore loginAsPublicUser()
        throws URISyntaxException, ClientProtocolException, IOException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient(getLaxSSLConnectionManager());
    client.setRedirectStrategy(new LaxRedirectStrategy());

    String loginSite = getLoginURL();
    HttpGet getLogin = new HttpGet(new URIBuilder(loginSite).build());
    HttpResponse response = client.execute(getLogin);
    verifyAndAuditCall(loginSite, response);

    Document page = Jsoup.parse(EntityUtils.toString(response.getEntity()));

    // select public user
    HttpPost login = new HttpPost(new URIBuilder(loginSite).build());
    HttpEntity entity = postForm(loginSite, client, login,
            new String[][] { { "__EVENTTARGET", "_ctl0_rblUserType_2" }, { "__EVENTARGUMENT", "" },
                    { "__VIEWSTATE", page.select("input[name=__VIEWSTATE]").first().val() } },
            true);

    page = Jsoup.parse(EntityUtils.toString(entity));

    // enter credentials
    entity = postForm(loginSite, client, login,
            new String[][] { { "__EVENTTARGET", "" }, { "__EVENTARGUMENT", "" }, { "_ctl0:cmdLogin", "Log In" },
                    { "_ctl0:rblUserType", "14" }, { "_ctl0:txtEMailAddress", getUsername() },
                    { "_ctl0:txtPassword", getPassword() },
                    { "__VIEWSTATE", page.select("input[name=__VIEWSTATE]").first().val() } },
            true);

    page = Jsoup.parse(EntityUtils.toString(entity));

    // check that the user was actually logged in
    if (page.select("a#Banner_hlLogoff").size() == 0) {
        throw new ServiceException(ErrorCode.MITA50003.getDesc());
    }
    return client.getCookieStore();
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryDMS(String dms_endpoint, String body) throws UnsupportedEncodingException, IOException,
        KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

    //        SSLContextBuilder builder = new SSLContextBuilder();
    //        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    //        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
    //                builder.build(),SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    //        CloseableHttpClient httpclient = HttpClients.custom()
    //                //.setSSLSocketFactory(sslsf)
    //                .setHostnameVerifier(new AllowAllHostnameVerifier())
    //                .setRedirectStrategy(new LaxRedirectStrategy()).build();
    //        /*from www. j a  va2s .c  om*/
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();

    String url = this.dms_URL + "/" + dms_endpoint;

    HttpPost post = new HttpPost(url);

    post.addHeader("Content-Type", "application/json");

    post.addHeader("Content-Type", cookie.substring(17));
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
            .setConnectTimeout(5000).setSocketTimeout(5000).build();
    post.setConfig(requestConfig);
    //            

    HttpEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
    post.setEntity(entity);
    CloseableHttpResponse clientresponse = httpclient.execute(post);

    if (clientresponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK
            && clientresponse.getStatusLine().getStatusCode() != HttpStatus.SC_ACCEPTED) {
        return null;
    }
    String sdata;
    sdata = EntityUtils.toString(clientresponse.getEntity(), StandardCharsets.UTF_8);

    return sdata;
    //       
}