Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#build()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#build() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: consul-api   File: DefaultHttpTransport.java    License: Apache License 2.0 6 votes vote down vote up
public DefaultHttpTransport() {
	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
	connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
	connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE_CONNECTIONS);

	RequestConfig requestConfig = RequestConfig.custom().
			setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT).
			setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT).
			setSocketTimeout(DEFAULT_READ_TIMEOUT).
			build();

	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().
			setConnectionManager(connectionManager).
			setDefaultRequestConfig(requestConfig).
			useSystemProperties();

	this.httpClient = httpClientBuilder.build();
}
 
Example 2
/**
 * Ensure proxy settings are applied to http client
 * @throws SecurityException 
 * @throws NoSuchFieldException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
@Test
public void shouldAddProxyToClient() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
	
	HttpClientBuilder builder = HttpClientBuilder.create();
	
	ClientConfiguration config = new ClientConfiguration().withProxyHost("127.0.0.1").withProxyPort(8080);

	HttpClientSettings settings = HttpClientSettings.adapt(config);
	
	DefaultTokenManager.addProxyConfig(builder, settings);
	builder.build();
	Field field = builder.getClass().getDeclaredField("routePlanner");    
	field.setAccessible(true);
	HttpRoutePlanner httpRoutePlanner = (HttpRoutePlanner) field.get(builder);
	
	assertNotNull(httpRoutePlanner);
}
 
Example 3
Source Project: product-iots   File: HTTPInvoker.java    License: Apache License 2.0 5 votes vote down vote up
private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}
 
Example 4
Source Project: knox   File: GatewayBasicFuncTest.java    License: Apache License 2.0 5 votes vote down vote up
private String oozieQueryJobStatus( String user, String password, String id, int status ) throws Exception {
  driver.getMock( "OOZIE" )
      .expect()
      .method( "GET" )
      .pathInfo( "/v1/job/" + id )
      .respond()
      .status( HttpStatus.SC_OK )
      .content( driver.getResourceBytes( "oozie-job-show-info.json" ) )
      .contentType( "application/json" );

  //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
  URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/job/" + id + ( driver.isUseGateway() ? "" : "?user.name=" + user ) );
  HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
  HttpClientBuilder builder = HttpClientBuilder.create();
  CloseableHttpClient client = builder.build();

  HttpClientContext context = HttpClientContext.create();
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(
      new AuthScope( targetHost ),
      new UsernamePasswordCredentials( user, password ) );
  context.setCredentialsProvider( credsProvider );

  // Create AuthCache instance
  AuthCache authCache = new BasicAuthCache();
  // Generate BASIC scheme object and add it to the local auth cache
  BasicScheme basicAuth = new BasicScheme();
  authCache.put( targetHost, basicAuth );
  // Add AuthCache to the execution context
  context.setAuthCache( authCache );

  HttpGet request = new HttpGet( url.toURI() );
  request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
  HttpResponse response = client.execute( targetHost, request, context );
  assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) );
  String json = EntityUtils.toString( response.getEntity() );
  return JsonPath.from(json).getString( "status" );
}
 
Example 5
Source Project: joynr   File: HttpClientProvider.java    License: Apache License 2.0 5 votes vote down vote up
public CloseableHttpClient createHttpClient(MessagingSettings mySettings, Properties withProperties) {

        // Create a HTTP client that uses the default pooling connection manager
        // and is configured by system properties
        HttpClientBuilder httpClientBuilder = HttpClients.custom()
                                                         .setDefaultCredentialsProvider(null)
                                                         .setMaxConnTotal(httpConstants.getHTTP_MAXIMUM_CONNECTIONS_TOTAL())
                                                         .setMaxConnPerRoute(httpConstants.getHTTP_MAXIMUM_CONNECTIONS_TO_HOST())
                                                         .useSystemProperties();

        String proxyHost = withProperties.getProperty("http.proxyhost");
        if (proxyHost != null) {
            // default proxy port is 8080
            int proxyPort = 8080;
            try {
                proxyPort = Integer.parseInt(withProperties.getProperty("http.proxyport"));
            } catch (Exception e) {
            }

            String proxyUser = withProperties.getProperty("http.proxyuser");
            if (proxyUser != null) {
                String proxyPassword = withProperties.getProperty("http.proxypassword");
                // default password is empty string
                proxyPassword = proxyPassword == null ? "" : proxyPassword;

                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                                             new UsernamePasswordCredentials(proxyUser, proxyPassword));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        return httpClientBuilder.build();
    }
 
Example 6
public WebServicesClient(ClientConfig config)
{
  if (SecurityUtils.isHadoopWebSecurityEnabled()) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(connectionManager);
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpClientBuilder.setDefaultAuthSchemeRegistry(authRegistry);
    ApacheHttpClient4Handler httpClientHandler = new ApacheHttpClient4Handler(httpClientBuilder.build(), new BasicCookieStore(), false);
    client = new Client(httpClientHandler, config);
  } else {
    client = Client.create(config);
  }
}
 
Example 7
@Test
public void testHttpRequestGet() throws Exception {

    RequestConfig.Builder req = RequestConfig.custom();
    req.setConnectTimeout(5000);
    req.setConnectionRequestTimeout(5000);
    req.setRedirectsEnabled(false);
    req.setSocketTimeout(5000);
    req.setExpectContinueEnabled(false);

    HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
    get.setConfig(req.build());

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(5);

    HttpClientBuilder builder = HttpClients.custom();
    builder.disableAutomaticRetries();
    builder.disableRedirectHandling();
    builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionManager(cm);
    CloseableHttpClient client = builder.build();

    String s = client.execute(get, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(301, response.getStatusLine().getStatusCode());
            return "success";
        }

    });
    assertEquals("success", s);

}
 
Example 8
public static String getFileInfo(String baseUrl, String externalId, String receiverAddress, String urkundUsername, String urkundPassword, int timeout){
	String ret = null;
	RequestConfig.Builder requestBuilder = RequestConfig.custom();
	requestBuilder = requestBuilder.setConnectTimeout(timeout);
	requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);
	
	HttpClientBuilder builder = HttpClientBuilder.create();     
	builder.setDefaultRequestConfig(requestBuilder.build());
	try (CloseableHttpClient httpClient = builder.build()) {
		HttpGet httpget = new HttpGet(baseUrl+"submissions/"+receiverAddress+"/"+externalId);
		
		//------------------------------------------------------------
		if(StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
			addAuthorization(httpget, urkundUsername, urkundPassword);
		}
		//------------------------------------------------------------
		httpget.addHeader("Accept", "application/json");
		//------------------------------------------------------------
		
		HttpResponse response = httpClient.execute(httpget);
		HttpEntity resEntity = response.getEntity();

		if (resEntity != null) {
			ret = EntityUtils.toString(resEntity);
			EntityUtils.consume(resEntity);
		}
		
	} catch (IOException e) {
		log.error("ERROR getting File Info : ", e);
	}
	return ret;
}
 
Example 9
Source Project: cloudbreak   File: VaultConfig.java    License: Apache License 2.0 5 votes vote down vote up
private ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
        throws GeneralSecurityException, IOException {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(
            DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));

    if (isNoneEmpty(httpsProxyUser, httpsProxyPassword)) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(httpsProxyUser, httpsProxyPassword);
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }

    if (hasSslConfiguration(sslConfiguration)) {
        SSLContext sslContext = getSSLContext(sslConfiguration,
                getTrustManagers(sslConfiguration));
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setSSLContext(sslContext);
    }

    RequestConfig requestConfig = RequestConfig
            .custom()
            .setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis()))
            .setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis()))
            .setAuthenticationEnabled(true)
            .build();

    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
 
Example 10
Source Project: train-ticket-reaper   File: HttpClientUtils.java    License: MIT License 5 votes vote down vote up
public static List<String> cookiesByGet(String url, String userAgent, String referer, String cookie) throws IOException {
    HttpClientBuilder builder = HttpClients.custom();
    CloseableHttpClient client = builder.build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader("Host", getHost(url));
    if (referer != null) {
        httpGet.addHeader("Referer", referer);
    }
    httpGet.addHeader("User-Agent", userAgent);
    if (cookie != null) {
        httpGet.addHeader("Cookie", cookie);
    }

    List<String> resultList = new LinkedList<>();
    CloseableHttpResponse response = client.execute(httpGet);
    for (Header header : response.getAllHeaders()) {
        if ("Set-Cookie".equals(header.getName())) {
            HeaderElement[] elements = header.getElements();
            resultList.add(elements[0].toString().split(";")[0]);
        }
    }
    if (resultList != null && resultList.size() > 0) {
        return resultList;
    } else {
        return null;
    }
}
 
Example 11
Source Project: instagram4j   File: Instagram4j.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Setup some variables
 */
