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.opennms.smoketest.minion.DiscoveryTest.java

@Test
public void canDiscoverRemoteNodes() throws ClientProtocolException, IOException {
    Date startOfTest = new Date();

    final String tomcatIp = minionSystem.getContainerInfo(ContainerAlias.TOMCAT).networkSettings().ipAddress();
    final InetSocketAddress opennmsHttp = minionSystem.getServiceAddress(ContainerAlias.OPENNMS, 8980);
    final HttpHost opennmsHttpHost = new HttpHost(opennmsHttp.getAddress().getHostAddress(),
            opennmsHttp.getPort());//from  ww  w.  j av  a 2 s . co  m

    HttpClient instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()) // Ignore the 302 response to the POST
            .build();

    Executor executor = Executor.newInstance(instance).auth(opennmsHttpHost, "admin", "admin")
            .authPreemptive(opennmsHttpHost);

    // Configure Discovery with the specific address of our Tomcat server
    // No REST endpoint is currently available, so we resort to POSTin nasty form data
    executor.execute(Request
            .Post(String.format("http://%s:%d/opennms/admin/discovery/actionDiscovery?action=AddSpecific",
                    opennmsHttp.getAddress().getHostAddress(), opennmsHttp.getPort()))
            .bodyForm(Form.form().add("specificipaddress", tomcatIp).add("specifictimeout", "2000")
                    .add("specificretries", "1").add("initialsleeptime", "30000")
                    .add("restartsleeptime", "86400000").add("foreignsource", "NODES").add("location", "MINION")
                    .add("retries", "1").add("timeout", "2000").build()))
            .returnContent();

    executor.execute(Request
            .Post(String.format("http://%s:%d/opennms/admin/discovery/actionDiscovery?action=SaveAndRestart",
                    opennmsHttp.getAddress().getHostAddress(), opennmsHttp.getPort()))
            .bodyForm(Form.form().add("initialsleeptime", "1").add("restartsleeptime", "86400000")
                    .add("foreignsource", "NODES").add("location", "MINION").add("retries", "1")
                    .add("timeout", "2000").build()))
            .returnContent();

    InetSocketAddress pgsql = minionSystem.getServiceAddress(ContainerAlias.POSTGRES, 5432);
    HibernateDaoFactory daoFactory = new HibernateDaoFactory(pgsql);
    EventDao eventDao = daoFactory.getDao(EventDaoHibernate.class);

    // TODO: Match the Monitoring System ID when this becomes available in the event
    Criteria criteria = new CriteriaBuilder(OnmsEvent.class)
            .eq("eventUei", EventConstants.NEW_SUSPECT_INTERFACE_EVENT_UEI).ge("eventTime", startOfTest)
            .toCriteria();

    await().atMost(1, MINUTES).pollInterval(10, SECONDS)
            .until(DaoUtils.countMatchingCallable(eventDao, criteria), greaterThan(0));
}

From source file:org.apache.juneau.rest.test.TestMicroservice.java

