com.netflix.client.http.HttpRequest Java Examples

The following examples show how to use com.netflix.client.http.HttpRequest. 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: ElasticSearchSink.java    From suro with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected Pair<HttpRequest, List<Message>> createBulkRequest(List<Message> msgList) {
    List<Message> msgListPayload = new LinkedList<>();
    StringBuilder sb = new StringBuilder();
    for (Message m : msgList) {
        String indexRequest = createIndexRequest(m);
        if (indexRequest != null) {
            sb.append(indexRequest);
            msgListPayload.add(m);
        }
    }

    return new Pair<>(
        HttpRequest.newBuilder()
            .verb(HttpRequest.Verb.POST)
            .uri("/_bulk")
            .setRetriable(true)
            .entity(sb.toString()).build(),
        msgListPayload);
}
 
Example #2
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 #3
Source File: RestClient.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
protected Pair<String, Integer> deriveSchemeAndPortFromPartialUri(HttpRequest task) {
    URI theUrl = task.getUri();
    boolean isSecure = getBooleanFromConfig(task.getOverrideConfig(), CommonClientConfigKey.IsSecure, this.isSecure);
    String scheme = theUrl.getScheme();
    if (scheme != null) {
        isSecure = 	scheme.equalsIgnoreCase("https");
    }
    int port = theUrl.getPort();
    if (port < 0 && !isSecure){
        port = 80;
    } else if (port < 0 && isSecure){
        port = 443;
    }
    if (scheme == null){
        if (isSecure) {
            scheme = "https";
        } else {
            scheme = "http";
        }
    }
    return new Pair<String, Integer>(scheme, port);
}
 
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: RetryTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testThrottledWithRetryNextServer() throws Exception {
    int connectionCount = connectionPoolManager.getConnectionsInPool();
    URI localUrl = new URI("/status?code=503");
    HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
    try {
        client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
        fail("Exception expected");
    } catch (ClientException e) { // NOPMD
    }
    assertEquals(3, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());
    System.out.println("Initial connections count " + connectionCount);
    System.out.println("Final connections count " + connectionPoolManager.getConnectionsInPool());
    // should be no connection leak        
    assertTrue(connectionPoolManager.getConnectionsInPool() <= connectionCount + 1);
}
 
Example #6
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 #7
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 #8
Source File: RetryTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulRetries() throws Exception {
    lb.setServersList(Lists.newArrayList(new Server("localhost:12987"), new Server("localhost:12987"), localServer));
    URI localUrl = new URI("/ok");
    HttpRequest request = HttpRequest.newBuilder().uri(localUrl).queryParams("name", "ribbon").build();
    try {
        HttpResponse response = client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
        assertEquals(200, response.getStatus());
    } catch (ClientException e) { 
        fail("Unexpected exception");
    }
    ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(new Server("localhost:12987")); 
    assertEquals(1, stats.getSuccessiveConnectionFailureCount());
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: RetryTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetriesOnPost() throws Exception {
    URI localUrl = new URI("/noresponse");
    HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).setRetriable(true).build();
    try {
        client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
        fail("Exception expected");
    } catch (ClientException e) { // NOPMD
    }
    ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(localServer); 
    assertEquals(3, stats.getSuccessiveConnectionFailureCount());
}
 
Example #16
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 #17
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 #18
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 #19
Source File: ManyShortLivedRequestsSurvivorTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void survive() throws IOException, ClientException, URISyntaxException, InterruptedException {

    String clientName = "RibbonClientTest-loadBalancingDefaultPolicyRoundRobin";
    String serverListKey = clientName + ".ribbon.listOfServers";
    int nbHitsPerServer = 60;
    MockWebServer server1 = new MockWebServer();
    MockWebServer server2 = new MockWebServer();

    for (int i = 0; i < nbHitsPerServer; i++) {
        server1.enqueue(new MockResponse().setResponseCode(200).setBody("server1 success <" + i + ">!"));
        server2.enqueue(new MockResponse().setResponseCode(200).setBody("server2 success <" + i + ">!"));
    }

    server1.play();
    server2.play();

    getConfigInstance().setProperty(serverListKey, hostAndPort(server1.getUrl("")) + "," + hostAndPort(server2.getUrl("")));

    RestClient client = (RestClient) ClientFactory.getNamedClient(clientName);
    HttpRequest request;
    for (int i = 0; i < nbHitsPerServer * 2; i++) {
        request = HttpRequest.newBuilder().uri(new URI("/")).build();
        HttpResponse response = client.executeWithLoadBalancer(request);
        response.close();
    }
}
 