public void setup() {
	log.info("Setup...");

	if (StringUtils.isEmpty(this.username)) {
		throw new IllegalArgumentException("Username is mandatory.");
	}

	if (StringUtils.isEmpty(this.password)) {
		throw new IllegalArgumentException("Password is mandatory.");
	}

	this.deviceId = InstagramHashUtil.generateDeviceId(this.username, this.password);

	if (StringUtils.isEmpty(this.uuid)) {
		this.uuid = InstagramGenericUtil.generateUuid(true);
	}

	if (StringUtils.isEmpty(this.advertisingId)) {
		this.advertisingId = InstagramGenericUtil.generateUuid(true);
	}

	if (this.cookieStore == null) {
		this.cookieStore = new BasicCookieStore();
	}

	log.info("Device ID is: " + this.deviceId + ", random id: " + this.uuid);
	HttpClientBuilder builder = HttpClientBuilder.create();
	if (proxy != null) {
		builder.setProxy(proxy);
	}

	if (credentialsProvider != null)
		builder.setDefaultCredentialsProvider(credentialsProvider);

	builder.setDefaultCookieStore(this.cookieStore);
	this.client = builder.build();
}
 
Example 12
@Override
public Client connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    return new Client(configuration.build());
}
 
Example 13
CloseableHttpClient createClient() {

        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultCookieStore(cookieStore);
        builder.setDefaultCredentialsProvider(credentialsProvider);
        builder.setUserAgent(format("SAP CM Client/%s based on Olingo v%s",
                getShortVersion(),
                getOlingoV2Version()));
        return builder.build();
    }
 
