com.netflix.client.ClientFactory Java Examples

The following examples show how to use com.netflix.client.ClientFactory. 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 check out the related API usage on the sidebar.
Example #1
Source File: DeleteRSSCommand.java    From recipes-rss with Apache License 2.0 6 votes vote down vote up
@Override
protected String run() {
	try {
		// The named client param must match the prefix for the ribbon
		// configuration specified in the edge.properties file
		RestClient client = (RestClient) ClientFactory.getNamedClient(RSSConstants.MIDDLETIER_REST_CLIENT);

		HttpClientRequest request = HttpClientRequest
				.newBuilder()
				.setVerb(Verb.DELETE)
				.setUri(new URI("/"
                           + RSSConstants.MIDDLETIER_WEB_RESOURCE_ROOT_PATH
                           + RSSConstants.RSS_ENTRY_POINT
                           + "?url=" + url)
                   )
				.build();
		HttpClientResponse response = client.executeWithLoadBalancer(request);

		return IOUtils.toString(response.getRawEntity(), Charsets.UTF_8);
	} catch (Exception exc) {
		throw new RuntimeException("Exception", exc);
	}
}
 
Example #2
Source File: GetRSSCommand.java    From recipes-rss with Apache License 2.0 6 votes vote down vote up
@Override
protected String run() {
	try {
		// The named client param must match the prefix for the ribbon
		// configuration specified in the edge.properties file
		RestClient client = (RestClient) ClientFactory.getNamedClient(RSSConstants.MIDDLETIER_REST_CLIENT);

		HttpClientRequest request = HttpClientRequest
				.newBuilder()
				.setVerb(Verb.GET)
				.setUri(new URI("/"
						+ RSSConstants.MIDDLETIER_WEB_RESOURCE_ROOT_PATH
						+ RSSConstants.RSS_ENTRY_POINT)
                   )
				.build();
		HttpClientResponse response = client.executeWithLoadBalancer(request);

		return IOUtils.toString(response.getRawEntity(), Charsets.UTF_8);
	} catch (Exception exc) {
		throw new RuntimeException("Exception", exc);
	}
}
 
Example #3
Source File: AddRSSCommand.java    From recipes-rss with Apache License 2.0 6 votes vote down vote up
@Override
protected String run() {
	try {
		/*
		 * The named client param must match the prefix for the ribbon
		 * configuration specified in the edge.properties file
		 */
		RestClient client = (RestClient) ClientFactory.getNamedClient(RSSConstants.MIDDLETIER_REST_CLIENT);

		HttpClientRequest request = HttpClientRequest
				.newBuilder()
				.setVerb(Verb.POST)
				.setUri(new URI("/"
						+ RSSConstants.MIDDLETIER_WEB_RESOURCE_ROOT_PATH
						+ RSSConstants.RSS_ENTRY_POINT
                           + "?url=" + url))
				.build();
		HttpClientResponse response = client.executeWithLoadBalancer(request);

		return IOUtils.toString(response.getRawEntity(), Charsets.UTF_8);
	} catch (Exception exc) {
		throw new RuntimeException("Exception occurred when adding a RSS feed", exc);
	}
}
 
Example #4
Source File: SecureGetTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSunnyDayNoClientAuth() throws Exception{

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = "GetPostSecureTest" + ".testSunnyDayNoClientAuth";

	String configPrefix = name + "." + "ribbon";

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS2.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);

	RestClient rc = (RestClient) ClientFactory.getNamedClient(name);

	testServer2.accept();

	URI getUri = new URI(SERVICE_URI2 + "test/");
       HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
	HttpResponse response = rc.execute(request);
	assertEquals(200, response.getStatus());
}
 
Example #5
Source File: RestClientTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecureClient2()  throws Exception {
    ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.IsSecure, "true");
    ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStore, secureServer.getTrustStore().getAbsolutePath());
    ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD);
    
    RestClient client = (RestClient) ClientFactory.getNamedClient("test3");
    BaseLoadBalancer lb = new BaseLoadBalancer();
    Server[] servers = new Server[]{new Server("localhost", secureServer.getServerPort())}; 
    lb.addServers(Arrays.asList(servers));
    client.setLoadBalancer(lb);
    HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertStatusIsOk(response.getStatus());
    assertEquals(secureServer.getServerPath("/"), response.getRequestedURI().toString());
    
}
 