public static CloseableHttpClient createHttpClient() {
    try {//from  w ww  .  ja  va 2  s  .c o m
        return HttpClients.custom().setSSLSocketFactory(getSSLSocketFactory())
                .setRedirectStrategy(new LaxRedirectStrategy()).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.xiyou.fruits.WebCrawler.net.HttpRequest.java

public HttpRequest() {
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(Config.TTIME_OUT)
            .setSocketTimeout(Config.TTIME_OUT).build();
    client = HttpClients.custom().setUserAgent(
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36")
            .setRetryHandler(new DefaultHttpRequestRetryHandler(Config.RETRY, true))
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultRequestConfig(requestConfig)
            .setConnectionManager(connectionManager).build();
}

From source file:com.adobe.ags.curly.ConnectionManager.java

public CloseableHttpClient getAuthenticatedClient(CredentialsProvider creds) {
    resetConnectionManager(httpPoolSize);
    return HttpClients.custom().setDefaultCredentialsProvider(creds).setDefaultCookieStore(cookieStore)
            .setConnectionManager(connectionManager).setConnectionManagerShared(true)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
}

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

BaseParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
    this.scheduleData = scheduleData;
    this.cookieProvider = cookieProvider;
    this.cookieStore = new BasicCookieStore();
    this.colorProvider = new ColorProvider(scheduleData);
    this.encodingDetector = new UniversalDetector(null);

    try {//  w  ww .  ja v a2s .c om
        KeyStore ks = loadKeyStore();
        MultiTrustManager multiTrustManager = new MultiTrustManager();
        multiTrustManager.addTrustManager(getDefaultTrustManager());
        multiTrustManager.addTrustManager(trustManagerFromKeystore(ks));

        TrustManager[] trustManagers = new TrustManager[] { multiTrustManager };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        final HostnameVerifier hostnameVerifier;

        if (scheduleData.getData() != null && scheduleData.getData().has(PARAM_SSL_HOSTNAME)) {
            hostnameVerifier = new CustomHostnameVerifier(scheduleData.getData().getString(PARAM_SSL_HOSTNAME));
        } else {
            hostnameVerifier = new DefaultHostnameVerifier();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, hostnameVerifier);

        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .build();
        this.executor = Executor.newInstance(httpclient).use(cookieStore);
    } catch (GeneralSecurityException | JSONException | IOException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Retrieves all results from the source site.
 * /*from w ww. j a  v a 2 s  .co  m*/
 * @return the birth centers matched
 * @throws URISyntaxException
 *             if the URL could not be correctly constructed
 * @throws IOException
 *             for any I/O related errors
 * @throws ServiceException
 *             for any other errors encountered
 */
private List<AccreditedBirthCenter> getAllResults() throws URISyntaxException, IOException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());

    HttpGet getFrontPage = new HttpGet(new URIBuilder(getSearchURL()).build());
    HttpResponse response = client.execute(getFrontPage);

    verifyAndAuditCall(getSearchURL(), response);

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

    List<AccreditedBirthCenter> allCenters = new ArrayList<AccreditedBirthCenter>();
    Elements rows = page.select("table#wp-table-reloaded-id-1-no-1 tbody tr");
    for (Element row : rows) {
        AccreditedBirthCenter center = parseCenter(row.children());
        if (center != null) {
            allCenters.add(center);
        }
    }
    return allCenters;
}

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

@Test
public void concurrentLoginSingleUser() throws Throwable {
    log.info("*********************************************");
    long start = System.currentTimeMillis();

    AtomicReference<String> userSessionId = new AtomicReference<>();
    LoginTask loginTask = null;//from w w  w. ja v  a  2 s .  com

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy()).build()) {
        loginTask = new LoginTask(httpClient, userSessionId, 100, 1, false,
                Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password")));
        run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask);
        int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test",
                userSessionId.get());
        Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT, clientSessionsCount);
    } finally {
        long end = System.currentTimeMillis() - start;
        log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram());
        log.info("concurrentLoginSingleUser took " + (end / 1000) + "s");
        log.info("*********************************************");
    }
}

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

/**
 * Performs the call to the source site, exact match is expected given the parameters.
 *
 * @param criteria the search criteria// w ww.j  a  v  a2  s.  c  o  m
 * @return the matched result, null if not found
 * @throws IOException if an I/O error is encountered
 * @throws URISyntaxException if the site URL cannot properly be created
 * @throws ServiceException for any other exceptions encountered
 */