Example 14
Source Project: allure2   File: GaPlugin.java    License: Apache License 2.0 5 votes vote down vote up
protected void sendStats(final String clientId, final GaParameters parameters) {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    try (CloseableHttpClient client = builder.build()) {
        final List<NameValuePair> pairs = Arrays.asList(
                pair("v", GA_API_VERSION),
                pair("aip", GA_API_VERSION),
                pair("tid", GA_ID),
                pair("z", UUID.randomUUID().toString()),
                pair("sc", "end"),
                pair("t", "event"),
                pair("cid", clientId),
                pair("an", "Allure Report"),
                pair("ec", "Allure CLI events"),
                pair("ea", "Report generate"),
                pair("av", parameters.getAllureVersion()),
                pair("ds", "Report generator"),
                pair("cd6", parameters.getLanguage()),
                pair("cd5", parameters.getFramework()),
                pair("cd2", parameters.getExecutorType()),
                pair("cd4", parameters.getResultsFormat()),
                pair("cm1", String.valueOf(parameters.getResultsCount()))
        );
        final HttpPost post = new HttpPost(GA_ENDPOINT);
        final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8);
        post.setEntity(entity);
        client.execute(post).close();
        LOGGER.debug("GA done");
    } catch (IOException e) {
        LOGGER.debug("Could not send analytics", e);
    }
}
 
Example 15
public CloseableHttpClient build() {
  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  httpClientBuilder.setConnectionManager( manager );

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  if ( socketTimeout > 0 ) {
    requestConfigBuilder.setSocketTimeout( socketTimeout );
  }
  if ( connectionTimeout > 0 ) {
    requestConfigBuilder.setConnectTimeout( socketTimeout );
  }
  if ( proxy != null ) {
    requestConfigBuilder.setProxy( proxy );
  }
  if ( cookieSpec != null ) {
    requestConfigBuilder.setCookieSpec( cookieSpec );
  }
  if ( maxRedirects > 0 ) {
    requestConfigBuilder.setMaxRedirects( maxRedirects );
  }
  if ( allowCircularRedirects ) {
    requestConfigBuilder.setCircularRedirectsAllowed( true );
  }
  if ( !rejectRelativeRedirect ) {
    requestConfigBuilder.setRelativeRedirectsAllowed( true );
  }

  // RequestConfig built
  httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );

  if ( provider != null ) {
    httpClientBuilder.setDefaultCredentialsProvider( provider );
  }
  if ( redirectStrategy != null ) {
    httpClientBuilder.setRedirectStrategy( redirectStrategy );
  }

  return httpClientBuilder.build();
}
 
Example 16
@Override
protected OneDriveAPI connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol()) {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            if(request.containsHeader(HttpHeaders.AUTHORIZATION)) {
                super.process(request, context);
            }
        }
    }.withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    final RequestExecutor executor = new GraphCommonsHttpRequestExecutor(configuration.build()) {
        @Override
        public void addAuthorizationHeader(final Set<RequestHeader> headers) {
            // Placeholder
            headers.add(new RequestHeader(HttpHeaders.AUTHORIZATION, "Bearer"));
        }
    };
    return new OneDriveAPI() {
        @Override
        public RequestExecutor getExecutor() {
            return executor;
        }

        @Override
        public boolean isBusinessConnection() {
            return false;
        }

        @Override
        public boolean isGraphConnection() {
            if(StringUtils.equals("graph.microsoft.com", host.getHostname())) {
                return true;
            }
            else if(StringUtils.equals("graph.microsoft.de", host.getHostname())) {
                return true;
            }
            return false;
        }

        @Override
        public String getBaseURL() {
            return String.format("%s://%s%s", host.getProtocol().getScheme(), host.getHostname(), host.getProtocol().getContext());
        }

        @Override
        public String getEmailURL() {
            return String.format("%s://%s%s", host.getProtocol().getScheme(), host.getHostname(), "/v1.0/me");
        }
    };
}
 