Example #6
Source File: AbstractServerList.java    From ribbon with Apache License 2.0 6 votes vote down vote up
/**
 * Get a ServerListFilter instance. It uses {@link ClientFactory#instantiateInstanceWithClientConfig(String, IClientConfig)}
 * which in turn uses reflection to initialize the filter instance. 
 * The filter class name is determined by the value of {@link CommonClientConfigKey#NIWSServerListFilterClassName}
 * in the {@link IClientConfig}. The default implementation is {@link ZoneAffinityServerListFilter}.
 */
public AbstractServerListFilter<T> getFilterImpl(IClientConfig niwsClientConfig) throws ClientException {
    String niwsServerListFilterClassName = null;
    try {
        niwsServerListFilterClassName = niwsClientConfig.get(
                        CommonClientConfigKey.NIWSServerListFilterClassName,
                        ZoneAffinityServerListFilter.class.getName());

        AbstractServerListFilter<T> abstractNIWSServerListFilter = 
                (AbstractServerListFilter<T>) ClientFactory.instantiateInstanceWithClientConfig(niwsServerListFilterClassName, niwsClientConfig);
        return abstractNIWSServerListFilter;
    } catch (Throwable e) {
        throw new ClientException(
                ClientException.ErrorType.CONFIGURATION,
                "Unable to get an instance of CommonClientConfigKey.NIWSServerListFilterClassName. Configured class:"
                        + niwsServerListFilterClassName, e);
    }
}
 
Example #7
Source File: NamedConnectionPoolTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionPoolCleaner() throws Exception {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    ConfigurationManager.getConfigInstance().setProperty("ConnectionPoolCleanerTest.ribbon." + CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, "100");
    ConfigurationManager.getConfigInstance().setProperty("ConnectionPoolCleanerTest.ribbon." + CommonClientConfigKey.ConnectionCleanerRepeatInterval, "500");
    RestClient client = (RestClient) ClientFactory.getNamedClient("ConnectionPoolCleanerTest");
    NFHttpClient httpclient = NFHttpClientFactory.getNamedNFHttpClient("ConnectionPoolCleanerTest");
    assertNotNull(httpclient);
    com.netflix.client.http.HttpResponse response = null;
    try {
        response = client.execute(HttpRequest.newBuilder().uri(server.getServerPath("/")).build());
    } finally {
        if (response != null) {
            response.close();
        }
    }
    MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) httpclient.getConnectionManager();
    Thread.sleep(2000);
    assertEquals(0, connectionPoolManager.getConnectionsInPool());
    client.shutdown();
}
 
Example #8
Source File: RetryTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Before
public void beforeTest() {
    ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.NFLoadBalancerClassName", BaseLoadBalancer.class.getName());
    ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.client.NFLoadBalancerPingClassName", DummyPing.class.getName());

    ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.ReadTimeout", "1000");
    ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.ConnectTimeout, "500");
    ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.OkToRetryOnAllOperations, "true");

    client = (RestClient) ClientFactory.getNamedClient("RetryTest");

    lb = (BaseLoadBalancer) client.getLoadBalancer();
    lb.setServersList(Lists.newArrayList(localServer));
    
    httpClient = NFHttpClientFactory.getNamedNFHttpClient("RetryTest");
    connectionPoolManager = (MonitoredConnectionManager) httpClient.getConnectionManager(); 
    
    client.setMaxAutoRetries(0);
    client.setMaxAutoRetriesNextServer(0);
    client.setOkToRetryOnAllOperations(false);
    lb.setServersList(Lists.newArrayList(localServer));
    // reset the server index
    lb.setRule(new AvailabilityFilteringRule());
    lb.getLoadBalancerStats().getSingleServerStat(localServer).clearSuccessiveConnectionFailureCount();
}
 
Example #9
Source File: RestClientTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteWithoutLB() throws Exception {
    RestClient client = (RestClient) ClientFactory.getNamedClient("google");
    HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertStatusIsOk(response.getStatus());
    response = client.execute(request);
    assertStatusIsOk(response.getStatus());
}
 