Example #20
Source File: ElasticSearchSink.java    From suro with Apache License 2.0 5 votes vote down vote up
public void recover(Message message) {
    IndexInfo info = indexInfo.create(message);

    HttpResponse response = null;
    try {
        response = client.executeWithLoadBalancer(
            HttpRequest.newBuilder()
                .verb(HttpRequest.Verb.POST)
                .setRetriable(true)
                .uri(indexInfo.getIndexUri(info))
                .entity(indexInfo.getSource(info))
                .build());
        if (response.getStatus() / 100 != 2) {
            Servo.getCounter(
                MonitorConfig.builder("unrecoverableRow")
                    .withTag(SINK_ID, getSinkId())
                    .withTag(TagKey.ROUTING_KEY, message.getRoutingKey())
                    .build()).increment();
        }
    } catch (Exception e) {
        log.error("Exception while recover: " + e.getMessage(), e);
        Servo.getCounter("recoverException").increment();
        if (reEnqueueOnException) {
            writeTo(new DefaultMessageContainer(message, jsonMapper));
        } else {
            Servo.getCounter(
                    MonitorConfig.builder("unrecoverableRow")
                            .withTag(SINK_ID, getSinkId())
                            .withTag(TagKey.ROUTING_KEY, message.getRoutingKey())
                            .build()).increment();
        }
    } finally {
        if (response != null) {
            response.close();
        }
    }

}
 
Example #21
Source File: RibbonRequestCommandForThreadIsolation.java    From s2g-zuul with MIT License 5 votes vote down vote up
public RibbonRequestCommandForThreadIsolation(AbstractLoadBalancerAwareClient client,HttpRequest request, String serviceName, String commandGroup,
		String commandKey, String threadPoolKey) {
	super(client,request, serviceName, commandGroup, commandKey,
			Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandGroup))
					.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
					.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(threadPoolKey))
					.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(
							HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)));

}
 
Example #22
Source File: RibbonRequestCommandForSemaphoreIsolation.java    From s2g-zuul with MIT License 5 votes vote down vote up
public RibbonRequestCommandForSemaphoreIsolation(AbstractLoadBalancerAwareClient client,HttpRequest request, String serviceName, String commandGroup,
		String commandKey) {
	super(client,request, serviceName, commandGroup, commandKey,
			Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandGroup))
					.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
					.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(
							HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)));
}
 
Example #23
Source File: RibbonZuulCommon.java    From s2g-zuul with MIT License 5 votes vote down vote up
public RibbonZuulCommon(AbstractLoadBalancerAwareClient client,HttpRequest request,String serviceName, String commandGroup, String commandKey,Setter setter) {
	super(setter);
	this.commandKey = commandKey;
	this.commandGroup = commandGroup;
	this.serviceName = serviceName;
	this.request = request;
	this.client = client;
}
 
Example #24
Source File: RestClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Override
public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
        HttpRequest request, IClientConfig requestConfig) {
    if (!request.isRetriable()) {
        return new RequestSpecificRetryHandler(false, false, this.getRetryHandler(), requestConfig);
    }
    if (this.ncc.get(CommonClientConfigKey.OkToRetryOnAllOperations, false)) {
        return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), requestConfig);
    }
    if (request.getVerb() != HttpRequest.Verb.GET) {
        return new RequestSpecificRetryHandler(true, false, this.getRetryHandler(), requestConfig);
    } else {
        return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), requestConfig);
    } 
}
 
Example #25
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 #26
Source File: GetPostTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testGet() throws Exception {
	URI getUri = new URI(SERVICE_URI + "test/getObject");
	MultivaluedMapImpl params = new MultivaluedMapImpl();
	params.add("name", "test");
	HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
	HttpResponse response = client.execute(request);
	assertEquals(200, response.getStatus());
	assertTrue(response.getEntity(TestObject.class).name.equals("test"));
}
 
Example #27
Source File: GetPostTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testPost() throws Exception {
	URI getUri = new URI(SERVICE_URI + "test/setObject");
	TestObject obj = new TestObject();
	obj.name = "fromClient";
	HttpRequest request = HttpRequest.newBuilder().verb(Verb.POST).uri(getUri).entity(obj).build();
	HttpResponse response = client.execute(request);
	assertEquals(200, response.getStatus());
	assertTrue(response.getEntity(TestObject.class).name.equals("fromClient"));
}
 
Example #28
Source File: GetPostTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testChunkedEncoding() throws Exception {
    String obj = "chunked encoded content";
	URI postUri = new URI(SERVICE_URI + "test/postStream");
	InputStream input = new ByteArrayInputStream(obj.getBytes("UTF-8"));
	HttpRequest request = HttpRequest.newBuilder().verb(Verb.POST).uri(postUri).entity(input).build();
	HttpResponse response = client.execute(request);
	assertEquals(200, response.getStatus());
	assertTrue(response.getEntity(String.class).equals(obj));
}
 
Example #29
Source File: RetryTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrottled() throws Exception {
    URI localUrl = new URI("/status?code=503");
    HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
    try {
        client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 0));
        fail("Exception expected");
    } catch (ClientException e) {
        assertNotNull(e);
    }
    assertEquals(1, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());        
}
 
Example #30
Source File: RetryTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrottledWithRetrySameServer() throws Exception {
    URI localUrl = new URI("/status?code=503");
    HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
    try {
        client.executeWithLoadBalancer(request, 
                DefaultClientConfigImpl
                .getEmptyConfig()
                .set(CommonClientConfigKey.MaxAutoRetries, 1)
                .set(CommonClientConfigKey.MaxAutoRetriesNextServer, 0));
        fail("Exception expected");
    } catch (ClientException e) { // NOPMD
    }
    assertEquals(2, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());        
}