Example 17
@Override
public ConnectionManagerAwareHttpClient create(HttpClientSettings settings) {
    final HttpClientBuilder builder = HttpClients.custom();
    // Note that it is important we register the original connection manager with the
    // IdleConnectionReaper as it's required for the successful deregistration of managers
    // from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
    final HttpClientConnectionManager cm = cmFactory.create(settings);

    builder.setRequestExecutor(new SdkHttpRequestExecutor())
            .setKeepAliveStrategy(buildKeepAliveStrategy(settings))
            .disableRedirectHandling()
            .disableAutomaticRetries()
            .setConnectionManager(ClientConnectionManagerFactory.wrap(cm));

    // By default http client enables Gzip compression. So we disable it
    // here.
    // Apache HTTP client removes Content-Length, Content-Encoding and
    // Content-MD5 headers when Gzip compression is enabled. Currently
    // this doesn't affect S3 or Glacier which exposes these headers.
    //
    if (!(settings.useGzip())) {
        builder.disableContentCompression();
    }

    HttpResponseInterceptor itcp = new CRC32ChecksumResponseInterceptor();
    if (settings.calculateCRC32FromCompressedData()) {
        builder.addInterceptorFirst(itcp);
    } else {
        builder.addInterceptorLast(itcp);
    }

    addProxyConfig(builder, settings);

    final ConnectionManagerAwareHttpClient httpClient = new SdkHttpClient(builder.build(), cm);

    if (settings.useReaper()) {
        IdleConnectionReaper.registerConnectionManager(cm, settings.getMaxIdleConnectionTime());
    }

    return httpClient;
}
 
Example 18
Source Project: knox   File: RMHaDispatchTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://passive-host.invalid");
    URI uri2 = new URI("http://other-host.invalid");
    URI uri3 = new URI("http://active-host.invalid");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    urlList.add(uri3.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(provider).anyTimes();


    BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class);
    EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes();
    EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes();
    EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString())).anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)).once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host.invalid");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest, outboundResponse);

    RMHaDispatch dispatch = new RMHaDispatch();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    dispatch.setHttpClient(client);
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.setInboundResponse(inboundResponse);
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    Assert.assertEquals(uri3.toString(), dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString());
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}
 
Example 19
private void pollServer() {	   
   Timer oldTimer = timerRef.getAndSet(null);
   if (oldTimer != null) {
      oldTimer.cancel();
   }
   HttpClientBuilder builder = HttpClientBuilder.create();
   builder.setSslcontext(sslContext);
	CloseableHttpClient httpClient = builder.build();
	
	boolean fastPoll = false;
	try {
		StringEntity entity = new StringEntity(buildPayload(), ContentType.APPLICATION_FORM_URLENCODED);
		HttpUriRequest pollingMsg = RequestBuilder.post()
				.setUri(uri)
				.setEntity(entity)
				.build();
		CloseableHttpResponse response = httpClient.execute(pollingMsg);
		try {
			HttpEntity stuff = response.getEntity();
			String thing = EntityUtils.toString(stuff);
			System.out.println("####\n#### RESPONSE " + response.getStatusLine());
			System.out.println("####\n    Response Message: " + thing + "\n####");
			
			fastPoll = applyResults(thing);
		}
		finally {
			response.close();
		}
	}
	catch(Exception ex) {
		ex.printStackTrace();
	}
	finally {
		try {
			httpClient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   timerRef.set(new Timer());
		if (fastPoll) {
		   System.out.println("####\n#### Schedule Fast Poll: " + FAST_POLL + "s" + "\n####");
		   timerRef.get().schedule(new PollServerTask(), FAST_POLL * 1000);
		}
		else {
		   int pollingInterval = Integer.valueOf(state.get(AosConstants.AOS_PARAM_UPDATERATE));
		   System.out.println("####\n#### Schedule Standard Poll: " + pollingInterval + "s" + "\n####");
		   timerRef.get().schedule(new PollServerTask(), pollingInterval * 1000);
		}
	}
}
 
Example 20
Source Project: plumdo-work   File: RestTemplateConfig.java    License: Apache License 2.0 3 votes vote down vote up
@Bean
public HttpClient httpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    httpClientBuilder.setSSLContext(sslContext());

    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));

    httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager());

    return httpClientBuilder.build();
}