Example #10
Source File: RestClientTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testVipAsURI()  throws Exception {
	ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.DeploymentContextBasedVipAddresses", server.getServerPath("/"));
	ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.InitializeNFLoadBalancer", "false");
    RestClient client = (RestClient) ClientFactory.getNamedClient("test1");
    assertNull(client.getLoadBalancer());
    HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertStatusIsOk(response.getStatus());
    assertEquals(server.getServerPath("/"), response.getRequestedURI().toString());
}
 
Example #11
Source File: RestClientTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecureClient()  throws Exception {
	ConfigurationManager.getConfigInstance().setProperty("test2.ribbon.IsSecure", "true");
	RestClient client = (RestClient) ClientFactory.getNamedClient("test2");
    HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertStatusIsOk(response.getStatus());
}
 
Example #12
Source File: RestClientTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelete() throws Exception {
    RestClient client = (RestClient) ClientFactory.getNamedClient("google");
    HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).verb(HttpRequest.Verb.DELETE).build();
    HttpResponse response = client.execute(request);
    assertStatusIsOk(response.getStatus());
    
    request = HttpRequest.newBuilder().uri(server.getServerURI()).verb(HttpRequest.Verb.DELETE).entity("").build();
    response = client.execute(request);
    assertStatusIsOk(response.getStatus());
}
 
Example #13
Source File: FollowRedirectTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedirectNotFollowed() throws Exception {
    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues("myclient");
    config.set(CommonClientConfigKey.FollowRedirects, Boolean.FALSE);
    ClientFactory.registerClientFromProperties("myclient", config);
    RestClient client = (RestClient) ClientFactory.getNamedClient("myclient");
    HttpRequest request = HttpRequest.newBuilder().uri(new URI("http://localhost:" + redirectingServer.getPort())).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertEquals(302, response.getStatus());          
}
 
Example #14
Source File: FollowRedirectTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedirectFollowed() throws Exception {
    IClientConfig config = DefaultClientConfigImpl
            .getClientConfigWithDefaultValues("myclient2")
            .set(IClientConfigKey.Keys.FollowRedirects, Boolean.TRUE);
    ClientFactory.registerClientFromProperties("myclient2", config);
    com.netflix.niws.client.http.RestClient client = (com.netflix.niws.client.http.RestClient) ClientFactory.getNamedClient("myclient2");
    HttpRequest request = HttpRequest.newBuilder().uri(new URI("http://localhost:" + redirectingServer.getPort())).build();
    HttpResponse response = client.execute(request);
    assertEquals(200, response.getStatus());      
}
 
Example #15
Source File: ZoneAwareLoadBalancer.java    From ribbon with Apache License 2.0 5 votes vote down vote up
private IRule cloneRule(IRule toClone) {
 	IRule rule;
 	if (toClone == null) {
 		rule = new AvailabilityFilteringRule();
 	} else {
 		String ruleClass = toClone.getClass().getName();        		
 		try {
	rule = (IRule) ClientFactory.instantiateInstanceWithClientConfig(ruleClass, this.getClientConfig());
} catch (Exception e) {
	throw new RuntimeException("Unexpected exception creating rule for ZoneAwareLoadBalancer", e);
}
 	}
 	return rule;
 }
 
Example #16
Source File: BaseLoadBalancer.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
    try {
        initWithNiwsConfig(clientConfig, ClientFactory::instantiateInstanceWithClientConfig);
    } catch (Exception e) {
        throw new RuntimeException("Error initializing load balancer", e);
    }
}
 
Example #17
Source File: ServerListLoabBalancerTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() {
	Configuration config = ConfigurationManager.getConfigInstance();
	config.setProperty("ServerListLoabBalancerTest.ribbon.NFLoadBalancerClassName", 
			com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName());
	config.setProperty("ServerListLoabBalancerTest.ribbon.NIWSServerListClassName", FixedServerList.class.getName());
	lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("ServerListLoabBalancerTest");
}
 
