Java Code Examples for com.netflix.client.ClientFactory#getNamedClient()

The following examples show how to use com.netflix.client.ClientFactory#getNamedClient() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 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: 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 12
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 13
Source File: SecureGetTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testSunnyDay() throws Exception {

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

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

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

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer1.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
	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/");
       HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
	HttpResponse response = rc.execute(request);
	assertEquals(200, response.getStatus());
}
 
Example 14
Source File: SecureAcceptAllGetTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testNegativeAcceptAllSSLSocketFactory() throws Exception{

    // test exception is thrown connecting to a random SSL endpoint without explicitly setting factory to allow all

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

    // don't set any interesting properties -- really we're just setting the defaults

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

    TEST_SERVER.accept();

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

    boolean foundCause = false;

    try {
        rc.execute(request);
    } catch(Throwable t){
        while (t != null && ! foundCause){
            if (t instanceof SSLPeerUnverifiedException && t.getMessage().startsWith("peer not authenticated")){
                foundCause = true;
                break;
            }
            t = t.getCause();
        }
    }

    assertTrue(foundCause);
}
 
Example 15
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);
}
 
Example 16
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 17
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 18
Source File: SecureAcceptAllGetTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testPositiveAcceptAllSSLSocketFactory() throws Exception{

    // test connection succeeds connecting to a random SSL endpoint with allow all SSL factory

    AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

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

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

    cm.setProperty(configPrefix + "." + CommonClientConfigKey.CustomSSLSocketFactoryClassName, "com.netflix.http4.ssl.AcceptAllSocketFactory");

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

    TEST_SERVER.accept();

    URI getUri = new URI(TEST_SERVICE_URI + "test/");
    HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
    HttpResponse response = rc.execute(request);
    assertEquals(200, response.getStatus());
}
 
Example 19
Source File: SecureRestClientKeystoreTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetKeystoreWithNoClientAuth() throws Exception{

	// jks format
	byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
	byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);

	File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
	File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");

	FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
       try {
           keystoreFileOut.write(dummyKeystore);
       } finally {
           keystoreFileOut.close();
       }

	FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
       try {
           truststoreFileOut.write(dummyTruststore);
       } finally {
           truststoreFileOut.close();
       }

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = this.getClass().getName() + ".test2";

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

	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.KeyStorePassword, "changeit");

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

	KeyStore keyStore = client.getKeyStore();

	Certificate cert = keyStore.getCertificate("ribbon_key");

	assertNotNull(cert);
}
 
Example 20
Source File: SecureRestClientKeystoreTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetKeystoreWithClientAuth() throws Exception{

	// jks format
	byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
	byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);

	File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
	File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");

	FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
       try {
           keystoreFileOut.write(dummyKeystore);
       } finally {
           keystoreFileOut.close();
       }

	FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
       try {
           truststoreFileOut.write(dummyTruststore);
       } finally {
           truststoreFileOut.close();
       }

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = this.getClass().getName() + ".test1";

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

	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.IsClientAuthRequired, "true");
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.KeyStorePassword, "changeit");
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.TrustStore, tempTruststore.getAbsolutePath());
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.TrustStorePassword, "changeit");

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

	KeyStore keyStore = client.getKeyStore();

	Certificate cert = keyStore.getCertificate("ribbon_key");

	assertNotNull(cert);

}