From 822e48119cb3b866db4fbd98bcccfe3ccea2b1ab Mon Sep 17 00:00:00 2001 From: Josh Gordineer Date: Tue, 14 Nov 2023 12:31:18 -0800 Subject: [PATCH] remove guava --- gradle.properties | 1 - ribbon-archaius/build.gradle | 1 - ribbon-core/build.gradle | 1 - .../DefaultLoadBalancerRetryHandler.java | 9 ++-- .../client/RequestSpecificRetryHandler.java | 13 +++-- .../client/config/CommonClientConfigKey.java | 16 +++--- .../client/config/ReloadableClientConfig.java | 10 ++-- .../client/ssl/URLSslContextFactory.java | 20 ++++--- .../com/netflix/client/util/ThreadUtils.java | 16 ++++++ .../config/CommonClientConfigKeyTest.java | 6 ++- .../EurekaNotificationServerListUpdater.java | 19 +++---- ...rekaNotificationServerListUpdaterTest.java | 12 ++--- .../niws/loadbalancer/LBBuilderTest.java | 12 +++-- ribbon-examples/build.gradle | 1 - .../URLConnectionLoadBalancer.java | 8 +-- .../netty/http/LoadBalancingExample.java | 6 ++- .../examples/server/ServerResources.java | 6 +-- ribbon-httpclient/build.gradle | 2 +- .../client/http/CaseInsensitiveMultiMap.java | 52 ++++++++----------- .../com/netflix/client/http/HttpRequest.java | 17 +++--- .../com/netflix/client/http/HttpResponse.java | 7 --- .../http4/MonitoredConnectionManager.java | 3 -- .../java/com/netflix/http4/NFHttpClient.java | 7 ++- .../netflix/http4/NamedConnectionPool.java | 4 +- .../HttpClientLoadBalancerErrorHandler.java | 27 +++++----- .../niws/client/http/HttpClientResponse.java | 30 +++-------- .../java/com/netflix/utils/MultiMapUtil.java | 23 ++++++++ .../netflix/niws/client/http/RetryTest.java | 15 +++--- ribbon-loadbalancer/build.gradle | 3 +- .../loadbalancer/AbstractServerPredicate.java | 39 +++++++------- .../AvailabilityFilteringRule.java | 5 +- .../loadbalancer/AvailabilityPredicate.java | 3 +- .../loadbalancer/BaseLoadBalancer.java | 7 ++- .../loadbalancer/CompositePredicate.java | 19 +++---- .../ConfigurationBasedServerList.java | 6 +-- .../DynamicServerListLoadBalancer.java | 2 - .../loadbalancer/LoadBalancerContext.java | 2 +- .../loadbalancer/LoadBalancerStats.java | 42 +++++---------- .../PollingServerListUpdater.java | 10 ++-- .../loadbalancer/PredicateBasedRule.java | 2 +- .../loadbalancer/ServerListSubsetFilter.java | 22 +++----- .../com/netflix/loadbalancer/ServerStats.java | 12 +---- .../loadbalancer/ZoneAffinityPredicate.java | 2 +- .../ZoneAffinityServerListFilter.java | 8 +-- .../loadbalancer/ZoneAvoidancePredicate.java | 2 +- .../loadbalancer/ZoneAwareLoadBalancer.java | 6 +-- .../client/testutil/MockHttpServer.java | 6 ++- .../loadbalancer/BestAvailableRuleTest.java | 5 +- .../netflix/loadbalancer/MockServerList.java | 4 +- .../netflix/loadbalancer/PredicatesTest.java | 50 ++++++++---------- .../loadbalancer/SubsetFilterTest.java | 7 +-- ribbon-test/build.gradle | 4 +- .../test/resources/EmbeddedResources.java | 7 ++- .../netflix/serialization/JacksonCodec.java | 4 +- .../serialization/SerializationUtils.java | 9 ++-- .../serialization/StringDeserializer.java | 4 +- ribbon-transport/build.gradle | 1 - .../transport/netty/RibbonTransport.java | 6 +-- .../netty/http/LoadBalancingHttpClient.java | 10 ++-- .../NettyHttpLoadBalancerErrorHandler.java | 20 ++++--- .../transport/netty/http/NettyClientTest.java | 5 +- .../netty/http/ServerListRefreshTest.java | 7 +-- ribbon/build.gradle | 1 - .../ribbon/template/TemplateParser.java | 5 +- 64 files changed, 325 insertions(+), 366 deletions(-) create mode 100644 ribbon-core/src/main/java/com/netflix/client/util/ThreadUtils.java create mode 100644 ribbon-httpclient/src/main/java/com/netflix/utils/MultiMapUtil.java diff --git a/gradle.properties b/gradle.properties index c4acbb672..44dcf7660 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,7 +2,6 @@ rx_java_version=1.0.9 rx_netty_version=0.4.9 servo_version=0.10.1 hystrix_version=1.4.3 -guava_version=19.0 archaius_version=0.7.6 eureka_version=1.7.2 jersey_version=1.19.1 diff --git a/ribbon-archaius/build.gradle b/ribbon-archaius/build.gradle index 519148905..f161e8699 100644 --- a/ribbon-archaius/build.gradle +++ b/ribbon-archaius/build.gradle @@ -1,7 +1,6 @@ dependencies { api "org.slf4j:slf4j-api:${slf4j_version}" api 'com.google.code.findbugs:annotations:2.0.0' - api "com.google.guava:guava:${guava_version}" api 'commons-configuration:commons-configuration:1.8' api 'commons-lang:commons-lang:2.6' api "com.netflix.archaius:archaius-core:${archaius_version}" diff --git a/ribbon-core/build.gradle b/ribbon-core/build.gradle index ab5b7c1af..a79c770c4 100644 --- a/ribbon-core/build.gradle +++ b/ribbon-core/build.gradle @@ -1,7 +1,6 @@ dependencies { api "org.slf4j:slf4j-api:${slf4j_version}" api 'com.google.code.findbugs:annotations:2.0.0' - api "com.google.guava:guava:${guava_version}" api 'commons-lang:commons-lang:2.6' testImplementation 'junit:junit:4.11' diff --git a/ribbon-core/src/main/java/com/netflix/client/DefaultLoadBalancerRetryHandler.java b/ribbon-core/src/main/java/com/netflix/client/DefaultLoadBalancerRetryHandler.java index 3b902e3b0..ef0d1d60c 100644 --- a/ribbon-core/src/main/java/com/netflix/client/DefaultLoadBalancerRetryHandler.java +++ b/ribbon-core/src/main/java/com/netflix/client/DefaultLoadBalancerRetryHandler.java @@ -17,13 +17,14 @@ */ package com.netflix.client; -import com.google.common.collect.Lists; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -36,12 +37,12 @@ public class DefaultLoadBalancerRetryHandler implements RetryHandler { @SuppressWarnings("unchecked") - private List> retriable = - Lists.>newArrayList(ConnectException.class, SocketTimeoutException.class); + private List> retriable = + new ArrayList<>(Arrays.asList(ConnectException.class, SocketTimeoutException.class)); @SuppressWarnings("unchecked") private List> circuitRelated = - Lists.>newArrayList(SocketException.class, SocketTimeoutException.class); + new ArrayList<>(Arrays.asList(SocketException.class, SocketTimeoutException.class)); protected final int retrySameServer; protected final int retryNextServer; diff --git a/ribbon-core/src/main/java/com/netflix/client/RequestSpecificRetryHandler.java b/ribbon-core/src/main/java/com/netflix/client/RequestSpecificRetryHandler.java index 8d3fab65e..e1957e937 100644 --- a/ribbon-core/src/main/java/com/netflix/client/RequestSpecificRetryHandler.java +++ b/ribbon-core/src/main/java/com/netflix/client/RequestSpecificRetryHandler.java @@ -1,14 +1,13 @@ package com.netflix.client; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; -import javax.annotation.Nullable; +import java.util.Collections; +import java.util.Objects; import java.net.SocketException; import java.util.List; -import java.util.Optional; +import javax.annotation.Nullable; /** * Implementation of RetryHandler created for each request which allows for request @@ -22,15 +21,15 @@ public class RequestSpecificRetryHandler implements RetryHandler { private final boolean okToRetryOnConnectErrors; private final boolean okToRetryOnAllErrors; - protected List> connectionRelated = - Lists.>newArrayList(SocketException.class); + protected List> connectionRelated = + Collections.singletonList(SocketException.class); public RequestSpecificRetryHandler(boolean okToRetryOnConnectErrors, boolean okToRetryOnAllErrors) { this(okToRetryOnConnectErrors, okToRetryOnAllErrors, RetryHandler.DEFAULT, null); } public RequestSpecificRetryHandler(boolean okToRetryOnConnectErrors, boolean okToRetryOnAllErrors, RetryHandler baseRetryHandler, @Nullable IClientConfig requestConfig) { - Preconditions.checkNotNull(baseRetryHandler); + Objects.requireNonNull(baseRetryHandler); this.okToRetryOnConnectErrors = okToRetryOnConnectErrors; this.okToRetryOnAllErrors = okToRetryOnAllErrors; this.fallback = baseRetryHandler; diff --git a/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java b/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java index 6c7bc18fb..c8edf054c 100644 --- a/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java +++ b/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java @@ -17,8 +17,6 @@ */ package com.netflix.client.config; -import com.google.common.reflect.TypeToken; - import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; @@ -28,8 +26,6 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import static com.google.common.base.Preconditions.checkArgument; - public abstract class CommonClientConfigKey implements IClientConfigKey { public static final String DEFAULT_NAME_SPACE = "ribbon"; @@ -248,20 +244,20 @@ public Class type() { private final String configKey; private final Class type; - private T defaultValue; + private final T defaultValue; - @SuppressWarnings("unchecked") protected CommonClientConfigKey(String configKey) { this(configKey, null); } + @SuppressWarnings("unchecked") protected CommonClientConfigKey(String configKey, T defaultValue) { this.configKey = configKey; Type superclass = getClass().getGenericSuperclass(); - checkArgument(superclass instanceof ParameterizedType, - "%s isn't parameterized", superclass); - Type runtimeType = ((ParameterizedType) superclass).getActualTypeArguments()[0]; - type = (Class) TypeToken.of(runtimeType).getRawType(); + if (!(superclass instanceof ParameterizedType)) { + throw new IllegalArgumentException(superclass + " isn't parameterized"); + } + this.type = (Class) ((ParameterizedType) superclass).getActualTypeArguments()[0]; this.defaultValue = defaultValue; } diff --git a/ribbon-core/src/main/java/com/netflix/client/config/ReloadableClientConfig.java b/ribbon-core/src/main/java/com/netflix/client/config/ReloadableClientConfig.java index c712ad85e..278e7def3 100644 --- a/ribbon-core/src/main/java/com/netflix/client/config/ReloadableClientConfig.java +++ b/ribbon-core/src/main/java/com/netflix/client/config/ReloadableClientConfig.java @@ -1,6 +1,6 @@ package com.netflix.client.config; -import com.google.common.base.Preconditions; +import java.util.Objects; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -159,7 +159,7 @@ interface ReloadableProperty extends Property { } private synchronized Property getOrCreateProperty(final IClientConfigKey key, final Supplier> valueSupplier, final Supplier defaultSupplier) { - Preconditions.checkNotNull(valueSupplier, "defaultValueSupplier cannot be null"); + Objects.requireNonNull(valueSupplier, "defaultValueSupplier cannot be null"); return (Property)dynamicProperties.computeIfAbsent(key, ignore -> new ReloadableProperty() { private volatile Optional current = Optional.empty(); @@ -355,7 +355,7 @@ protected final void setDefault(IClientConfigKey key) { * Store the default value for key while giving precedence to default values in the property resolver */ protected final void setDefault(IClientConfigKey key, T value) { - Preconditions.checkArgument(key != null, "key cannot be null"); + Objects.requireNonNull(key, "key cannot be null"); value = resolveFromPropertyResolver(key).orElse(value); internalProperties.put(key, Optional.ofNullable(value)); @@ -367,7 +367,7 @@ protected final void setDefault(IClientConfigKey key, T value) { @Override public IClientConfig set(IClientConfigKey key, T value) { - Preconditions.checkArgument(key != null, "key cannot be null"); + Objects.requireNonNull(key, "key cannot be null"); value = resolveValueToType(key, value); if (isDynamic) { @@ -384,7 +384,7 @@ public IClientConfig set(IClientConfigKey key, T value) { @Override @Deprecated public void setProperty(IClientConfigKey key, Object value) { - Preconditions.checkArgument(value != null, "Value may not be null"); + Objects.requireNonNull(value, "Value may not be null"); set(key, value); } diff --git a/ribbon-core/src/main/java/com/netflix/client/ssl/URLSslContextFactory.java b/ribbon-core/src/main/java/com/netflix/client/ssl/URLSslContextFactory.java index f9ead162b..a314da53d 100644 --- a/ribbon-core/src/main/java/com/netflix/client/ssl/URLSslContextFactory.java +++ b/ribbon-core/src/main/java/com/netflix/client/ssl/URLSslContextFactory.java @@ -29,9 +29,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; - /** * Secure socket factory that is used the NIWS code if a non-standard key store or trust store * is specified. @@ -100,8 +97,11 @@ private static KeyStore createKeyStore(final URL storeFile, final String passwor if(storeFile == null){ return null; } - - Preconditions.checkArgument(StringUtils.isNotEmpty(password), "Null keystore should have empty password, defined keystore must have password"); + + if (StringUtils.isEmpty(password)) { + throw new IllegalArgumentException( + "Null keystore should have empty password, defined keystore must have password"); + } KeyStore keyStore = null; @@ -139,13 +139,17 @@ public String toString() { builder.append("ClientSslSocketFactory [trustStoreUrl=").append(trustStoreUrl); if (trustStoreUrl != null) { - builder.append(", trustStorePassword="); - builder.append(Strings.repeat("*", this.getTrustStorePasswordLength())); + builder.append(", trustStorePassword="); + for (int i = 0; i < this.getTrustStorePasswordLength(); i++) { + builder.append("*"); + } } builder.append(", keyStoreUrl=").append(keyStoreUrl); if (keyStoreUrl != null) { builder.append(", keystorePassword = "); - builder.append(Strings.repeat("*", this.getKeyStorePasswordLength())); + for (int i = 0; i < this.getKeyStorePasswordLength(); i++) { + builder.append("*"); + } } builder.append(']'); diff --git a/ribbon-core/src/main/java/com/netflix/client/util/ThreadUtils.java b/ribbon-core/src/main/java/com/netflix/client/util/ThreadUtils.java new file mode 100644 index 000000000..7ee22e1b5 --- /dev/null +++ b/ribbon-core/src/main/java/com/netflix/client/util/ThreadUtils.java @@ -0,0 +1,16 @@ +package com.netflix.client.util; + +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; + +public class ThreadUtils { + + public static ThreadFactory threadFactory(String name) { + return r -> { + Thread thread = Executors.defaultThreadFactory().newThread(r); + thread.setName(name); + thread.setDaemon(true); + return thread; + }; + } +} diff --git a/ribbon-core/src/test/java/com/netflix/client/config/CommonClientConfigKeyTest.java b/ribbon-core/src/test/java/com/netflix/client/config/CommonClientConfigKeyTest.java index 335d0e597..426972d5f 100644 --- a/ribbon-core/src/test/java/com/netflix/client/config/CommonClientConfigKeyTest.java +++ b/ribbon-core/src/test/java/com/netflix/client/config/CommonClientConfigKeyTest.java @@ -2,9 +2,11 @@ import static org.junit.Assert.*; + import org.junit.Test; -import com.google.common.collect.Sets; +import java.util.Arrays; +import java.util.HashSet; public class CommonClientConfigKeyTest { @@ -12,7 +14,7 @@ public class CommonClientConfigKeyTest { public void testCommonKeys() { IClientConfigKey[] keys = CommonClientConfigKey.values(); assertTrue(keys.length > 30); - assertEquals(Sets.newHashSet(keys), CommonClientConfigKey.keys()); + assertEquals(new HashSet<>(Arrays.asList(keys)), CommonClientConfigKey.keys()); assertTrue(CommonClientConfigKey.keys().contains(CommonClientConfigKey.ConnectTimeout)); } } diff --git a/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdater.java b/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdater.java index 2b388db7c..2031f08e4 100644 --- a/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdater.java +++ b/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdater.java @@ -1,6 +1,7 @@ package com.netflix.niws.loadbalancer; -import com.google.common.util.concurrent.ThreadFactoryBuilder; +import static com.netflix.client.util.ThreadUtils.threadFactory; + import com.netflix.config.DynamicIntProperty; import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.EurekaClient; @@ -45,16 +46,12 @@ private static class LazyHolder { private LazyHolder() { int corePoolSize = getCorePoolSize(); defaultServerListUpdateExecutor = new ThreadPoolExecutor( - corePoolSize, - corePoolSize * 5, - 0, - TimeUnit.NANOSECONDS, - new ArrayBlockingQueue(queueSizeProp.get()), - new ThreadFactoryBuilder() - .setNameFormat("EurekaNotificationServerListUpdater-%d") - .setDaemon(true) - .build() - ); + corePoolSize, + corePoolSize * 5, + 0, + TimeUnit.NANOSECONDS, + new ArrayBlockingQueue(queueSizeProp.get()), + threadFactory("EurekaNotificationServerListUpdater-%d")); poolSizeProp.addCallback(new Runnable() { @Override diff --git a/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdaterTest.java b/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdaterTest.java index f700a9a50..94e35b7d8 100644 --- a/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdaterTest.java +++ b/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdaterTest.java @@ -1,10 +1,13 @@ package com.netflix.niws.loadbalancer; -import com.google.common.util.concurrent.ThreadFactoryBuilder; +import static com.netflix.client.util.ThreadUtils.threadFactory; + import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaEventListener; import com.netflix.loadbalancer.ServerListUpdater; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Assert; @@ -12,7 +15,6 @@ import org.junit.Test; import javax.inject.Provider; -import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionException; @@ -42,11 +44,7 @@ public void setUp() { 0, TimeUnit.NANOSECONDS, new ArrayBlockingQueue(1000), - new ThreadFactoryBuilder() - .setNameFormat("EurekaNotificationServerListUpdater-%d") - .setDaemon(true) - .build() - ); + threadFactory("EurekaNotificationServerListUpdater-%d")); } @Test diff --git a/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LBBuilderTest.java b/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LBBuilderTest.java index 7be0c3d8d..f6308296f 100644 --- a/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LBBuilderTest.java +++ b/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LBBuilderTest.java @@ -1,6 +1,5 @@ package com.netflix.niws.loadbalancer; -import com.google.common.collect.Lists; import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; @@ -23,6 +22,9 @@ import com.netflix.loadbalancer.ServerListUpdater; import com.netflix.loadbalancer.ZoneAffinityServerListFilter; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.configuration.Configuration; import org.junit.Before; import org.junit.Ignore; @@ -90,7 +92,7 @@ public void testBuildWithDiscoveryEnabledNIWSServerList() { .withServerListFilter(filter) .buildDynamicServerListLoadBalancer(); assertNotNull(lb); - assertEquals(Lists.newArrayList(expected), lb.getAllServers()); + assertEquals(Collections.singletonList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); Server server = lb.chooseServer(); @@ -111,7 +113,7 @@ public void testBuildWithDiscoveryEnabledNIWSServerListAndUpdater() { .withServerListUpdater(updater) .buildDynamicServerListLoadBalancerWithUpdater(); assertNotNull(lb); - assertEquals(Lists.newArrayList(expected), lb.getAllServers()); + assertEquals(Collections.singletonList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); assertSame(updater, lb.getServerListUpdater()); @@ -139,12 +141,12 @@ public void testBuildWithArchaiusProperties() { assertTrue(dynamicLB.getFilter() instanceof ZoneAffinityServerListFilter); assertTrue(dynamicLB.getRule() instanceof RoundRobinRule); assertTrue(dynamicLB.getPing() instanceof DummyPing); - assertEquals(Lists.newArrayList(expected), lb.getAllServers()); + assertEquals(Collections.singletonList(expected), lb.getAllServers()); } @Test public void testBuildStaticServerListLoadBalancer() { - List list = Lists.newArrayList(expected, expected); + List list = new ArrayList<>(Arrays.asList(expected, expected)); IRule rule = new AvailabilityFilteringRule(); IClientConfig clientConfig = IClientConfig.Builder.newBuilder() .withDefaultValues() diff --git a/ribbon-examples/build.gradle b/ribbon-examples/build.gradle index e885de9ed..202074c1f 100644 --- a/ribbon-examples/build.gradle +++ b/ribbon-examples/build.gradle @@ -12,7 +12,6 @@ dependencies { api 'org.codehaus.jackson:jackson-mapper-asl:1.9.11' api 'com.thoughtworks.xstream:xstream:1.4.5' api "com.sun.jersey:jersey-server:${jersey_version}" - api "com.google.guava:guava:${guava_version}" api "com.netflix.archaius:archaius-core:${archaius_version}" testImplementation 'junit:junit:4.11' } diff --git a/ribbon-examples/src/main/java/com/netflix/ribbon/examples/loadbalancer/URLConnectionLoadBalancer.java b/ribbon-examples/src/main/java/com/netflix/ribbon/examples/loadbalancer/URLConnectionLoadBalancer.java index bc27d2cc5..eec96881a 100644 --- a/ribbon-examples/src/main/java/com/netflix/ribbon/examples/loadbalancer/URLConnectionLoadBalancer.java +++ b/ribbon-examples/src/main/java/com/netflix/ribbon/examples/loadbalancer/URLConnectionLoadBalancer.java @@ -3,11 +3,12 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import rx.Observable; -import com.google.common.collect.Lists; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.RetryHandler; import com.netflix.loadbalancer.BaseLoadBalancer; @@ -57,10 +58,11 @@ public LoadBalancerStats getLoadBalancerStats() { } public static void main(String[] args) throws Exception { - URLConnectionLoadBalancer urlLoadBalancer = new URLConnectionLoadBalancer(Lists.newArrayList( + URLConnectionLoadBalancer urlLoadBalancer = new URLConnectionLoadBalancer(new ArrayList<>( + Arrays.asList( new Server("www.google.com", 80), new Server("www.linkedin.com", 80), - new Server("www.yahoo.com", 80))); + new Server("www.yahoo.com", 80)))); for (int i = 0; i < 6; i++) { System.out.println(urlLoadBalancer.call("/")); } diff --git a/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty/http/LoadBalancingExample.java b/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty/http/LoadBalancingExample.java index 8d219c4bf..ce292eda8 100644 --- a/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty/http/LoadBalancingExample.java +++ b/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty/http/LoadBalancingExample.java @@ -4,12 +4,13 @@ import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import rx.Observer; -import com.google.common.collect.Lists; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import com.netflix.loadbalancer.BaseLoadBalancer; @@ -19,7 +20,8 @@ public class LoadBalancingExample { public static void main(String[] args) throws Exception { - List servers = Lists.newArrayList(new Server("www.google.com:80"), new Server("www.examples.com:80"), new Server("www.wikipedia.org:80")); + List servers = new ArrayList<>( + Arrays.asList(new Server("www.google.com:80"), new Server("www.examples.com:80"), new Server("www.wikipedia.org:80"))); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder() .buildFixedServerListLoadBalancer(servers); diff --git a/ribbon-examples/src/main/java/com/netflix/ribbon/examples/server/ServerResources.java b/ribbon-examples/src/main/java/com/netflix/ribbon/examples/server/ServerResources.java index 2ca21c406..bb18a71b2 100644 --- a/ribbon-examples/src/main/java/com/netflix/ribbon/examples/server/ServerResources.java +++ b/ribbon-examples/src/main/java/com/netflix/ribbon/examples/server/ServerResources.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.util.ArrayList; import java.util.List; import javax.ws.rs.Consumes; @@ -34,7 +35,6 @@ import org.codehaus.jackson.map.ObjectMapper; -import com.google.common.collect.Lists; import com.thoughtworks.xstream.XStream; @Path("/testAsync") @@ -89,9 +89,9 @@ public boolean equals(Object obj) { private static ObjectMapper mapper = new ObjectMapper(); public static final Person defaultPerson = new Person("ribbon", 1); - public static final List persons = Lists.newArrayList(); + public static final List persons = new ArrayList<>(); - public static final List streamContent = Lists.newArrayList(); + public static final List streamContent = new ArrayList<>(); static { for (int i = 0; i < 1000; i++) { diff --git a/ribbon-httpclient/build.gradle b/ribbon-httpclient/build.gradle index f595022e5..634d22cc0 100644 --- a/ribbon-httpclient/build.gradle +++ b/ribbon-httpclient/build.gradle @@ -8,7 +8,6 @@ dependencies { api "com.sun.jersey.contribs:jersey-apache-client4:${jersey_version}" api "org.slf4j:slf4j-api:${slf4j_version}" api "com.netflix.servo:servo-core:${servo_version}" - api "com.google.guava:guava:${guava_version}" api 'com.netflix.netflix-commons:netflix-commons-util:0.1.1' testImplementation 'junit:junit:4.11' testImplementation "org.slf4j:slf4j-log4j12:${slf4j_version}" @@ -17,5 +16,6 @@ dependencies { testImplementation 'com.google.mockwebserver:mockwebserver:20130505' testImplementation 'com.fasterxml.jackson.core:jackson-databind:2.4.3' testImplementation project(':ribbon-archaius') + testImplementation "com.google.guava:guava:32.1.3-jre" testImplementation project(":ribbon-loadbalancer").sourceSets.test.output } diff --git a/ribbon-httpclient/src/main/java/com/netflix/client/http/CaseInsensitiveMultiMap.java b/ribbon-httpclient/src/main/java/com/netflix/client/http/CaseInsensitiveMultiMap.java index 4d933504e..94279ea7c 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/client/http/CaseInsensitiveMultiMap.java +++ b/ribbon-httpclient/src/main/java/com/netflix/client/http/CaseInsensitiveMultiMap.java @@ -1,44 +1,45 @@ package com.netflix.client.http; +import static com.netflix.utils.MultiMapUtil.getStringCollectionMap; + +import com.sun.jersey.core.util.StringKeyStringValueIgnoreCaseMultivaluedMap; +import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.AbstractMap.SimpleEntry; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; +import java.util.Set; public class CaseInsensitiveMultiMap implements HttpHeaders { - Multimap> map = ArrayListMultimap.create(); + private final StringKeyStringValueIgnoreCaseMultivaluedMap map = + new StringKeyStringValueIgnoreCaseMultivaluedMap(); @Override public String getFirstValue(String headerName) { - Collection> entries = map.get(headerName.toLowerCase()); - if (entries == null || entries.isEmpty()) { + final List strings = map.get(headerName); + if (strings == null || strings.isEmpty()) { return null; } - return entries.iterator().next().getValue(); + return strings.get(0); } @Override public List getAllValues(String headerName) { - Collection> entries = map.get(headerName.toLowerCase()); - List values = Lists.newArrayList(); - if (entries != null) { - for (Entry entry: entries) { - values.add(entry.getValue()); - } - } - return values; + return map.get(headerName); } @Override public List> getAllHeaders() { - Collection> all = map.values(); - return new ArrayList>(all); + final Set>> entries = map.entrySet(); + List> list = new ArrayList<>(); + for (Entry> entry : entries) { + final List values = entry.getValue(); + for (String value : values) { + list.add(new SimpleEntry<>(entry.getKey(), value)); + } + } + return list; } @Override @@ -47,19 +48,10 @@ public boolean containsHeader(String name) { } public void addHeader(String name, String value) { - if (getAllValues(name).contains(value)) { - return; - } - SimpleEntry entry = new SimpleEntry(name, value); - map.put(name.toLowerCase(), entry); + map.add(name, value); } Map> asMap() { - Multimap result = ArrayListMultimap.create(); - Collection> all = map.values(); - for (Entry entry: all) { - result.put(entry.getKey(), entry.getValue()); - } - return result.asMap(); + return getStringCollectionMap(map); } } diff --git a/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpRequest.java b/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpRequest.java index 88fc8967d..10f32c843 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpRequest.java +++ b/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpRequest.java @@ -17,16 +17,17 @@ */ package com.netflix.client.http; +import com.netflix.utils.MultiMapUtil; +import com.sun.jersey.core.util.MultivaluedMapImpl; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; +import java.util.Collections; import java.util.Map; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; import com.netflix.client.ClientRequest; import com.netflix.client.config.IClientConfig; +import javax.ws.rs.core.MultivaluedMap; /** * Request for HTTP communication. @@ -56,7 +57,7 @@ public String verb() { } protected CaseInsensitiveMultiMap httpHeaders = new CaseInsensitiveMultiMap(); - protected Multimap queryParams = ArrayListMultimap.create(); + protected MultivaluedMap queryParams = new MultivaluedMapImpl(); private Object entity; protected Verb verb; @@ -94,7 +95,7 @@ public Builder header(String name, String value) { return this; } - Builder queryParams(Multimap queryParams) { + Builder queryParams(MultivaluedMap queryParams) { request.queryParams = queryParams; return this; } @@ -124,12 +125,12 @@ public Builder setRetriable(boolean retriable) { */ @Deprecated public Builder queryParams(String name, String value) { - request.queryParams.put(name, value); + request.queryParams.add(name, value); return this; } public Builder queryParam(String name, String value) { - request.queryParams.put(name, value); + request.queryParams.add(name, value); return this; } @@ -155,7 +156,7 @@ public HttpRequest build() { } public Map> getQueryParams() { - return queryParams.asMap(); + return MultiMapUtil.getStringCollectionMap(queryParams); } public Verb getVerb() { diff --git a/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpResponse.java b/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpResponse.java index 766a022c8..08135e65f 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpResponse.java +++ b/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpResponse.java @@ -17,7 +17,6 @@ */ package com.netflix.client.http; -import com.google.common.reflect.TypeToken; import com.netflix.client.IResponse; import java.io.Closeable; @@ -61,10 +60,4 @@ public interface HttpResponse extends IResponse, Closeable { public T getEntity(Class type) throws Exception; public T getEntity(Type type) throws Exception; - - /** - * @deprecated use {@link #getEntity(Type)} - */ - @Deprecated - public T getEntity(TypeToken type) throws Exception; } diff --git a/ribbon-httpclient/src/main/java/com/netflix/http4/MonitoredConnectionManager.java b/ribbon-httpclient/src/main/java/com/netflix/http4/MonitoredConnectionManager.java index 0efb18873..3b23400be 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/http4/MonitoredConnectionManager.java +++ b/ribbon-httpclient/src/main/java/com/netflix/http4/MonitoredConnectionManager.java @@ -27,8 +27,6 @@ import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.HttpParams; -import com.google.common.annotations.VisibleForTesting; - /** * A connection manager that uses {@link NamedConnectionPool}, which provides * connection reuse statistics, as its underlying connection pool. @@ -72,7 +70,6 @@ protected ConnPoolByRoute createConnectionPool(long connTTL, return new NamedConnectionPool(connOperator, connPerRoute, 20, connTTL, connTTLTimeUnit); } - @VisibleForTesting ConnPoolByRoute getConnectionPool() { return this.pool; } diff --git a/ribbon-httpclient/src/main/java/com/netflix/http4/NFHttpClient.java b/ribbon-httpclient/src/main/java/com/netflix/http4/NFHttpClient.java index 88d26fa79..d21b42ce8 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/http4/NFHttpClient.java +++ b/ribbon-httpclient/src/main/java/com/netflix/http4/NFHttpClient.java @@ -17,7 +17,8 @@ */ package com.netflix.http4; -import com.google.common.util.concurrent.ThreadFactoryBuilder; +import static com.netflix.client.util.ThreadUtils.threadFactory; + import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; @@ -97,9 +98,7 @@ public class NFHttpClient extends DefaultHttpClient { private Property maxConnectionPerHostProperty; static { - ThreadFactory factory = (new ThreadFactoryBuilder()).setDaemon(true) - .setNameFormat("Connection pool clean up thread") - .build(); + ThreadFactory factory = threadFactory("Connection pool clean up thread"); connectionPoolCleanUpScheduler = Executors.newScheduledThreadPool(2, factory); } diff --git a/ribbon-httpclient/src/main/java/com/netflix/http4/NamedConnectionPool.java b/ribbon-httpclient/src/main/java/com/netflix/http4/NamedConnectionPool.java index da62a74c1..c1b7c2cee 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/http4/NamedConnectionPool.java +++ b/ribbon-httpclient/src/main/java/com/netflix/http4/NamedConnectionPool.java @@ -17,6 +17,7 @@ */ package com.netflix.http4; +import java.util.Objects; import java.util.concurrent.TimeUnit; import org.apache.http.conn.ClientConnectionOperator; @@ -30,7 +31,6 @@ import org.apache.http.impl.conn.tsccm.WaitingThreadAborter; import org.apache.http.params.HttpParams; -import com.google.common.base.Preconditions; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Counter; @@ -93,7 +93,7 @@ public NamedConnectionPool(String name, ClientConnectionOperator operator, } void initMonitors(String name) { - Preconditions.checkNotNull(name); + Objects.requireNonNull(name); freeEntryCounter = Monitors.newCounter(name + "_Reuse"); createEntryCounter = Monitors.newCounter(name + "_CreateNew"); requestCounter = Monitors.newCounter(name + "_Request"); diff --git a/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientLoadBalancerErrorHandler.java b/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientLoadBalancerErrorHandler.java index e3f4ec0e4..3538523f0 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientLoadBalancerErrorHandler.java +++ b/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientLoadBalancerErrorHandler.java @@ -3,6 +3,8 @@ import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.apache.http.ConnectionClosedException; @@ -11,24 +13,21 @@ import org.apache.http.conn.ConnectionPoolTimeoutException; import org.apache.http.conn.HttpHostConnectException; -import com.google.common.collect.Lists; import com.netflix.client.ClientException; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.config.IClientConfig; -import com.netflix.client.http.HttpResponse; public class HttpClientLoadBalancerErrorHandler extends DefaultLoadBalancerRetryHandler { - @SuppressWarnings("unchecked") - protected List> retriable = - Lists.>newArrayList(ConnectException.class, SocketTimeoutException.class, ConnectTimeoutException.class, - NoHttpResponseException.class, ConnectionPoolTimeoutException.class, ConnectionClosedException.class, HttpHostConnectException.class); - - @SuppressWarnings("unchecked") - protected List> circuitRelated = - Lists.>newArrayList(SocketException.class, SocketTimeoutException.class, ConnectTimeoutException.class, - ConnectionClosedException.class, HttpHostConnectException.class); - + + protected List> retriable = + new ArrayList<>(Arrays.asList(ConnectException.class, SocketTimeoutException.class, ConnectTimeoutException.class, + NoHttpResponseException.class, ConnectionPoolTimeoutException.class, ConnectionClosedException.class, HttpHostConnectException.class)); + + protected List> circuitRelated = + new ArrayList<>(Arrays.asList(SocketException.class, SocketTimeoutException.class, ConnectTimeoutException.class, + ConnectionClosedException.class, HttpHostConnectException.class)); + public HttpClientLoadBalancerErrorHandler() { super(); } @@ -43,7 +42,7 @@ public HttpClientLoadBalancerErrorHandler(int retrySameServer, } /** - * @return true if the Throwable has one of the following exception type as a cause: + * @return true if the Throwable has one of the following exception type as a cause: * {@link SocketException}, {@link SocketTimeoutException} */ @Override @@ -71,7 +70,7 @@ public boolean isRetriableException(Throwable e, boolean sameServer) { protected List> getRetriableExceptions() { return retriable; } - + @Override protected List> getCircuitRelatedExceptions() { return circuitRelated; diff --git a/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientResponse.java b/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientResponse.java index f0c8cd228..7fd9d4c5a 100644 --- a/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientResponse.java +++ b/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientResponse.java @@ -17,10 +17,8 @@ */ package com.netflix.niws.client.http; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.reflect.TypeToken; +import static com.netflix.utils.MultiMapUtil.getStringCollectionMap; + import com.netflix.client.ClientException; import com.netflix.client.config.IClientConfig; import com.netflix.client.http.HttpHeaders; @@ -28,15 +26,12 @@ import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.GenericType; +import java.util.Map.Entry; import javax.ws.rs.core.MultivaluedMap; import java.io.InputStream; import java.lang.reflect.Type; import java.net.URI; -import java.util.AbstractMap; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; +import java.util.*; /** * A NIWS Client Response @@ -48,7 +43,7 @@ class HttpClientResponse implements HttpResponse { private final ClientResponse bcr; - private final Multimap headers = ArrayListMultimap.create(); + private final MultivaluedMap headers; private final HttpHeaders httpHeaders; private final URI requestedURI; private final IClientConfig overrideConfig; @@ -57,11 +52,7 @@ public HttpClientResponse(ClientResponse cr, URI requestedURI, IClientConfig con bcr = cr; this.requestedURI = requestedURI; this.overrideConfig = config; - for (Map.Entry> entry: bcr.getHeaders().entrySet()) { - if (entry.getKey() != null && entry.getValue() != null) { - headers.putAll(entry.getKey(), entry.getValue()); - } - } + headers = bcr.getHeaders(); httpHeaders = new HttpHeaders() { @Override public String getFirstValue(String headerName) { @@ -74,7 +65,7 @@ public List getAllValues(String headerName) { @Override public List> getAllHeaders() { MultivaluedMap map = bcr.getHeaders(); - List> result = Lists.newArrayList(); + List> result = new ArrayList<>(); for (Map.Entry> header: map.entrySet()) { String name = header.getKey(); for (String value: header.getValue()) { @@ -108,7 +99,7 @@ public T getEntity(Class c) throws Exception { @Override public Map> getHeaders() { - return headers.asMap(); + return getStringCollectionMap(headers); } @Override @@ -172,11 +163,6 @@ public HttpHeaders getHttpHeaders() { return httpHeaders; } - @Override - public T getEntity(TypeToken type) throws Exception { - return bcr.getEntity(new GenericType(type.getType())); - } - @Override public T getEntity(Type type) throws Exception { return bcr.getEntity(new GenericType(type)); diff --git a/ribbon-httpclient/src/main/java/com/netflix/utils/MultiMapUtil.java b/ribbon-httpclient/src/main/java/com/netflix/utils/MultiMapUtil.java new file mode 100644 index 000000000..2b2286b3b --- /dev/null +++ b/ribbon-httpclient/src/main/java/com/netflix/utils/MultiMapUtil.java @@ -0,0 +1,23 @@ +package com.netflix.utils; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import javax.ws.rs.core.MultivaluedMap; + +public class MultiMapUtil { + + public static Map> getStringCollectionMap( + MultivaluedMap headers) { + final Set>> entries = headers.entrySet(); + Map> map = new HashMap<>(); + for (Entry> entry : entries) { + map.put(entry.getKey(), entry.getValue()); + } + return map; + } + +} diff --git a/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RetryTest.java b/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RetryTest.java index 24a6bd368..2f67a14b2 100644 --- a/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RetryTest.java +++ b/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RetryTest.java @@ -24,12 +24,14 @@ import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import com.google.common.collect.Lists; import com.netflix.client.ClientException; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; @@ -50,8 +52,7 @@ public class RetryTest { @ClassRule - public static MockHttpServer server = new MockHttpServer() - ; + public static MockHttpServer server = new MockHttpServer(); private RestClient client; private BaseLoadBalancer lb; @@ -77,7 +78,7 @@ public void beforeTest() { client = (RestClient) ClientFactory.getNamedClient("RetryTest"); lb = (BaseLoadBalancer) client.getLoadBalancer(); - lb.setServersList(Lists.newArrayList(localServer)); + lb.setServersList(Collections.singletonList(localServer)); httpClient = NFHttpClientFactory.getNamedNFHttpClient("RetryTest"); connectionPoolManager = (MonitoredConnectionManager) httpClient.getConnectionManager(); @@ -85,7 +86,7 @@ public void beforeTest() { client.setMaxAutoRetries(0); client.setMaxAutoRetriesNextServer(0); client.setOkToRetryOnAllOperations(false); - lb.setServersList(Lists.newArrayList(localServer)); + lb.setServersList(Collections.singletonList(localServer)); // reset the server index lb.setRule(new AvailabilityFilteringRule()); lb.getLoadBalancerStats().getSingleServerStat(localServer).clearSuccessiveConnectionFailureCount(); @@ -191,7 +192,7 @@ public void testRetriesOnPost() throws Exception { @Test public void testRetriesOnPostWithConnectException() throws Exception { URI localUrl = new URI("/status?code=503"); - lb.setServersList(Lists.newArrayList(localServer)); + lb.setServersList(Collections.singletonList(localServer)); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).setRetriable(true).build(); try { HttpResponse response = client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); @@ -205,7 +206,7 @@ public void testRetriesOnPostWithConnectException() throws Exception { @Test public void testSuccessfulRetries() throws Exception { - lb.setServersList(Lists.newArrayList(new Server("localhost:12987"), new Server("localhost:12987"), localServer)); + lb.setServersList(new ArrayList<>(Arrays.asList(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 { diff --git a/ribbon-loadbalancer/build.gradle b/ribbon-loadbalancer/build.gradle index ad7cbd275..a19e6c44b 100644 --- a/ribbon-loadbalancer/build.gradle +++ b/ribbon-loadbalancer/build.gradle @@ -4,8 +4,8 @@ dependencies { api "io.reactivex:rxjava:${rx_java_version}" api "org.slf4j:slf4j-api:${slf4j_version}" api "com.netflix.servo:servo-core:${servo_version}" - api "com.google.guava:guava:${guava_version}" api 'com.netflix.netflix-commons:netflix-commons-util:0.1.1' + api 'com.github.ben-manes.caffeine:caffeine:2.9.2' testImplementation project(":ribbon-archaius") testImplementation 'junit:junit:4.11' @@ -13,4 +13,5 @@ dependencies { testImplementation 'org.awaitility:awaitility:3.0.0' testImplementation "org.slf4j:slf4j-log4j12:${slf4j_version}" testImplementation "com.sun.jersey:jersey-server:${jersey_version}" + testImplementation "com.google.guava:guava:32.1.3-jre" } diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractServerPredicate.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractServerPredicate.java index 03dde8b05..cef3cc931 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractServerPredicate.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractServerPredicate.java @@ -17,17 +17,17 @@ */ package com.netflix.loadbalancer; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import java.util.stream.Collectors; import javax.annotation.Nullable; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; import com.netflix.client.config.IClientConfig; /** @@ -50,15 +50,15 @@ public abstract class AbstractServerPredicate implements Predicate private final Predicate serverOnlyPredicate = new Predicate() { @Override - public boolean apply(@Nullable Server input) { - return AbstractServerPredicate.this.apply(new PredicateKey(input)); + public boolean test(@Nullable Server input) { + return AbstractServerPredicate.this.test(new PredicateKey(input)); } }; public static AbstractServerPredicate alwaysTrue() { return new AbstractServerPredicate() { @Override - public boolean apply(@Nullable PredicateKey input) { + public boolean test(@Nullable PredicateKey input) { return true; } }; @@ -131,11 +131,12 @@ public List getEligibleServers(List servers) { */ public List getEligibleServers(List servers, Object loadBalancerKey) { if (loadBalancerKey == null) { - return ImmutableList.copyOf(Iterables.filter(servers, this.getServerOnlyPredicate())); + return servers.stream().filter(this.getServerOnlyPredicate()) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { - List results = Lists.newArrayList(); + List results = new ArrayList<>(); for (Server server: servers) { - if (this.apply(new PredicateKey(loadBalancerKey, server))) { + if (this.test(new PredicateKey(loadBalancerKey, server))) { results.add(server); } } @@ -167,7 +168,7 @@ private int incrementAndGetModulo(int modulo) { public Optional chooseRandomlyAfterFiltering(List servers) { List eligible = getEligibleServers(servers); if (eligible.size() == 0) { - return Optional.absent(); + return Optional.empty(); } return Optional.of(eligible.get(random.nextInt(eligible.size()))); } @@ -179,7 +180,7 @@ public Optional chooseRandomlyAfterFiltering(List servers) { public Optional chooseRoundRobinAfterFiltering(List servers) { List eligible = getEligibleServers(servers); if (eligible.size() == 0) { - return Optional.absent(); + return Optional.empty(); } return Optional.of(eligible.get(incrementAndGetModulo(eligible.size()))); } @@ -192,7 +193,7 @@ public Optional chooseRoundRobinAfterFiltering(List servers) { public Optional chooseRandomlyAfterFiltering(List servers, Object loadBalancerKey) { List eligible = getEligibleServers(servers, loadBalancerKey); if (eligible.size() == 0) { - return Optional.absent(); + return Optional.empty(); } return Optional.of(eligible.get(random.nextInt(eligible.size()))); } @@ -203,7 +204,7 @@ public Optional chooseRandomlyAfterFiltering(List servers, Objec public Optional chooseRoundRobinAfterFiltering(List servers, Object loadBalancerKey) { List eligible = getEligibleServers(servers, loadBalancerKey); if (eligible.size() == 0) { - return Optional.absent(); + return Optional.empty(); } return Optional.of(eligible.get(incrementAndGetModulo(eligible.size()))); } @@ -215,8 +216,8 @@ public static AbstractServerPredicate ofKeyPredicate(final Predicate return new AbstractServerPredicate() { @Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP") - public boolean apply(PredicateKey input) { - return p.apply(input.getServer()); + public boolean test(PredicateKey input) { + return p.test(input.getServer()); } }; } diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityFilteringRule.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityFilteringRule.java index 143af1c75..35894d39b 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityFilteringRule.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityFilteringRule.java @@ -19,7 +19,6 @@ import java.util.List; -import com.google.common.collect.Collections2; import com.netflix.client.config.IClientConfig; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; @@ -69,7 +68,7 @@ public int getAvailableServersCount() { if (servers == null) { return 0; } - return Collections2.filter(servers, predicate.getServerOnlyPredicate()).size(); + return (int) servers.stream().filter(predicate.getServerOnlyPredicate()).count(); } @@ -83,7 +82,7 @@ public Server choose(Object key) { int count = 0; Server server = roundRobinRule.choose(key); while (count++ <= 10) { - if (server != null && predicate.apply(new PredicateKey(server))) { + if (server != null && predicate.test(new PredicateKey(server))) { return server; } server = roundRobinRule.choose(key); diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityPredicate.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityPredicate.java index 6320cd78b..52ccadfd2 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityPredicate.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityPredicate.java @@ -17,7 +17,6 @@ */ package com.netflix.loadbalancer; -import com.google.common.base.Preconditions; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; @@ -81,7 +80,7 @@ private int getActiveConnectionsLimit() { } @Override - public boolean apply(@Nullable PredicateKey input) { + public boolean test(@Nullable PredicateKey input) { LoadBalancerStats stats = getLBStats(); if (stats == null) { return true; diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/BaseLoadBalancer.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/BaseLoadBalancer.java index af49283f7..8e9b7144f 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/BaseLoadBalancer.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/BaseLoadBalancer.java @@ -19,7 +19,6 @@ import static java.util.Collections.singleton; -import com.google.common.collect.ImmutableList; import com.netflix.client.ClientFactory; import com.netflix.client.IClientConfigAware; import com.netflix.client.PrimeConnections; @@ -507,9 +506,9 @@ public void setServersList(List lsrv) { boolean listChanged = false; if (!allServerList.equals(allServers)) { listChanged = true; - if (changeListeners != null && changeListeners.size() > 0) { - List oldList = ImmutableList.copyOf(allServerList); - List newList = ImmutableList.copyOf(allServers); + if (changeListeners != null && !changeListeners.isEmpty()) { + List oldList = Collections.unmodifiableList(new ArrayList<>(allServerList)); + List newList = Collections.unmodifiableList(new ArrayList<>(allServers)); for (ServerListChangeListener l: changeListeners) { try { l.serverListChanged(oldList, newList); diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/CompositePredicate.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/CompositePredicate.java index 1fc527b41..459efdbe8 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/CompositePredicate.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/CompositePredicate.java @@ -18,15 +18,13 @@ */ package com.netflix.loadbalancer; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.function.Predicate; import javax.annotation.Nullable; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Lists; - /** * A predicate that is composed from one or more predicates in "AND" relationship. * It also has the functionality of "fallback" to one of more different predicates. @@ -41,15 +39,15 @@ public class CompositePredicate extends AbstractServerPredicate { private AbstractServerPredicate delegate; - private List fallbacks = Lists.newArrayList(); + private List fallbacks = new ArrayList<>(); private int minimalFilteredServers = 1; private float minimalFilteredPercentage = 0; @Override - public boolean apply(@Nullable PredicateKey input) { - return delegate.apply(input); + public boolean test(@Nullable PredicateKey input) { + return delegate.test(input); } @@ -64,8 +62,11 @@ public static class Builder { Builder(AbstractServerPredicate ...primaryPredicates) { toBuild = new CompositePredicate(); - Predicate chain = Predicates.and(primaryPredicates); - toBuild.delegate = AbstractServerPredicate.ofKeyPredicate(chain); + Predicate chain = alwaysTrue(); + for (AbstractServerPredicate primaryPredicate : primaryPredicates) { + chain = chain.and(primaryPredicate); + } + toBuild.delegate = AbstractServerPredicate.ofKeyPredicate(chain); } public Builder addFallbackPredicate(AbstractServerPredicate fallback) { diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ConfigurationBasedServerList.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ConfigurationBasedServerList.java index 770269e8a..fbca5bfef 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ConfigurationBasedServerList.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ConfigurationBasedServerList.java @@ -17,10 +17,10 @@ */ package com.netflix.loadbalancer; +import com.netflix.servo.util.Strings; +import java.util.ArrayList; import java.util.List; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; @@ -56,7 +56,7 @@ public void initWithNiwsConfig(IClientConfig clientConfig) { } protected List derive(String value) { - List list = Lists.newArrayList(); + List list = new ArrayList<>(); if (!Strings.isNullOrEmpty(value)) { for (String s: value.split(",")) { list.add(new Server(s.trim())); diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DynamicServerListLoadBalancer.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DynamicServerListLoadBalancer.java index a6a11c63a..ff915e0f7 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DynamicServerListLoadBalancer.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DynamicServerListLoadBalancer.java @@ -17,7 +17,6 @@ */ package com.netflix.loadbalancer; -import com.google.common.annotations.VisibleForTesting; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; @@ -232,7 +231,6 @@ public void stopServerListRefreshing() { } } - @VisibleForTesting public void updateListOfServers() { List servers = new ArrayList(); if (serverListImpl != null) { diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerContext.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerContext.java index 8dd9eecc8..55822db48 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerContext.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerContext.java @@ -17,7 +17,6 @@ */ package com.netflix.loadbalancer; -import com.google.common.base.Strings; import com.netflix.client.ClientException; import com.netflix.client.ClientRequest; import com.netflix.client.DefaultLoadBalancerRetryHandler; @@ -27,6 +26,7 @@ import com.netflix.client.config.IClientConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Timer; +import com.netflix.servo.util.Strings; import com.netflix.util.Pair; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerStats.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerStats.java index 427610dee..d34434907 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerStats.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerStats.java @@ -17,13 +17,10 @@ */ package com.netflix.loadbalancer; -import com.google.common.base.Preconditions; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.cache.RemovalListener; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.LoadingCache; +import com.github.benmanes.caffeine.cache.RemovalListener; import com.netflix.client.IClientConfigAware; -import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; @@ -32,6 +29,7 @@ import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Monitors; +import com.netflix.servo.util.Preconditions; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -40,7 +38,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** @@ -92,14 +89,14 @@ public class LoadBalancerStats implements IClientConfigAware { private UnboxedIntProperty activeRequestsCountTimeout = new UnboxedIntProperty(ACTIVE_REQUESTS_COUNT_TIMEOUT.defaultValue()); - private final LoadingCache serverStatsCache = CacheBuilder.newBuilder() - .expireAfterAccess(30, TimeUnit.MINUTES) - .removalListener((RemovalListener) notification -> notification.getValue().close()) - .build(new CacheLoader() { - public ServerStats load(Server server) { - return createServerStats(server); - } - }); + private final LoadingCache serverStatsCache = Caffeine.newBuilder() + .expireAfterAccess(30, TimeUnit.MINUTES) + .removalListener((RemovalListener) (key, value, cause) -> { + if (value != null) { + value.close(); + } + }) + .build(this::createServerStats); protected ServerStats createServerStats(Server server) { ServerStats ss = new ServerStats(this); @@ -180,12 +177,7 @@ public void updateServerList(List servers){ public void addServer(Server server) { if (server != null) { - try { - serverStatsCache.get(server); - } catch (ExecutionException e) { - ServerStats stats = createServerStats(server); - serverStatsCache.asMap().putIfAbsent(server, stats); - } + serverStatsCache.get(server); } } @@ -205,13 +197,7 @@ protected ServerStats getServerStats(Server server) { return null; } - try { - return serverStatsCache.get(server); - } catch (ExecutionException e) { - ServerStats stats = createServerStats(server); - serverStatsCache.asMap().putIfAbsent(server, stats); - return serverStatsCache.asMap().get(server); - } + return serverStatsCache.get(server); } public void incrementActiveRequestsCount(Server server) { diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PollingServerListUpdater.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PollingServerListUpdater.java index ae8c7dd79..2707e106c 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PollingServerListUpdater.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PollingServerListUpdater.java @@ -1,8 +1,10 @@ package com.netflix.loadbalancer; -import com.google.common.util.concurrent.ThreadFactoryBuilder; +import static com.netflix.client.util.ThreadUtils.threadFactory; + import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; +import java.util.concurrent.ThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,10 +33,8 @@ private static class LazyHolder { static ScheduledExecutorService _serverListRefreshExecutor = null; static { - _serverListRefreshExecutor = Executors.newScheduledThreadPool(POOL_SIZE, new ThreadFactoryBuilder() - .setNameFormat("PollingServerListUpdater-%d") - .setDaemon(true) - .build()); + _serverListRefreshExecutor = Executors.newScheduledThreadPool(POOL_SIZE, + threadFactory("PollingServerListUpdater-%d")); } } diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PredicateBasedRule.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PredicateBasedRule.java index feaddacb4..dfd70d5f1 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PredicateBasedRule.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PredicateBasedRule.java @@ -17,7 +17,7 @@ */ package com.netflix.loadbalancer; -import com.google.common.base.Optional; +import java.util.Optional; /** * A rule which delegates the server filtering logic to an instance of {@link AbstractServerPredicate}. diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListSubsetFilter.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListSubsetFilter.java index 56c4d1a74..de501348b 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListSubsetFilter.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListSubsetFilter.java @@ -15,19 +15,13 @@ */ package com.netflix.loadbalancer; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Random; -import java.util.Set; +import java.util.*; /** * A server list filter that limits the number of the servers used by the load balancer to be the subset of all servers. @@ -42,7 +36,7 @@ public class ServerListSubsetFilter extends ZoneAffinityServerListFilter implements IClientConfigAware, Comparator{ private Random random = new Random(); - private volatile Set currentSubset = Sets.newHashSet(); + private volatile Set currentSubset = new HashSet<>(); private Property sizeProp; private Property eliminationPercent; private Property eliminationFailureCountThreshold; @@ -101,8 +95,8 @@ public void initWithNiwsConfig(IClientConfig clientConfig) { @Override public List getFilteredListOfServers(List servers) { List zoneAffinityFiltered = super.getFilteredListOfServers(servers); - Set candidates = Sets.newHashSet(zoneAffinityFiltered); - Set newSubSet = Sets.newHashSet(currentSubset); + Set candidates = new HashSet<>(zoneAffinityFiltered); + Set newSubSet = new HashSet<>(currentSubset); LoadBalancerStats lbStats = getLoadBalancerStats(); for (T server: currentSubset) { // this server is either down or out of service @@ -135,7 +129,7 @@ public List getFilteredListOfServers(List servers) { } if (numToForceEliminate > 0) { - List sortedSubSet = Lists.newArrayList(newSubSet); + List sortedSubSet = new ArrayList<>(newSubSet); Collections.sort(sortedSubSet, this); List forceEliminated = sortedSubSet.subList(0, numToForceEliminate); newSubSet.removeAll(forceEliminated); @@ -151,16 +145,16 @@ public List getFilteredListOfServers(List servers) { if (numToChoose > candidates.size()) { // Not enough healthy instances to choose, fallback to use the // total server pool - candidates = Sets.newHashSet(zoneAffinityFiltered); + candidates = new HashSet<>(zoneAffinityFiltered); candidates.removeAll(newSubSet); } - List chosen = randomChoose(Lists.newArrayList(candidates), numToChoose); + List chosen = randomChoose(new ArrayList<>(candidates), numToChoose); for (T server: chosen) { newSubSet.add(server); } } currentSubset = newSubSet; - return Lists.newArrayList(newSubSet); + return new ArrayList<>(newSubSet); } /** diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerStats.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerStats.java index 44a2c2f17..6b5cf58ab 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerStats.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerStats.java @@ -17,10 +17,6 @@ */ package com.netflix.loadbalancer; -import com.google.common.annotations.VisibleForTesting; - -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; import com.netflix.client.config.UnboxedIntProperty; import com.netflix.servo.annotations.DataSourceType; @@ -31,7 +27,6 @@ import com.netflix.util.MeasuredRate; import java.util.Date; -import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -68,14 +63,11 @@ public class ServerStats { Server server; AtomicLong totalRequests = new AtomicLong(); - - @VisibleForTesting + AtomicInteger successiveConnectionFailureCount = new AtomicInteger(0); - - @VisibleForTesting + AtomicInteger activeRequestsCount = new AtomicInteger(0); - @VisibleForTesting AtomicInteger openConnectionsCount = new AtomicInteger(0); private volatile long lastConnectionFailedTimestamp; diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityPredicate.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityPredicate.java index 908e4d6c8..76290048a 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityPredicate.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityPredicate.java @@ -33,7 +33,7 @@ public ZoneAffinityPredicate(String zone) { } @Override - public boolean apply(PredicateKey input) { + public boolean test(PredicateKey input) { Server s = input.getServer(); String az = s.getZone(); if (az != null && zone != null && az.toLowerCase().equals(zone.toLowerCase())) { diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityServerListFilter.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityServerListFilter.java index 49e47a6e9..c57880676 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityServerListFilter.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityServerListFilter.java @@ -18,8 +18,6 @@ * */ -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; @@ -27,6 +25,7 @@ import com.netflix.client.config.Property; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -123,8 +122,9 @@ private boolean shouldEnableZoneAffinity(List filtered) { @Override public List getFilteredListOfServers(List servers) { if (zone != null && (zoneAffinity || zoneExclusive) && servers !=null && servers.size() > 0){ - List filteredServers = Lists.newArrayList(Iterables.filter( - servers, this.zoneAffinityPredicate.getServerOnlyPredicate())); + List filteredServers = + servers.stream().filter(this.zoneAffinityPredicate.getServerOnlyPredicate()).collect( + Collectors.toList()); if (shouldEnableZoneAffinity(filteredServers)) { return filteredServers; } else if (zoneAffinity) { diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAvoidancePredicate.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAvoidancePredicate.java index c173d6515..af0bed899 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAvoidancePredicate.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAvoidancePredicate.java @@ -77,7 +77,7 @@ private void initDynamicProperties(IClientConfig clientConfig) { } @Override - public boolean apply(@Nullable PredicateKey input) { + public boolean test(@Nullable PredicateKey input) { if (!enabled.getOrDefault()) { return true; } diff --git a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAwareLoadBalancer.java b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAwareLoadBalancer.java index 7b9507821..930d0ea30 100644 --- a/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAwareLoadBalancer.java +++ b/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAwareLoadBalancer.java @@ -17,10 +17,7 @@ */ package com.netflix.loadbalancer; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; import com.netflix.client.ClientFactory; -import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; @@ -168,8 +165,7 @@ public Server chooseServer(Object key) { return super.chooseServer(key); } } - - @VisibleForTesting + BaseLoadBalancer getLoadBalancer(String zone) { zone = zone.toLowerCase(); BaseLoadBalancer loadBalancer = balancers.get(zone); diff --git a/ribbon-loadbalancer/src/test/java/com/netflix/client/testutil/MockHttpServer.java b/ribbon-loadbalancer/src/test/java/com/netflix/client/testutil/MockHttpServer.java index 2de6bed23..ebd0f87f2 100644 --- a/ribbon-loadbalancer/src/test/java/com/netflix/client/testutil/MockHttpServer.java +++ b/ribbon-loadbalancer/src/test/java/com/netflix/client/testutil/MockHttpServer.java @@ -1,5 +1,8 @@ package com.netflix.client.testutil; +import static com.netflix.client.util.ThreadUtils.threadFactory; + +import com.netflix.client.util.ThreadUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -370,8 +373,7 @@ private static Map queryToMap(HttpExchange t) { public void before(final Description description) throws Exception { this.service = Executors.newFixedThreadPool( - threadCount, - new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TestHttpServer-%d").build()); + threadCount, threadFactory("TestHttpServer-%d")); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0); if (hasSsl) { diff --git a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/BestAvailableRuleTest.java b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/BestAvailableRuleTest.java index 0599fcca8..58860053b 100644 --- a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/BestAvailableRuleTest.java +++ b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/BestAvailableRuleTest.java @@ -20,17 +20,16 @@ import static org.junit.Assert.*; +import java.util.ArrayList; import java.util.List; import org.junit.Test; -import com.google.common.collect.Lists; - public class BestAvailableRuleTest { @Test public void testRule() { - List servers = Lists.newArrayList(); + List servers = new ArrayList<>(); for (int i = 0; i < 10; i++) { servers.add(new Server(String.valueOf(i), 80)); } diff --git a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/MockServerList.java b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/MockServerList.java index 8f76b5ff9..7e3f2e9da 100644 --- a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/MockServerList.java +++ b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/MockServerList.java @@ -1,13 +1,13 @@ package com.netflix.loadbalancer; +import java.util.ArrayList; import java.util.List; -import com.google.common.collect.Lists; import com.netflix.client.config.IClientConfig; public class MockServerList extends AbstractServerList { - private List serverList = Lists.newArrayList(); + private List serverList = new ArrayList<>(); public void setServerList(List serverList) { this.serverList = serverList; diff --git a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/PredicatesTest.java b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/PredicatesTest.java index 027e9e00d..c1b262c0b 100644 --- a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/PredicatesTest.java +++ b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/PredicatesTest.java @@ -19,17 +19,11 @@ import static org.junit.Assert.*; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import org.junit.AfterClass; import org.junit.Test; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; import com.netflix.config.ConfigurationManager; import com.netflix.config.DeploymentContext.ContextKey; @@ -66,7 +60,7 @@ public void setServerStats(LoadBalancerStats lbStats, Object[][] stats) { @Test public void testAvalabilityPredicate() { Object[][] stats = new Object[10][3]; - List expectedFiltered = Lists.newArrayList(); + List expectedFiltered = new ArrayList<>(); for (int i = 0; i < 7; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); @@ -83,15 +77,15 @@ public void testAvalabilityPredicate() { LoadBalancerStats lbStats = new LoadBalancerStats("default"); setServerStats(lbStats, stats); AvailabilityPredicate predicate = new AvailabilityPredicate(lbStats, null); - assertFalse(predicate.apply(new PredicateKey((Server) stats[8][0]))); - assertTrue(predicate.apply(new PredicateKey((Server) stats[0][0]))); - List servers = Lists.newArrayList(); + assertFalse(predicate.test(new PredicateKey((Server) stats[8][0]))); + assertTrue(predicate.test(new PredicateKey((Server) stats[0][0]))); + List servers = new ArrayList<>(); for (int i = 0; i < 10; i++) { servers.add((Server) stats[i][0]); } List filtered = predicate.getEligibleServers(servers); assertEquals(expectedFiltered, filtered); - Set chosen = Sets.newHashSet(); + Set chosen = new HashSet<>(); for (int i = 0; i < 20; i++) { Server s = predicate.chooseRoundRobinAfterFiltering(servers).get(); assertEquals("good:" + (i % 7), s.getId()); @@ -127,9 +121,9 @@ public void testAvalabilityPredicateAfterFailure() { @Test public void testZoneAvoidancePredicate() { Object[][] stats = new Object[10][3]; - Map> zoneMap = Maps.newHashMap(); - List expectedFiltered = Lists.newArrayList(); - List list0 = Lists.newArrayList(); + Map> zoneMap = new HashMap<>(); + List expectedFiltered = new ArrayList<>(); + List list0 = new ArrayList<>(); for (int i = 0; i < 3; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); @@ -140,7 +134,7 @@ public void testZoneAvoidancePredicate() { expectedFiltered.add((Server) stats[i][0]); } zoneMap.put("0", list0); - List list1 = Lists.newArrayList(); + List list1 = new ArrayList<>(); for (int i = 3; i < 7; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("bad:" + i); @@ -150,7 +144,7 @@ public void testZoneAvoidancePredicate() { stats[i][2] = 2; } zoneMap.put("1", list1); - List list2 = Lists.newArrayList(); + List list2 = new ArrayList<>(); for (int i = 7; i < 10; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); @@ -164,9 +158,9 @@ public void testZoneAvoidancePredicate() { setServerStats(lbStats, stats); lbStats.updateZoneServerMapping(zoneMap); ZoneAvoidancePredicate predicate = new ZoneAvoidancePredicate(lbStats, null); - assertFalse(predicate.apply(new PredicateKey((Server) stats[5][0]))); - assertTrue(predicate.apply(new PredicateKey((Server) stats[0][0]))); - assertTrue(predicate.apply(new PredicateKey((Server) stats[9][0]))); + assertFalse(predicate.test(new PredicateKey((Server) stats[5][0]))); + assertTrue(predicate.test(new PredicateKey((Server) stats[0][0]))); + assertTrue(predicate.test(new PredicateKey((Server) stats[9][0]))); } @Test @@ -174,8 +168,8 @@ public void testCompositePredicate() { ConfigurationManager.getConfigInstance().setProperty(ContextKey.zone.getKey(), "0"); Object[][] stats = new Object[10][3]; - Map> zoneMap = Maps.newHashMap(); - List expectedFiltered = Lists.newArrayList(); + Map> zoneMap = new HashMap<>(); + List expectedFiltered = new ArrayList<>(); for (int i = 0; i < 3; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); @@ -184,7 +178,7 @@ public void testCompositePredicate() { stats[i][2] = 0; expectedFiltered.add((Server) stats[i][0]); } - List list1 = Lists.newArrayList(); + List list1 = new ArrayList<>(); for (int i = 3; i < 7; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("bad:" + i); @@ -194,7 +188,7 @@ public void testCompositePredicate() { stats[i][2] = 0; } zoneMap.put("1", list1); - List list2 = Lists.newArrayList(); + List list2 = new ArrayList<>(); for (int i = 7; i < 10; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); @@ -211,10 +205,10 @@ public void testCompositePredicate() { AvailabilityPredicate p1 = new AvailabilityPredicate(lbStats, null); ZoneAffinityPredicate p2 = new ZoneAffinityPredicate("0"); CompositePredicate c = CompositePredicate.withPredicates(p2, p1).build(); - assertFalse(c.apply(new PredicateKey((Server) stats[5][0]))); - assertTrue(c.apply(new PredicateKey((Server) stats[0][0]))); - assertFalse(c.apply(new PredicateKey((Server) stats[9][0]))); - List servers = Lists.newArrayList(); + assertFalse(c.test(new PredicateKey((Server) stats[5][0]))); + assertTrue(c.test(new PredicateKey((Server) stats[0][0]))); + assertFalse(c.test(new PredicateKey((Server) stats[9][0]))); + List servers = new ArrayList<>(); for (int i = 0; i < 10; i++) { servers.add((Server) stats[i][0]); } diff --git a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/SubsetFilterTest.java b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/SubsetFilterTest.java index 9524e513c..250937989 100644 --- a/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/SubsetFilterTest.java +++ b/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/SubsetFilterTest.java @@ -18,6 +18,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; @@ -50,7 +51,7 @@ public static void init() { } List getServersAndStats(LoadBalancerStats lbStats, Object[][] stats) { - List list = Lists.newArrayList(); + List list = new ArrayList<>(); for (Object[] serverStats: stats) { Server server = new Server((String) serverStats[0]); list.add(server); @@ -140,7 +141,7 @@ public void testFiltering() { assertTrue(filtered.contains(s5)); // Not enough healthy servers, just get whatever is available - List lastFiltered = filter.getFilteredListOfServers(Lists.newArrayList(filtered)); + List lastFiltered = filter.getFilteredListOfServers(new ArrayList<>(filtered)); assertEquals(5, lastFiltered.size()); } @@ -207,7 +208,7 @@ public void testWithLoadBalancer() { assertTrue(filtered.contains(s5)); // Not enough healthy servers, just get whatever is available - serverList.setServerList(Lists.newArrayList(filtered)); + serverList.setServerList(new ArrayList<>(filtered)); lb.updateListOfServers(); List lastFiltered = lb.getAllServers(); assertEquals(5, lastFiltered.size()); diff --git a/ribbon-test/build.gradle b/ribbon-test/build.gradle index 12a8405ce..37521c243 100644 --- a/ribbon-test/build.gradle +++ b/ribbon-test/build.gradle @@ -5,9 +5,9 @@ dependencies { api 'org.codehaus.jackson:jackson-mapper-asl:1.9.11' api "com.netflix.eureka:eureka-client:${eureka_version}" api "io.reactivex:rxjava:${rx_java_version}" - api 'javax.ws.rs:jsr311-api:1.1.1' - api "com.google.guava:guava:${guava_version}" + api 'javax.ws.rs:jsr311-api:1.1.1' api "junit:junit:${junit_version}" api "org.powermock:powermock-easymock-release-full:${powermock_version}" api "org.easymock:easymock:${easymock_version}" + api "com.google.guava:guava:32.1.3-jre" } diff --git a/ribbon-test/src/main/java/com/netflix/ribbon/test/resources/EmbeddedResources.java b/ribbon-test/src/main/java/com/netflix/ribbon/test/resources/EmbeddedResources.java index df2517ee4..bea568016 100644 --- a/ribbon-test/src/main/java/com/netflix/ribbon/test/resources/EmbeddedResources.java +++ b/ribbon-test/src/main/java/com/netflix/ribbon/test/resources/EmbeddedResources.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.util.ArrayList; import java.util.List; import javax.ws.rs.Consumes; @@ -37,8 +38,6 @@ import org.codehaus.jackson.map.ObjectMapper; import org.junit.Ignore; -import com.google.common.collect.Lists; - @Ignore @Path("/testAsync") @Consumes(MediaType.APPLICATION_JSON) @@ -89,8 +88,8 @@ public boolean equals(Object obj) { private static ObjectMapper mapper = new ObjectMapper(); public static final Person defaultPerson = new Person("ribbon", 1); - public static final List streamContent = Lists.newArrayList(); - public static final List entityStream = Lists.newArrayList(); + public static final List streamContent = new ArrayList<>(); + public static final List entityStream = new ArrayList<>(); static { for (int i = 0; i < 1000; i++) { diff --git a/ribbon-test/src/main/java/com/netflix/serialization/JacksonCodec.java b/ribbon-test/src/main/java/com/netflix/serialization/JacksonCodec.java index 947beee59..2af7b2ac4 100644 --- a/ribbon-test/src/main/java/com/netflix/serialization/JacksonCodec.java +++ b/ribbon-test/src/main/java/com/netflix/serialization/JacksonCodec.java @@ -5,12 +5,12 @@ import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.codehaus.jackson.type.TypeReference; -import com.google.common.base.Charsets; import com.google.common.io.CharStreams; public class JacksonCodec implements Serializer, Deserializer { @@ -23,7 +23,7 @@ public class JacksonCodec implements Serializer, Deserializ public T deserialize(InputStream in, TypeDef type) throws IOException { if (String.class.equals(type.getRawType())) { - return (T) CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); + return (T) CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8)); } return mapper.readValue(in, new TypeTokenBasedReference(type)); } diff --git a/ribbon-test/src/main/java/com/netflix/serialization/SerializationUtils.java b/ribbon-test/src/main/java/com/netflix/serialization/SerializationUtils.java index 2df4880e0..3f3ed7207 100644 --- a/ribbon-test/src/main/java/com/netflix/serialization/SerializationUtils.java +++ b/ribbon-test/src/main/java/com/netflix/serialization/SerializationUtils.java @@ -4,20 +4,21 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -import com.google.common.base.Preconditions; +import java.nio.charset.StandardCharsets; +import java.util.Objects; public class SerializationUtils { public static T deserializeFromString(Deserializer deserializer, String content, TypeDef typeDef) throws IOException { - Preconditions.checkNotNull(deserializer); - ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes("UTF-8")); + Objects.requireNonNull(deserializer); + ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); return deserializer.deserialize(in, typeDef); } public static String serializeToString(Serializer serializer, T obj, TypeDef typeDef) throws IOException { - return new String(serializeToBytes(serializer, obj, typeDef), "UTF-8"); + return new String(serializeToBytes(serializer, obj, typeDef), StandardCharsets.UTF_8); } public static byte[] serializeToBytes(Serializer serializer, T obj, TypeDef typeDef) diff --git a/ribbon-test/src/main/java/com/netflix/serialization/StringDeserializer.java b/ribbon-test/src/main/java/com/netflix/serialization/StringDeserializer.java index 47c63ce05..6a7c9c23d 100644 --- a/ribbon-test/src/main/java/com/netflix/serialization/StringDeserializer.java +++ b/ribbon-test/src/main/java/com/netflix/serialization/StringDeserializer.java @@ -3,8 +3,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; -import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.google.common.io.Closeables; @@ -23,7 +23,7 @@ public static final StringDeserializer getInstance() { public String deserialize(InputStream in, TypeDef type) throws IOException { try { - String content = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); + String content = CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8)); return content; } finally { Closeables.close(in, true); diff --git a/ribbon-transport/build.gradle b/ribbon-transport/build.gradle index 934ca609e..5e1cd2f0f 100644 --- a/ribbon-transport/build.gradle +++ b/ribbon-transport/build.gradle @@ -9,7 +9,6 @@ dependencies { api "io.netty:netty-codec-http:4.0.27.Final" api 'javax.inject:javax.inject:1' api "org.slf4j:slf4j-api:${slf4j_version}" - api "com.google.guava:guava:${guava_version}" testImplementation 'junit:junit:4.11' testImplementation "org.slf4j:slf4j-log4j12:${slf4j_version}" testImplementation "com.sun.jersey:jersey-server:${jersey_version}" diff --git a/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/RibbonTransport.java b/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/RibbonTransport.java index ca4c91857..207882558 100644 --- a/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/RibbonTransport.java +++ b/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/RibbonTransport.java @@ -17,8 +17,8 @@ */ package com.netflix.ribbon.transport.netty; -import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.client.DefaultLoadBalancerRetryHandler; +import com.netflix.client.util.ThreadUtils; import com.netflix.loadbalancer.reactive.ExecutionListener; import com.netflix.client.RetryHandler; import com.netflix.client.config.DefaultClientConfigImpl; @@ -57,9 +57,7 @@ public final class RibbonTransport { public static final ScheduledExecutorService poolCleanerScheduler; static { - ThreadFactory factory = (new ThreadFactoryBuilder()).setDaemon(true) - .setNameFormat("RxClient_Connection_Pool_Clean_Up") - .build(); + ThreadFactory factory = ThreadUtils.threadFactory("RxClient_Connection_Pool_Clean_Up"); poolCleanerScheduler = new ScheduledThreadPoolExectuorWithDynamicSize(POOL_CLEANER_CORE_SIZE, factory); } diff --git a/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.java b/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.java index 0ceb590f3..f2e519c06 100644 --- a/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.java +++ b/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.java @@ -42,6 +42,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; @@ -54,8 +55,6 @@ import rx.functions.Func1; import rx.functions.Func2; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; import com.netflix.client.RequestSpecificRetryHandler; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; @@ -298,7 +297,7 @@ public Observable> submit(Server server, final HttpClientR * @return */ protected ServerOperation> requestToOperation(final HttpClientRequest request, final ClientConfig rxClientConfig) { - Preconditions.checkNotNull(request); + Objects.requireNonNull(request); return new ServerOperation>() { final AtomicInteger count = new AtomicInteger(0); @@ -425,7 +424,6 @@ private Observable> submit(final Server server, final Http return result; } - @VisibleForTesting ServerStats getServerStats(Server server) { return lbContext.getServerStats(server); } @@ -521,13 +519,11 @@ public SSLEngine createSSLEngine(ByteBufAllocator allocator) { } return clientBuilder.build(); } - - @VisibleForTesting + HttpClientListener getListener() { return (HttpClientListener) listener; } - @VisibleForTesting Map> getRxClients() { return rxClientCache; } diff --git a/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/NettyHttpLoadBalancerErrorHandler.java b/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/NettyHttpLoadBalancerErrorHandler.java index aa3f64ecc..1f247dcd1 100644 --- a/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/NettyHttpLoadBalancerErrorHandler.java +++ b/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/NettyHttpLoadBalancerErrorHandler.java @@ -20,10 +20,10 @@ import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; - -import com.google.common.collect.Lists; import com.netflix.client.ClientException; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.config.IClientConfig; @@ -31,17 +31,15 @@ public class NettyHttpLoadBalancerErrorHandler extends DefaultLoadBalancerRetryHandler { - @SuppressWarnings("unchecked") - private List> retriable = - Lists.>newArrayList(ConnectException.class, SocketTimeoutException.class, + private final List> retriable = + new ArrayList<>(Arrays.asList(ConnectException.class, SocketTimeoutException.class, io.netty.handler.timeout.ReadTimeoutException.class, io.netty.channel.ConnectTimeoutException.class, - io.reactivex.netty.client.PoolExhaustedException.class); - - @SuppressWarnings("unchecked") - private List> circuitRelated = - Lists.>newArrayList(SocketException.class, SocketTimeoutException.class, + io.reactivex.netty.client.PoolExhaustedException.class)); + + private final List> circuitRelated = + new ArrayList<>(Arrays.asList(SocketException.class, SocketTimeoutException.class, io.netty.handler.timeout.ReadTimeoutException.class, io.netty.channel.ConnectTimeoutException.class, - io.reactivex.netty.client.PoolExhaustedException.class); + io.reactivex.netty.client.PoolExhaustedException.class)); public NettyHttpLoadBalancerErrorHandler() { super(); diff --git a/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/NettyClientTest.java b/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/NettyClientTest.java index b1d1dbbca..7630825be 100644 --- a/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/NettyClientTest.java +++ b/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/NettyClientTest.java @@ -38,6 +38,7 @@ import java.io.IOException; import java.nio.charset.Charset; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; @@ -631,7 +632,7 @@ private static List getPersonListFromResponse(Observable getPersonList(Observable events) { - List result = Lists.newArrayList(); + List result = new ArrayList<>(); Iterator iterator = events.map(new Func1() { @Override public Person call(ServerSentEvent t1) { @@ -671,7 +672,7 @@ public void testStreamWithLoadBalancer() throws Exception { BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient lbObservables = (LoadBalancingHttpClient) RibbonTransport.newSSEClient(lb, config); HttpClientRequest request = HttpClientRequest.createGet("/testAsync/personStream"); - List result = Lists.newArrayList(); + List result = new ArrayList<>(); Server goodServer = new Server("localhost:" + port); Server badServer = new Server("localhost:12245"); List servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); diff --git a/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/ServerListRefreshTest.java b/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/ServerListRefreshTest.java index 422a2dbd9..3560db363 100644 --- a/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/ServerListRefreshTest.java +++ b/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/ServerListRefreshTest.java @@ -18,7 +18,6 @@ package com.netflix.ribbon.transport.netty.http; import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.netflix.ribbon.transport.netty.RibbonTransport; @@ -29,6 +28,8 @@ import org.junit.Test; import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Set; @@ -71,11 +72,11 @@ public void testServerListRefresh() throws IOException { HttpClientRequest request2 = HttpClientRequest.createGet("http://localhost:" + server3.getPort()); client.submit(request2).toBlocking().last(); Set cachedServers = client.getRxClients().keySet(); - assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort()), new Server("localhost", server3.getPort())), cachedServers); + assertEquals(new HashSet<>(Arrays.asList(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort()), new Server("localhost", server3.getPort()))), cachedServers); List newList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", 99999)); lb.setServersList(newList); cachedServers = client.getRxClients().keySet(); - assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server3.getPort())), cachedServers); + assertEquals(new HashSet<>(Arrays.asList(new Server("localhost", server1.getPort()), new Server("localhost", server3.getPort()))), cachedServers); } finally { server1.shutdown(); server2.shutdown(); diff --git a/ribbon/build.gradle b/ribbon/build.gradle index ab0673633..cea7368dc 100644 --- a/ribbon/build.gradle +++ b/ribbon/build.gradle @@ -16,7 +16,6 @@ dependencies { api "io.reactivex:rxjava:${rx_java_version}" api "io.reactivex:rxnetty:${rx_netty_version}" api 'commons-configuration:commons-configuration:1.8' - api "com.google.guava:guava:${guava_version}" api "com.netflix.archaius:archaius-core:${archaius_version}" testImplementation "junit:junit:${junit_version}" testImplementation "org.powermock:powermock-easymock-release-full:${powermock_version}" diff --git a/ribbon/src/main/java/com/netflix/ribbon/template/TemplateParser.java b/ribbon/src/main/java/com/netflix/ribbon/template/TemplateParser.java index 02881f959..f52921457 100644 --- a/ribbon/src/main/java/com/netflix/ribbon/template/TemplateParser.java +++ b/ribbon/src/main/java/com/netflix/ribbon/template/TemplateParser.java @@ -16,11 +16,10 @@ package com.netflix.ribbon.template; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; -import com.google.common.collect.Maps; - /** * Created by mcohen on 5/1/14. */ @@ -102,7 +101,7 @@ public static String toData(Map variables, String template, List public static void main(String[] args) throws TemplateParsingException { String template = "/abc/{id}?name={name}"; - Map vars = Maps.newHashMap(); + Map vars = new HashMap<>(); vars.put("id", "5"); vars.put("name", "netflix"); List list = parseTemplate(template);