Example #18
Source File: ElasticSearchSink.java    From suro with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void createClient() {
    if (ribbonEtc.containsKey("eureka")) {
        ribbonEtc.setProperty(
            clientName + ".ribbon.AppName", clientName);
        ribbonEtc.setProperty(
            clientName + ".ribbon.NIWSServerListClassName",
            "com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList");
        String[] host_port = addressList.get(0).split(":");
        ribbonEtc.setProperty(
            clientName + ".ribbon.DeploymentContextBasedVipAddresses",
            host_port[0]);
        ribbonEtc.setProperty(
            clientName + ".ribbon.Port",
            host_port[1]);
    } else {
        ribbonEtc.setProperty(clientName + ".ribbon.listOfServers", Joiner.on(",").join(addressList));
    }
    ribbonEtc.setProperty(
        clientName + ".ribbon.EnablePrimeConnections",
        "true");
    String retryPropertyName = clientName + ".ribbon." + CommonClientConfigKey.OkToRetryOnAllOperations;
    if (ribbonEtc.getProperty(retryPropertyName) == null) {
        // default set this to enable retry on POST operation upon read timeout
        ribbonEtc.setProperty(retryPropertyName, "true");
    }
    String maxRetryProperty = clientName + ".ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer;
    if (ribbonEtc.getProperty(maxRetryProperty) == null) {
        // by default retry two different servers upon exception
        ribbonEtc.setProperty(maxRetryProperty, "2");
    }
    ConfigurationManager.loadProperties(ribbonEtc);
    client = (RestClient) ClientFactory.getNamedClient(clientName);

}
 
Example #19
Source File: LBClientFactory.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public LBClient create(String clientName) {
  IClientConfig config =
      ClientFactory.getNamedConfig(clientName, DisableAutoRetriesByDefaultClientConfig.class);
  ILoadBalancer lb = ClientFactory.getNamedLoadBalancer(clientName);
  return LBClient.create(lb, config);
}
 
Example #20
Source File: LBClientFactoryTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateLBClient() {
  LBClientFactory.Default lbClientFactory = new LBClientFactory.Default();
  LBClient client = lbClientFactory.create("clientName");
  assertEquals("clientName", client.getClientName());
  assertEquals(ClientFactory.getNamedLoadBalancer("clientName"), client.getLoadBalancer());
}
 
Example #21
Source File: SecureGetTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailsWithHostNameValidationOn() throws Exception {

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = "GetPostSecureTest" + ".testFailsWithHostNameValidationOn";

	String configPrefix = name + "." + "ribbon";

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "true"); // <--
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD);
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);

	RestClient rc = (RestClient) ClientFactory.getNamedClient(name);

	testServer1.accept();

	URI getUri = new URI(SERVICE_URI1 + "test/");
	MultivaluedMapImpl params = new MultivaluedMapImpl();
	params.add("name", "test");
       HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();

	try{
		rc.execute(request);

		fail("expecting ssl hostname validation error");
	}catch(ClientHandlerException che){
		assertTrue(che.getMessage().indexOf("hostname in certificate didn't match") > -1);
	}
}
 
Example #22
Source File: CloudReactiveFeign.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public Builder<T> enableLoadBalancer(RetryHandler retryHandler){
    if(retryHandler.getMaxRetriesOnSameServer() > 0){
        logger.warn("Use retryWhen(ReactiveRetryPolicy retryPolicy) " +
                "as it allow to configure retry delays (backoff)");
    }
    return setLoadBalancerCommandFactory(serviceName ->
            LoadBalancerCommand.builder()
            .withLoadBalancer(ClientFactory.getNamedLoadBalancer(serviceName))
            .withRetryHandler(retryHandler)
            .build());
}
 