private ProviderProfile getProviderProfile(NurseAnesthetistsSearchCriteria criteria)
        throws ServiceException, IOException, URISyntaxException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());

    String searchURL = getSearchURL();
    HttpGet getSearch = new HttpGet(new URIBuilder(searchURL).build());
    HttpResponse response = client.execute(getSearch);
    verifyAndAuditCall(searchURL, response);

    Document page = Jsoup.parse(EntityUtils.toString(response.getEntity()));
    HttpPost search = new HttpPost(new URIBuilder(searchURL).build());

    String searchType = "Lookup Certification Status";

    String last4 = criteria.getSsn().substring(criteria.getSsn().length() - 4);
    HttpEntity entity = postForm(searchURL, client, search,
            new String[][] { { "__EVENTARGUMENT", "" }, { "__EVENTTARGET", "" },
                    { "__EVENTVALIDATION", page.select("input[name=__EVENTVALIDATION]").first().val() },
                    { "__VIEWSTATE", page.select("input[name=__VIEWSTATE]").first().val() },
                    { "ctl00$PageContent$CertRecert$btnLookup", searchType },
                    { "ctl00$PageContent$CertRecert$txtAANANumber", "" + criteria.getAanaNumber() },
                    { "ctl00$PageContent$CertRecert$txtSSNLast4", "" + last4 } },
            true);

    page = Jsoup.parse(EntityUtils.toString(entity));
    Elements message = page.select("#ctl00_PageContent_ucCredentialsControl_lblErrorMessage");
    if (message.size() > 0) {
        if (message.text().startsWith("No individual with a social security number")) {
            // no match, return null
            return null;
        }
    }

    if (criteria.isRecertification()) {
        searchType = "Lookup Recertification Status";
        entity = postForm(searchURL, client, search,
                new String[][] { { "__EVENTARGUMENT", "" }, { "__EVENTTARGET", "" },
                        { "__EVENTVALIDATION", page.select("input[name=__EVENTVALIDATION]").first().val() },
                        { "__VIEWSTATE", page.select("input[name=__VIEWSTATE]").first().val() },
                        { "ctl00$PageContent$CertRecert$btnSwapDisplayMode", searchType } },
                true);
        page = Jsoup.parse(EntityUtils.toString(entity));
    }
    return parseProvider(page);
}

From source file:org.thoughtcrime.securesms.mms.MmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent("Android-Mms/2.0")
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .build();//  w ww . j a v a 2 s  .c o m
}

From source file:com.liferay.sync.engine.session.Session.java

public static HttpClientBuilder createHttpClientBuilder(boolean trustSelfSigned, int maxConnections) {

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    httpClientBuilder.disableAutomaticRetries();

    RequestConfig.Builder builder = RequestConfig.custom();

    builder.setConnectTimeout(PropsValues.SYNC_HTTP_CONNECTION_TIMEOUT);

    if (maxConnections == Integer.MAX_VALUE) {
        builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT * 2);
    } else {// ww w.ja  v a  2 s. c  o m
        builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT);
    }

    List<Header> headers = new ArrayList<>(2);

    Header syncBuildHeader = new BasicHeader("Sync-Build", String.valueOf(ReleaseInfo.getBuildNumber()));

    headers.add(syncBuildHeader);

    String syncDeviceType = null;

    if (OSDetector.isApple()) {
        syncDeviceType = "desktop-mac";
    } else if (OSDetector.isLinux()) {
        syncDeviceType = "desktop-linux";
    } else if (OSDetector.isWindows()) {
        syncDeviceType = "desktop-windows";
    }

    Header syncDeviceTypeHeader = new BasicHeader("Sync-Device", syncDeviceType);

    headers.add(syncDeviceTypeHeader);

    httpClientBuilder.setDefaultHeaders(headers);

    httpClientBuilder.setDefaultRequestConfig(builder.build());
    httpClientBuilder.setMaxConnPerRoute(maxConnections);
    httpClientBuilder.setMaxConnTotal(maxConnections);
    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    httpClientBuilder.setRoutePlanner(getHttpRoutePlanner());

    try {
        if (trustSelfSigned) {
            httpClientBuilder.setSSLSocketFactory(_getTrustingSSLSocketFactory());
        } else {
            httpClientBuilder.setSSLSocketFactory(_getDefaultSSLSocketFactory());
        }
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
    }

    return httpClientBuilder;
}