Example #23
Source File: RibbonZuulCommon.java    From s2g-zuul with MIT License 5 votes vote down vote up
protected RestClient getRestClient() throws ZuulException {
		Application application = DiscoveryManager.getInstance().getDiscoveryClient().getApplication(serviceName);
		if (application == null) {
			throw new ZuulException( "Service-NotFoud",HttpServletResponse.SC_NOT_FOUND, serviceName + "服务未找到");
		}
		
		List<DiscoveryEnabledServer> instances = Lists.newArrayList();
		for (InstanceInfo info : application.getInstances()) {
			if (info.getStatus() == InstanceStatus.UP) {
				instances.add(new DiscoveryEnabledServer(info, false, false));
			}
		}

		RestClient client = (RestClient) ClientFactory.getNamedClient(serviceName);
		ZoneAwareLoadBalancer loadbalancer = (ZoneAwareLoadBalancer) client.getLoadBalancer();
		
//		//loadbalancer.setServersList(instances);		
//		IRule rule = new RandomRule();
//		int ruleLoad = ZuulCommandHelper.getLoadBalanceRule(commandGroup, commandKey);
//		if (ruleLoad == 2) {
//			rule = new ClientConfigEnabledRoundRobinRule();
//		} else if (ruleLoad == 3) {
//			rule=new AvailabilityFilteringRule();
//		} else if (ruleLoad == 3) {
//			rule=new ZoneAvoidanceRule();
//		} else if (ruleLoad == 4) {
//			rule=new RetryRule();
//		} else if (ruleLoad == 5) {
//			rule=new RoundRobinRule();
//		}else if (ruleLoad == 6) {
//			rule=new ResponseTimeWeightedRule();
//		}else if (ruleLoad == 7) {
//			rule=new WeightedResponseTimeRule();
//		}
//		loadbalancer.setRule(rule);
//		client.setLoadBalancer(loadbalancer);
		return client;
	}
 
Example #24
Source File: RibbonMarathonClient.java    From spring-cloud-marathon with MIT License 5 votes vote down vote up
@Override
public LBClient create(String clientName) {
    LBClient client = new LBClientFactory.Default().create(clientName);
    IClientConfig config = ClientFactory.getNamedConfig(clientName);
    client.setRetryHandler(new DefaultLoadBalancerRetryHandler(config));
    return client;
}
 
Example #25
Source File: DefaultNIWSServerListFilterTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })    
@Test
public void testZoneExclusivity() throws Exception {
    ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.DeploymentContextBasedVipAddresses", "l10nservicegeneral.cloud.netflix.net:7001");
    ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.NFLoadBalancerClassName", DynamicServerListLoadBalancer.class.getName());
    ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.EnableZoneExclusivity", "true");
    ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName());
    DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("DefaultNIWSServerListFilterTest2");
    ZoneAffinityServerListFilter filter = (ZoneAffinityServerListFilter) lb.getFilter();
    LoadBalancerStats loadBalancerStats = lb.getLoadBalancerStats();
    List<DiscoveryEnabledServer> servers = new ArrayList<DiscoveryEnabledServer>();        
    servers.add(createServer(1, "a"));
    servers.add(createServer(2, "a"));
    servers.add(createServer(3, "a"));
    servers.add(createServer(4, "a"));
    servers.add(createServer(1, "b"));
    servers.add(createServer(2, "b"));
    servers.add(createServer(3, "b"));
    servers.add(createServer(1, "c"));
    servers.add(createServer(2, "c"));
    servers.add(createServer(3, "c"));
    servers.add(createServer(4, "c"));
    servers.add(createServer(5, "c"));
    List<DiscoveryEnabledServer> filtered = filter.getFilteredListOfServers(servers);
    List<DiscoveryEnabledServer> expected = new ArrayList<DiscoveryEnabledServer>();
    expected.add(createServer(1, "c"));
    expected.add(createServer(2, "c"));
    expected.add(createServer(3, "c"));
    expected.add(createServer(4, "c"));
    expected.add(createServer(5, "c"));
    assertEquals(expected, filtered);
    lb.setServersList(filtered);        
    for (int i = 1; i <= 4; i++) {            
        loadBalancerStats.incrementActiveRequestsCount(createServer(i, "c"));
    }
    filtered = filter.getFilteredListOfServers(servers);
    assertEquals(expected, filtered);
}
 
Example #26
Source File: ResponseTimeWeightedRuleTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerWeights(){
    try{
        ConfigurationManager.loadPropertiesFromResources("sample-client.properties"); 

        ConfigurationManager.getConfigInstance().setProperty(
                "sample-client.ribbon.NFLoadBalancerClassName", "com.netflix.loadbalancer.DynamicServerListLoadBalancer");
        ConfigurationManager.getConfigInstance().setProperty(
                "sample-client.ribbon.NFLoadBalancerRuleClassName", "com.netflix.loadbalancer.WeightedResponseTimeRule");
        // shorter weight adjusting interval
        ConfigurationManager.getConfigInstance().setProperty(
                "sample-client.ribbon." + WeightedResponseTimeRule.WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY, "5000");
        ConfigurationManager.getConfigInstance().setProperty(
                "sample-client.ribbon.InitializeNFLoadBalancer", "true");       

        RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client"); 

        HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); 

        for (int i = 0; i < 20; i++) {
            client.executeWithLoadBalancer(request);
        }
        System.out.println(((AbstractLoadBalancer) client.getLoadBalancer()).getLoadBalancerStats());
        // wait for the weights to be adjusted
        Thread.sleep(5000);
        for (int i = 0; i < 50; i++) {
            client.executeWithLoadBalancer(request);
        }
        System.out.println(((AbstractLoadBalancer) client.getLoadBalancer()).getLoadBalancerStats());
    }
    catch (Exception e){
        e.printStackTrace();
    }
}
 
Example #27
Source File: GetPostTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@BeforeClass 
public static void init() throws Exception {
    PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.http", "com.netflix.niws.client");
    int port = (new Random()).nextInt(1000) + 4000;
    SERVICE_URI = "http://localhost:" + port + "/";
    try{
        server = HttpServerFactory.create(SERVICE_URI, resourceConfig);           
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    client = (RestClient) ClientFactory.getNamedClient("GetPostTest");
}
 
Example #28
Source File: PrimeConnectionsTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrimeConnectionsSmallPool() throws Exception {
	Configuration config = ConfigurationManager.getConfigInstance();
	config.setProperty("PrimeConnectionsTest1.ribbon.NFLoadBalancerClassName", 
			com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName());
	config.setProperty("PrimeConnectionsTest1.ribbon.NIWSServerListClassName", SmallFixedServerList.class.getName());
	config.setProperty("PrimeConnectionsTest1.ribbon.EnablePrimeConnections", "true");
	DynamicServerListLoadBalancer<Server> lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("PrimeConnectionsTest1");
	PrimeConnectionEndStats stats = lb.getPrimeConnections().getEndStats();
	assertEquals(stats.success, SMALL_FIXED_SERVER_LIST_SIZE);
}
 
Example #29
Source File: SecureGetTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientRejectsWrongServer() throws Exception{

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = "GetPostSecureTest" + ".testClientRejectsWrongServer";

	String configPrefix = name + "." + "ribbon";

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath()); // <--
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);

	RestClient rc = (RestClient) ClientFactory.getNamedClient(name);

	testServer2.accept();

	URI getUri = new URI(SERVICE_URI2 + "test/");
	HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
	try{
		rc.execute(request);

		fail("expecting ssl hostname validation error");

	}catch(ClientHandlerException che){
		assertTrue(che.getMessage().indexOf("peer not authenticated") > -1);
	}
}
 
Example #30
Source File: SecureAcceptAllGetTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testNegativeAcceptAllSSLSocketFactoryCannotWorkWithTrustStore() throws Exception{

    // test config exception happens before we even try to connect to anything

    AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

    String name = "GetPostSecureTest." + testName.getMethodName();

    String configPrefix = name + "." + "ribbon";

    cm.setProperty(configPrefix + "." + CommonClientConfigKey.CustomSSLSocketFactoryClassName, "com.netflix.http4.ssl.AcceptAllSocketFactory");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, TEST_FILE_TS.getAbsolutePath());
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD);

    boolean foundCause = false;

    try {
        ClientFactory.getNamedClient(name);
    } catch(Throwable t){
         while (t != null && ! foundCause){
             if (t instanceof IllegalArgumentException && t.getMessage().startsWith("Invalid value for property:CustomSSLSocketFactoryClassName")){
                 foundCause = true;
                 break;
             }
             t = t.getCause();
         }
    }

    assertTrue(foundCause);
}