index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/LoadBalancingRxClientWithPoolOptions.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty; import io.reactivex.netty.client.CompositePoolLimitDeterminationStrategy; import io.reactivex.netty.client.MaxConnectionsBasedStrategy; import io.reactivex.netty.client.PoolLimitDeterminationStrategy; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.pipeline.PipelineConfigurator; import java.util.concurrent.ScheduledExecutorService; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerBuilder; public abstract class LoadBalancingRxClientWithPoolOptions<I, O, T extends RxClient<I, O>> extends LoadBalancingRxClient<I, O, T>{ protected CompositePoolLimitDeterminationStrategy poolStrategy; protected MaxConnectionsBasedStrategy globalStrategy; protected int idleConnectionEvictionMills; protected ScheduledExecutorService poolCleanerScheduler; protected boolean poolEnabled = true; public LoadBalancingRxClientWithPoolOptions(IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { this(LoadBalancerBuilder.newBuilder().withClientConfig(config).buildDynamicServerListLoadBalancer(), config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } public LoadBalancingRxClientWithPoolOptions(ILoadBalancer lb, IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { super(lb, config, retryHandler, pipelineConfigurator); poolEnabled = config.get(CommonClientConfigKey.EnableConnectionPool, DefaultClientConfigImpl.DEFAULT_ENABLE_CONNECTION_POOL); if (poolEnabled) { this.poolCleanerScheduler = poolCleanerScheduler; int maxTotalConnections = config.get(IClientConfigKey.Keys.MaxTotalConnections, DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS); int maxConnections = config.get(Keys.MaxConnectionsPerHost, DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST); MaxConnectionsBasedStrategy perHostStrategy = new DynamicPropertyBasedPoolStrategy(maxConnections, config.getClientName() + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxConnectionsPerHost); globalStrategy = new DynamicPropertyBasedPoolStrategy(maxTotalConnections, config.getClientName() + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxTotalConnections); poolStrategy = new CompositePoolLimitDeterminationStrategy(perHostStrategy, globalStrategy); idleConnectionEvictionMills = config.get(Keys.ConnIdleEvictTimeMilliSeconds, DefaultClientConfigImpl.DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS); } } protected final PoolLimitDeterminationStrategy getPoolStrategy() { return globalStrategy; } protected int getConnectionIdleTimeoutMillis() { return idleConnectionEvictionMills; } protected boolean isPoolEnabled() { return poolEnabled; } @Override public int getMaxConcurrentRequests() { if (poolEnabled) { return globalStrategy.getMaxConnections(); } return super.getMaxConcurrentRequests(); } }
3,500
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/DynamicPropertyBasedPoolStrategy.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty; import com.netflix.config.DynamicProperty; import io.reactivex.netty.client.MaxConnectionsBasedStrategy; /** * A {@link MaxConnectionsBasedStrategy} that resize itself based on callbacks from * {@link DynamicProperty} * * @author awang * */ public class DynamicPropertyBasedPoolStrategy extends MaxConnectionsBasedStrategy { private final DynamicProperty poolSizeProperty; public DynamicPropertyBasedPoolStrategy(final int maxConnections, String propertyName) { super(maxConnections); poolSizeProperty = DynamicProperty.getInstance(propertyName); setMaxConnections(poolSizeProperty.getInteger(maxConnections)); poolSizeProperty.addCallback(new Runnable() { @Override public void run() { setMaxConnections(poolSizeProperty.getInteger(maxConnections)); }; }); } protected void setMaxConnections(int max) { int diff = max - getMaxConnections(); incrementMaxConnections(diff); } }
3,501
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/RibbonTransport.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.loadbalancer.reactive.ExecutionListener; import com.netflix.client.RetryHandler; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import com.netflix.ribbon.transport.netty.http.NettyHttpLoadBalancerErrorHandler; import com.netflix.ribbon.transport.netty.http.SSEClient; import com.netflix.ribbon.transport.netty.tcp.LoadBalancingTcpClient; import com.netflix.ribbon.transport.netty.udp.LoadBalancingUdpClient; import com.netflix.config.DynamicIntProperty; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.utils.ScheduledThreadPoolExectuorWithDynamicSize; import io.netty.buffer.ByteBuf; import io.netty.channel.socket.DatagramPacket; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.text.sse.ServerSentEvent; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; public final class RibbonTransport { public static final PipelineConfigurator<HttpClientResponse<ServerSentEvent>, HttpClientRequest<ByteBuf>> DEFAULT_SSE_PIPELINE_CONFIGURATOR = PipelineConfigurators.sseClientConfigurator(); public static final PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> DEFAULT_HTTP_PIPELINE_CONFIGURATOR = PipelineConfigurators.httpClientConfigurator(); public static final DynamicIntProperty POOL_CLEANER_CORE_SIZE = new DynamicIntProperty("rxNetty.poolCleaner.coreSize", 2); public static final ScheduledExecutorService poolCleanerScheduler; static { ThreadFactory factory = (new ThreadFactoryBuilder()).setDaemon(true) .setNameFormat("RxClient_Connection_Pool_Clean_Up") .build(); poolCleanerScheduler = new ScheduledThreadPoolExectuorWithDynamicSize(POOL_CLEANER_CORE_SIZE, factory); } private RibbonTransport() { } private static RetryHandler getDefaultHttpRetryHandlerWithConfig(IClientConfig config) { return new NettyHttpLoadBalancerErrorHandler(config); } private static RetryHandler getDefaultRetryHandlerWithConfig(IClientConfig config) { return new DefaultLoadBalancerRetryHandler(config); } public static RxClient<ByteBuf, ByteBuf> newTcpClient(ILoadBalancer loadBalancer, IClientConfig config) { return new LoadBalancingTcpClient<ByteBuf, ByteBuf>(loadBalancer, config, getDefaultRetryHandlerWithConfig(config), null, poolCleanerScheduler); } public static <I, O> RxClient<I, O> newTcpClient(ILoadBalancer loadBalancer, PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config, RetryHandler retryHandler) { return new LoadBalancingTcpClient<I, O>(loadBalancer, config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } public static <I, O> RxClient<I, O> newTcpClient(PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config) { return new LoadBalancingTcpClient<I, O>(config, getDefaultRetryHandlerWithConfig(config), pipelineConfigurator, poolCleanerScheduler); } public static RxClient<ByteBuf, ByteBuf> newTcpClient(IClientConfig config) { return new LoadBalancingTcpClient<ByteBuf, ByteBuf>(config, getDefaultRetryHandlerWithConfig(config), null, poolCleanerScheduler); } public static RxClient<DatagramPacket, DatagramPacket> newUdpClient(ILoadBalancer loadBalancer, IClientConfig config) { return new LoadBalancingUdpClient<DatagramPacket, DatagramPacket>(loadBalancer, config, getDefaultRetryHandlerWithConfig(config), null); } public static RxClient<DatagramPacket, DatagramPacket> newUdpClient(IClientConfig config) { return new LoadBalancingUdpClient<DatagramPacket, DatagramPacket>(config, getDefaultRetryHandlerWithConfig(config), null); } public static <I, O> RxClient<I, O> newUdpClient(ILoadBalancer loadBalancer, PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config, RetryHandler retryHandler) { return new LoadBalancingUdpClient<I, O>(loadBalancer, config, retryHandler, pipelineConfigurator); } public static <I, O> RxClient<I, O> newUdpClient(PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config) { return new LoadBalancingUdpClient<I, O>(config, getDefaultRetryHandlerWithConfig(config), pipelineConfigurator); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); return newHttpClient(config); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler, List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .withExecutorListeners(listeners) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(IClientConfig config) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer) { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); return newHttpClient(loadBalancer, config); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, ILoadBalancer loadBalancer, IClientConfig config) { return LoadBalancingHttpClient.<I, O>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, IClientConfig config) { return LoadBalancingHttpClient.<I, O>builder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, IClientConfig config, RetryHandler retryHandler) { return LoadBalancingHttpClient.<I, O>builder() .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler, List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners) { return LoadBalancingHttpClient.<I, O>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .withExecutorListeners(listeners) .build(); } public static LoadBalancingHttpClient<ByteBuf, ServerSentEvent> newSSEClient(ILoadBalancer loadBalancer, IClientConfig config) { return SSEClient.<ByteBuf>sseClientBuilder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_SSE_PIPELINE_CONFIGURATOR) .build(); } public static LoadBalancingHttpClient<ByteBuf, ServerSentEvent> newSSEClient(IClientConfig config) { return SSEClient.<ByteBuf>sseClientBuilder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_SSE_PIPELINE_CONFIGURATOR) .build(); } public static <I> LoadBalancingHttpClient<I, ServerSentEvent> newSSEClient(PipelineConfigurator<HttpClientResponse<ServerSentEvent>, HttpClientRequest<I>> pipelineConfigurator, ILoadBalancer loadBalancer, IClientConfig config) { return SSEClient.<I>sseClientBuilder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .build(); } public static <I> LoadBalancingHttpClient<I, ServerSentEvent> newSSEClient(PipelineConfigurator<HttpClientResponse<ServerSentEvent>, HttpClientRequest<I>> pipelineConfigurator, IClientConfig config) { return SSEClient.<I>sseClientBuilder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .build(); } public static LoadBalancingHttpClient<ByteBuf, ServerSentEvent> newSSEClient() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); return newSSEClient(config); } }
3,502
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/udp/LoadBalancingUdpClient.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty.udp; import com.netflix.client.RetryHandler; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.LoadBalancingRxClient; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import io.reactivex.netty.RxNetty; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.protocol.udp.client.UdpClientBuilder; import io.reactivex.netty.servo.udp.UdpClientListener; public class LoadBalancingUdpClient<I, O> extends LoadBalancingRxClient<I, O, RxClient<I,O>> implements RxClient<I, O> { public LoadBalancingUdpClient(IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator) { super(config, retryHandler, pipelineConfigurator); } public LoadBalancingUdpClient(ILoadBalancer lb, IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator) { super(lb, config, retryHandler, pipelineConfigurator); } @Override protected RxClient<I, O> createRxClient(Server server) { UdpClientBuilder<I, O> builder = RxNetty.newUdpClientBuilder(server.getHost(), server.getPort()); if (pipelineConfigurator != null) { builder.pipelineConfigurator(pipelineConfigurator); } return builder.build(); } @Override protected MetricEventsListener<? extends ClientMetricsEvent<?>> createListener( String name) { return UdpClientListener.newUdpListener(name); } }
3,503
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/tcp/LoadBalancingTcpClient.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty.tcp; import java.util.concurrent.ScheduledExecutorService; import io.netty.channel.ChannelOption; import io.reactivex.netty.RxNetty; import io.reactivex.netty.client.ClientBuilder; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.servo.tcp.TcpClientListener; import com.netflix.client.RetryHandler; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.ribbon.transport.netty.LoadBalancingRxClientWithPoolOptions; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; public class LoadBalancingTcpClient<I, O> extends LoadBalancingRxClientWithPoolOptions<I, O, RxClient<I,O>> implements RxClient<I, O> { public LoadBalancingTcpClient(ILoadBalancer lb, IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { super(lb, config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } public LoadBalancingTcpClient(IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { super(config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } @Override protected RxClient<I, O> createRxClient(Server server) { ClientBuilder<I, O> builder = RxNetty.newTcpClientBuilder(server.getHost(), server.getPort()); if (pipelineConfigurator != null) { builder.pipelineConfigurator(pipelineConfigurator); } Integer connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); builder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); if (isPoolEnabled()) { builder.withConnectionPoolLimitStrategy(poolStrategy) .withIdleConnectionsTimeoutMillis(idleConnectionEvictionMills) .withPoolIdleCleanupScheduler(poolCleanerScheduler); } else { builder.withNoConnectionPooling(); } RxClient<I, O> client = builder.build(); return client; } @Override protected MetricEventsListener<? extends ClientMetricsEvent<?>> createListener( String name) { return TcpClientListener.newListener(name); } }
3,504
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/DefaultResponseToErrorPolicy.java
package com.netflix.ribbon.transport.netty.http; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import com.netflix.client.ClientException; public class DefaultResponseToErrorPolicy<O> implements Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> { @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1, Integer backoff) { if (t1.getStatus().equals(HttpResponseStatus.INTERNAL_SERVER_ERROR)) { return Observable.error(new ClientException(ClientException.ErrorType.GENERAL)); } if (t1.getStatus().equals(HttpResponseStatus.SERVICE_UNAVAILABLE) || t1.getStatus().equals(HttpResponseStatus.BAD_GATEWAY) || t1.getStatus().equals(HttpResponseStatus.GATEWAY_TIMEOUT)) { if (backoff > 0) { return Observable.timer(backoff, TimeUnit.MILLISECONDS) .concatMap(new Func1<Long, Observable<HttpClientResponse<O>>>() { @Override public Observable<HttpClientResponse<O>> call(Long t1) { return Observable.error(new ClientException(ClientException.ErrorType.SERVER_THROTTLED)); } }); } else { return Observable.error(new ClientException(ClientException.ErrorType.SERVER_THROTTLED)); } } return Observable.just(t1); } }
3,505
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty.http; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.ChannelOption; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.client.CompositePoolLimitDeterminationStrategy; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.contexts.RxContexts; import io.reactivex.netty.contexts.http.HttpRequestIdProvider; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.pipeline.ssl.DefaultFactories; import io.reactivex.netty.pipeline.ssl.SSLEngineFactory; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientBuilder; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.servo.http.HttpClientListener; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLEngine; import rx.Observable; 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; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.ssl.ClientSslSocketFactoryException; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerStats; import com.netflix.loadbalancer.reactive.ExecutionContext; import com.netflix.loadbalancer.reactive.ExecutionListener; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; import com.netflix.loadbalancer.reactive.ServerOperation; import com.netflix.ribbon.transport.netty.LoadBalancingRxClientWithPoolOptions; /** * A Netty HttpClient that can connect to different servers. Internally it caches the RxNetty's HttpClient, with each created with * a connection pool governed by {@link CompositePoolLimitDeterminationStrategy} that has a global limit and per server limit. * * @author awang */ public class LoadBalancingHttpClient<I, O> extends LoadBalancingRxClientWithPoolOptions<HttpClientRequest<I>, HttpClientResponse<O>, HttpClient<I, O>> implements HttpClient<I, O> { private static final HttpClientConfig DEFAULT_RX_CONFIG = HttpClientConfig.Builder.newDefaultConfig(); private final String requestIdHeaderName; private final HttpRequestIdProvider requestIdProvider; private final List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners; private final LoadBalancerCommand<HttpClientResponse<O>> defaultCommandBuilder; private final Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> responseToErrorPolicy; private final Func1<Integer, Integer> backoffStrategy; public static class Builder<I, O> { ILoadBalancer lb; IClientConfig config; RetryHandler retryHandler; PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator; ScheduledExecutorService poolCleanerScheduler; List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners; Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> responseToErrorPolicy; Func1<Integer, Integer> backoffStrategy; Func1<Builder<I, O>, LoadBalancingHttpClient<I, O>> build; protected Builder(Func1<Builder<I, O>, LoadBalancingHttpClient<I, O>> build) { this.build = build; } public Builder<I, O> withLoadBalancer(ILoadBalancer lb) { this.lb = lb; return this; } public Builder<I, O> withClientConfig(IClientConfig config) { this.config = config; return this; } public Builder<I, O> withRetryHandler(RetryHandler retryHandler) { this.retryHandler = retryHandler; return this; } public Builder<I, O> withPipelineConfigurator(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator) { this.pipelineConfigurator = pipelineConfigurator; return this; } public Builder<I, O> withPoolCleanerScheduler(ScheduledExecutorService poolCleanerScheduler) { this.poolCleanerScheduler = poolCleanerScheduler; return this; } public Builder<I, O> withExecutorListeners(List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners) { this.listeners = listeners; return this; } /** * Policy for converting a response to an error if the status code indicates it as such. This will only * be called for responses with status code 4xx or 5xx * * Parameters to the function are * * HttpClientResponse - The actual response * * Integer - Backoff to apply if this is a retryable error. The backoff amount is in milliseconds * and is based on the configured BackoffStrategy. It is the responsibility of this function * to implement the actual backoff mechanism. This can be done as Observable.error(e).delay(backoff, TimeUnit.MILLISECONDS) * The return Observable will either contain the HttpClientResponse if is it not an error or an * Observable.error() with the translated exception. * * @param responseToErrorPolicy */ public Builder<I, O> withResponseToErrorPolicy(Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> responseToErrorPolicy) { this.responseToErrorPolicy = responseToErrorPolicy; return this; } /** * Strategy for calculating the backoff based on the number of reties. Input is the number * of retries and output is the backoff amount in milliseconds. * The default implementation is non random exponential backoff with time interval configurable * via the property BackoffInterval (default 1000 msec) * * @param backoffStrategy */ public Builder<I, O> withBackoffStrategy(Func1<Integer, Integer> backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } public LoadBalancingHttpClient<I, O> build() { if (retryHandler == null) { retryHandler = new NettyHttpLoadBalancerErrorHandler(); } if (config == null) { config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); } if (lb == null) { lb = LoadBalancerBuilder.newBuilder().withClientConfig(config).buildLoadBalancerFromConfigWithReflection(); } if (listeners == null) { listeners = Collections.<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>>emptyList(); } if (backoffStrategy == null) { backoffStrategy = new Func1<Integer, Integer>() { @Override public Integer call(Integer backoffCount) { int interval = config.getOrDefault(IClientConfigKey.Keys.BackoffInterval); if (backoffCount < 0) { backoffCount = 0; } else if (backoffCount > 10) { // Reasonable upper bound backoffCount = 10; } return (int)Math.pow(2, backoffCount) * interval; } }; } if (responseToErrorPolicy == null) { responseToErrorPolicy = new DefaultResponseToErrorPolicy<O>(); } return build.call(this); } } public static <I, O> Builder<I, O> builder() { return new Builder<I, O>(new Func1<Builder<I, O>, LoadBalancingHttpClient<I, O>>() { @Override public LoadBalancingHttpClient<I, O> call(Builder<I, O> builder) { return new LoadBalancingHttpClient<I, O>(builder); } }); } protected LoadBalancingHttpClient(Builder<I, O> builder) { super(builder.lb, builder.config, new RequestSpecificRetryHandler(true, true, builder.retryHandler, null), builder.pipelineConfigurator, builder.poolCleanerScheduler); requestIdHeaderName = getProperty(IClientConfigKey.Keys.RequestIdHeaderName, null, null); requestIdProvider = (requestIdHeaderName != null) ? new HttpRequestIdProvider(requestIdHeaderName, RxContexts.DEFAULT_CORRELATOR) : null; this.listeners = new CopyOnWriteArrayList<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>>(builder.listeners); defaultCommandBuilder = LoadBalancerCommand.<HttpClientResponse<O>>builder() .withLoadBalancerContext(lbContext) .withListeners(this.listeners) .withClientConfig(builder.config) .withRetryHandler(builder.retryHandler) .build(); this.responseToErrorPolicy = builder.responseToErrorPolicy; this.backoffStrategy = builder.backoffStrategy; } private RetryHandler getRequestRetryHandler(HttpClientRequest<?> request, IClientConfig requestConfig) { return new RequestSpecificRetryHandler( true, request.getMethod().equals(HttpMethod.GET), // Default only allows retrys for GET defaultRetryHandler, requestConfig); } protected static void setHostHeader(HttpClientRequest<?> request, String host) { request.getHeaders().set(HttpHeaders.Names.HOST, host); } /** * Submit a request to server chosen by the load balancer to execute. An error will be emitted from the returned {@link Observable} if * there is no server available from load balancer. */ @Override public Observable<HttpClientResponse<O>> submit(HttpClientRequest<I> request) { return submit(request, null, null); } /** * Submit a request to server chosen by the load balancer to execute. An error will be emitted from the returned {@link Observable} if * there is no server available from load balancer. * * @param config An {@link ClientConfig} to override the default configuration for the client. Can be null. * @return */ @Override public Observable<HttpClientResponse<O>> submit(final HttpClientRequest<I> request, final ClientConfig config) { return submit(null, request, null, null, config); } /** * Submit a request to run on a specific server * * @param server * @param request * @param requestConfig * @return */ public Observable<HttpClientResponse<O>> submit(Server server, final HttpClientRequest<I> request, final IClientConfig requestConfig) { return submit(server, request, null, requestConfig, getRxClientConfig(requestConfig)); } /** * Submit a request to server chosen by the load balancer to execute. An error will be emitted from the returned {@link Observable} if * there is no server available from load balancer. * * @param errorHandler A handler to determine the load balancer retry logic. If null, the default one will be used. * @param requestConfig An {@link IClientConfig} to override the default configuration for the client. Can be null. * @return */ public Observable<HttpClientResponse<O>> submit(final HttpClientRequest<I> request, final RetryHandler errorHandler, final IClientConfig requestConfig) { return submit(null, request, errorHandler, requestConfig, null); } public Observable<HttpClientResponse<O>> submit(Server server, final HttpClientRequest<I> request) { return submit(server, request, null, null, getRxClientConfig(null)); } /** * Convert an HttpClientRequest to a ServerOperation * * @param request * @param rxClientConfig * @return */ protected ServerOperation<HttpClientResponse<O>> requestToOperation(final HttpClientRequest<I> request, final ClientConfig rxClientConfig) { Preconditions.checkNotNull(request); return new ServerOperation<HttpClientResponse<O>>() { final AtomicInteger count = new AtomicInteger(0); @Override public Observable<HttpClientResponse<O>> call(Server server) { HttpClient<I,O> rxClient = getOrCreateRxClient(server); setHostHeader(request, server.getHost()); Observable<HttpClientResponse<O>> o; if (rxClientConfig != null) { o = rxClient.submit(request, rxClientConfig); } else { o = rxClient.submit(request); } return o.concatMap(new Func1<HttpClientResponse<O>, Observable<HttpClientResponse<O>>>() { @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1) { if (t1.getStatus().code()/100 == 4 || t1.getStatus().code()/100 == 5) return responseToErrorPolicy.call(t1, backoffStrategy.call(count.getAndIncrement())); else return Observable.just(t1); } }); } }; } /** * Construct an RxClient.ClientConfig from an IClientConfig * * @param requestConfig * @return */ private RxClient.ClientConfig getRxClientConfig(IClientConfig requestConfig) { if (requestConfig == null) { return DEFAULT_RX_CONFIG; } int requestReadTimeout = getProperty(IClientConfigKey.Keys.ReadTimeout, requestConfig, DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT); Boolean followRedirect = getProperty(IClientConfigKey.Keys.FollowRedirects, requestConfig, null); HttpClientConfig.Builder builder = new HttpClientConfig.Builder().readTimeout(requestReadTimeout, TimeUnit.MILLISECONDS); if (followRedirect != null) { builder.setFollowRedirect(followRedirect); } return builder.build(); } /** * @return ClientConfig that is merged from IClientConfig and ClientConfig in the method arguments */ private RxClient.ClientConfig getRxClientConfig(IClientConfig ribbonClientConfig, ClientConfig rxClientConfig) { if (ribbonClientConfig == null) { return rxClientConfig; } else if (rxClientConfig == null) { return getRxClientConfig(ribbonClientConfig); } int readTimeoutFormRibbon = ribbonClientConfig.get(CommonClientConfigKey.ReadTimeout, -1); if (rxClientConfig instanceof HttpClientConfig) { HttpClientConfig httpConfig = (HttpClientConfig) rxClientConfig; HttpClientConfig.Builder builder = HttpClientConfig.Builder.from(httpConfig); if (readTimeoutFormRibbon >= 0) { builder.readTimeout(readTimeoutFormRibbon, TimeUnit.MILLISECONDS); } return builder.build(); } else { RxClient.ClientConfig.Builder builder = new RxClient.ClientConfig.Builder(rxClientConfig); if (readTimeoutFormRibbon >= 0) { builder.readTimeout(readTimeoutFormRibbon, TimeUnit.MILLISECONDS); } return builder.build(); } } private IClientConfig getRibbonClientConfig(ClientConfig rxClientConfig) { if (rxClientConfig != null && rxClientConfig.isReadTimeoutSet()) { return IClientConfig.Builder.newBuilder().withReadTimeout((int) rxClientConfig.getReadTimeoutInMillis()).build(); } return null; } /** * Subject an operation to run in the load balancer * * @param request * @param errorHandler * @param requestConfig * @param rxClientConfig * @return */ private Observable<HttpClientResponse<O>> submit(final Server server, final HttpClientRequest<I> request, final RetryHandler errorHandler, final IClientConfig requestConfig, final ClientConfig rxClientConfig) { RetryHandler retryHandler = errorHandler; if (retryHandler == null) { retryHandler = getRequestRetryHandler(request, requestConfig); } final IClientConfig config = requestConfig == null ? DefaultClientConfigImpl.getEmptyConfig() : requestConfig; final ExecutionContext<HttpClientRequest<I>> context = new ExecutionContext<HttpClientRequest<I>>(request, config, this.getClientConfig(), retryHandler); Observable<HttpClientResponse<O>> result = submitToServerInURI(request, config, rxClientConfig, retryHandler, context); if (result == null) { LoadBalancerCommand<HttpClientResponse<O>> command; if (retryHandler != defaultRetryHandler) { // need to create new builder instead of the default one command = LoadBalancerCommand.<HttpClientResponse<O>>builder() .withExecutionContext(context) .withLoadBalancerContext(lbContext) .withListeners(listeners) .withClientConfig(this.getClientConfig()) .withRetryHandler(retryHandler) .withServer(server) .build(); } else { command = defaultCommandBuilder; } result = command.submit(requestToOperation(request, getRxClientConfig(config, rxClientConfig))); } return result; } @VisibleForTesting ServerStats getServerStats(Server server) { return lbContext.getServerStats(server); } /** * Submits the request to the server indicated in the URI * @param request * @param requestConfig * @param config * @param errorHandler * @param context * @return */ private Observable<HttpClientResponse<O>> submitToServerInURI( HttpClientRequest<I> request, IClientConfig requestConfig, ClientConfig config, RetryHandler errorHandler, ExecutionContext<HttpClientRequest<I>> context) { // First, determine server from the URI URI uri; try { uri = new URI(request.getUri()); } catch (URISyntaxException e) { return Observable.error(e); } String host = uri.getHost(); if (host == null) { return null; } int port = uri.getPort(); if (port < 0) { if (clientConfig.get(IClientConfigKey.Keys.IsSecure, false)) { port = 443; } else { port = 80; } } return LoadBalancerCommand.<HttpClientResponse<O>>builder() .withRetryHandler(errorHandler) .withLoadBalancerContext(lbContext) .withListeners(listeners) .withExecutionContext(context) .withServer(new Server(host, port)) .build() .submit(this.requestToOperation(request, getRxClientConfig(requestConfig, config))); } @Override protected HttpClient<I, O> createRxClient(Server server) { HttpClientBuilder<I, O> clientBuilder; if (requestIdProvider != null) { clientBuilder = RxContexts.<I, O>newHttpClientBuilder(server.getHost(), server.getPort(), requestIdProvider, RxContexts.DEFAULT_CORRELATOR, pipelineConfigurator); } else { clientBuilder = RxContexts.<I, O>newHttpClientBuilder(server.getHost(), server.getPort(), RxContexts.DEFAULT_CORRELATOR, pipelineConfigurator); } Integer connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); Integer readTimeout = getProperty(IClientConfigKey.Keys.ReadTimeout, null, DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT); Boolean followRedirect = getProperty(IClientConfigKey.Keys.FollowRedirects, null, null); HttpClientConfig.Builder builder = new HttpClientConfig.Builder().readTimeout(readTimeout, TimeUnit.MILLISECONDS); if (followRedirect != null) { builder.setFollowRedirect(followRedirect); } clientBuilder .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout) .config(builder.build()); if (isPoolEnabled()) { clientBuilder .withConnectionPoolLimitStrategy(poolStrategy) .withIdleConnectionsTimeoutMillis(idleConnectionEvictionMills) .withPoolIdleCleanupScheduler(poolCleanerScheduler); } else { clientBuilder .withNoConnectionPooling(); } if (sslContextFactory != null) { try { SSLEngineFactory myFactory = new DefaultFactories.SSLContextBasedFactory(sslContextFactory.getSSLContext()) { @Override public SSLEngine createSSLEngine(ByteBufAllocator allocator) { SSLEngine myEngine = super.createSSLEngine(allocator); myEngine.setUseClientMode(true); return myEngine; } }; clientBuilder.withSslEngineFactory(myFactory); } catch (ClientSslSocketFactoryException e) { throw new RuntimeException(e); } } return clientBuilder.build(); } @VisibleForTesting HttpClientListener getListener() { return (HttpClientListener) listener; } @VisibleForTesting Map<Server, HttpClient<I, O>> getRxClients() { return rxClientCache; } @Override protected MetricEventsListener<? extends ClientMetricsEvent<?>> createListener(String name) { return HttpClientListener.newHttpListener(name); } }
3,506
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/SSEClient.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty.http; import io.netty.channel.ChannelOption; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientBuilder; import io.reactivex.netty.protocol.text.sse.ServerSentEvent; import rx.functions.Func1; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfigKey; import com.netflix.loadbalancer.Server; public class SSEClient<I> extends LoadBalancingHttpClient<I, ServerSentEvent> { public static <I> Builder<I, ServerSentEvent> sseClientBuilder() { return new Builder<I, ServerSentEvent>(new Func1<Builder<I, ServerSentEvent>, LoadBalancingHttpClient<I, ServerSentEvent>>() { @Override public LoadBalancingHttpClient<I, ServerSentEvent> call(Builder<I, ServerSentEvent> t1) { return new SSEClient<I>(t1); } }); } private SSEClient(LoadBalancingHttpClient.Builder<I, ServerSentEvent> t1) { super(t1); } @Override protected HttpClient<I, ServerSentEvent> getOrCreateRxClient(Server server) { HttpClientBuilder<I, ServerSentEvent> clientBuilder = new HttpClientBuilder<I, ServerSentEvent>(server.getHost(), server.getPort()).pipelineConfigurator(pipelineConfigurator); int requestConnectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); RxClient.ClientConfig rxClientConfig = new HttpClientConfig.Builder().build(); HttpClient<I, ServerSentEvent> client = clientBuilder.channelOption( ChannelOption.CONNECT_TIMEOUT_MILLIS, requestConnectTimeout).config(rxClientConfig).build(); return client; } @Override public void shutdown() { } }
3,507
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/NettyHttpLoadBalancerErrorHandler.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.transport.netty.http; import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; 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; import com.netflix.client.http.UnexpectedHttpResponseException; public class NettyHttpLoadBalancerErrorHandler extends DefaultLoadBalancerRetryHandler { @SuppressWarnings("unchecked") private List<Class<? extends Throwable>> retriable = Lists.<Class<? extends Throwable>>newArrayList(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<Class<? extends Throwable>> circuitRelated = Lists.<Class<? extends Throwable>>newArrayList(SocketException.class, SocketTimeoutException.class, io.netty.handler.timeout.ReadTimeoutException.class, io.netty.channel.ConnectTimeoutException.class, io.reactivex.netty.client.PoolExhaustedException.class); public NettyHttpLoadBalancerErrorHandler() { super(); } public NettyHttpLoadBalancerErrorHandler(IClientConfig clientConfig) { super(clientConfig); } public NettyHttpLoadBalancerErrorHandler(int retrySameServer, int retryNextServer, boolean retryEnabled) { super(retrySameServer, retryNextServer, retryEnabled); } /** * @return true if the Throwable has one of the following exception type as a cause: * {@link SocketException}, {@link SocketTimeoutException} */ @Override public boolean isCircuitTrippingException(Throwable e) { if (e instanceof UnexpectedHttpResponseException) { return ((UnexpectedHttpResponseException) e).getStatusCode() == 503; } else if (e instanceof ClientException) { return ((ClientException) e).getErrorType() == ClientException.ErrorType.SERVER_THROTTLED; } return super.isCircuitTrippingException(e); } @Override public boolean isRetriableException(Throwable e, boolean sameServer) { if (e instanceof ClientException) { ClientException ce = (ClientException) e; if (ce.getErrorType() == ClientException.ErrorType.SERVER_THROTTLED) { return !sameServer && retryEnabled; } } return super.isRetriableException(e, sameServer); } @Override protected List<Class<? extends Throwable>> getRetriableExceptions() { return retriable; } @Override protected List<Class<? extends Throwable>> getCircuitRelatedExceptions() { return circuitRelated; } }
3,508
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/RxMovieProxyExampleTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.examples.rx; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Scopes; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import com.netflix.config.ConfigurationManager; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.RibbonTransportFactory.DefaultRibbonTransportFactory; import com.netflix.ribbon.examples.rx.proxy.MovieService; import com.netflix.ribbon.examples.rx.proxy.RxMovieProxyExample; import com.netflix.ribbon.guice.RibbonModule; import com.netflix.ribbon.guice.RibbonResourceProvider; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider.DefaultAnnotationProcessorsProvider; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClient; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class RxMovieProxyExampleTest extends RxMovieClientTestBase { static class MyClientConfigFactory implements ClientConfigFactory { @Override public IClientConfig newConfig() { return new DefaultClientConfigImpl() { @Override public String getNameSpace() { return "MyConfig"; } }; } } @Test public void shouldBind() { ConfigurationManager.getConfigInstance().setProperty(MovieService.class.getSimpleName() + ".ribbon.listOfServers", "localhost:" + port); Injector injector = Guice.createInjector( new RibbonModule(), new AbstractModule() { @Override protected void configure() { bind(MovieService.class).toProvider(new RibbonResourceProvider<MovieService>(MovieService.class)).asEagerSingleton(); } } ); RxMovieProxyExample example = injector.getInstance(RxMovieProxyExample.class); assertTrue(example.runExample()); } @Test public void shouldBindCustomClientConfigFactory() { ConfigurationManager.getConfigInstance().setProperty(MovieService.class.getSimpleName() + ".MyConfig.listOfServers", "localhost:" + port); Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(RibbonResourceFactory.class).to(DefaultResourceFactory.class).in(Scopes.SINGLETON); bind(RibbonTransportFactory.class).to(DefaultRibbonTransportFactory.class).in(Scopes.SINGLETON); bind(AnnotationProcessorsProvider.class).to(DefaultAnnotationProcessorsProvider.class).in(Scopes.SINGLETON); bind(ClientConfigFactory.class).to(MyClientConfigFactory.class).in(Scopes.SINGLETON); } }, new AbstractModule() { @Override protected void configure() { bind(MovieService.class).toProvider(new RibbonResourceProvider<MovieService>(MovieService.class)).asEagerSingleton(); } } ); RxMovieProxyExample example = injector.getInstance(RxMovieProxyExample.class); assertTrue(example.runExample()); } @Test public void testTransportFactoryWithInjection() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(ClientConfigFactory.class).to(MyClientConfigFactory.class).in(Scopes.SINGLETON); bind(RibbonTransportFactory.class).to(DefaultRibbonTransportFactory.class).in(Scopes.SINGLETON); } } ); RibbonTransportFactory transportFactory = injector.getInstance(RibbonTransportFactory.class); HttpClient<ByteBuf, ByteBuf> client = transportFactory.newHttpClient("myClient"); IClientConfig config = ((LoadBalancingHttpClient) client).getClientConfig(); assertEquals("MyConfig", config.getNameSpace()); } }
3,509
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/RxMovieClientTestBase.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.examples.rx; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServer; import org.junit.After; import org.junit.Before; /** * @author Tomasz Bak */ public class RxMovieClientTestBase { protected int port = 0; private RxMovieServer movieServer; private HttpServer<ByteBuf, ByteBuf> httpServer; @Before public void setUp() throws Exception { movieServer = new RxMovieServer(port); httpServer = movieServer.createServer().start(); port = httpServer.getServerPort(); } @After public void tearDown() throws Exception { httpServer.shutdown(); } }
3,510
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/RibbonModuleTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.examples.rx; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.ribbon.ClientOptions; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.examples.rx.common.RecommendationServiceFallbackHandler; import com.netflix.ribbon.examples.rx.common.RecommendationServiceResponseValidator; import com.netflix.ribbon.examples.rx.common.RxMovieTransformer; import com.netflix.ribbon.guice.RibbonModule; import com.netflix.ribbon.http.HttpRequestTemplate; import com.netflix.ribbon.http.HttpResourceGroup; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.StringTransformer; import org.junit.Test; import rx.Observable; import javax.inject.Inject; import javax.inject.Singleton; public class RibbonModuleTest { private static final int PORT = 7001; @Singleton public static class MyService extends AbstractRxMovieClient { private final HttpResourceGroup httpResourceGroup; private final HttpRequestTemplate<ByteBuf> registerMovieTemplate; private final HttpRequestTemplate<ByteBuf> updateRecommendationTemplate; private final HttpRequestTemplate<ByteBuf> recommendationsByUserIdTemplate; private final HttpRequestTemplate<ByteBuf> recommendationsByTemplate; @Inject public MyService(RibbonResourceFactory factory) { httpResourceGroup = factory.createHttpResourceGroup("movieServiceClient", ClientOptions.create() .withMaxAutoRetriesNextServer(3) .withConfigurationBasedServerList("localhost:" + PORT)); registerMovieTemplate = httpResourceGroup.newTemplateBuilder("registerMovie", ByteBuf.class) .withMethod("POST") .withUriTemplate("/movies") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withResponseValidator(new RecommendationServiceResponseValidator()).build(); updateRecommendationTemplate = httpResourceGroup.newTemplateBuilder("updateRecommendation", ByteBuf.class) .withMethod("POST") .withUriTemplate("/users/{userId}/recommendations") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withResponseValidator(new RecommendationServiceResponseValidator()).build(); recommendationsByUserIdTemplate = httpResourceGroup.newTemplateBuilder("recommendationsByUserId", ByteBuf.class) .withMethod("GET") .withUriTemplate("/users/{userId}/recommendations") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withFallbackProvider(new RecommendationServiceFallbackHandler()) .withResponseValidator(new RecommendationServiceResponseValidator()).build(); recommendationsByTemplate = httpResourceGroup.newTemplateBuilder("recommendationsBy", ByteBuf.class) .withMethod("GET") .withUriTemplate("/recommendations?category={category}&ageGroup={ageGroup}") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withFallbackProvider(new RecommendationServiceFallbackHandler()) .withResponseValidator(new RecommendationServiceResponseValidator()).build(); } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerMoviesRegistration() { return new Observable[]{ registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.ORANGE_IS_THE_NEW_BLACK), new RxMovieTransformer()) .build().toObservable(), registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.BREAKING_BAD), new RxMovieTransformer()) .build().toObservable(), registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.HOUSE_OF_CARDS), new RxMovieTransformer()) .build().toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsUpdate() { return new Observable[]{ updateRecommendationTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.ORANGE_IS_THE_NEW_BLACK.getId()), new StringTransformer()) .withRequestProperty("userId", TEST_USER) .build().toObservable(), updateRecommendationTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.BREAKING_BAD.getId()), new StringTransformer()) .withRequestProperty("userId", TEST_USER) .build().toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsSearch() { return new Observable[]{ recommendationsByUserIdTemplate.requestBuilder() .withRequestProperty("userId", TEST_USER) .build().toObservable(), recommendationsByTemplate.requestBuilder() .withRequestProperty("category", "Drama") .withRequestProperty("ageGroup", "Adults") .build().toObservable() }; } } @Test public void shouldBind() { Injector injector = Guice.createInjector( new RibbonModule() ); MyService service = injector.getInstance(MyService.class); service.runExample(); } }
3,511
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/proxy/RxMovieProxyExample.java
package com.netflix.ribbon.examples.rx.proxy; import io.netty.buffer.ByteBuf; import javax.inject.Inject; import rx.Observable; import com.google.inject.Singleton; import com.netflix.ribbon.examples.rx.AbstractRxMovieClient; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.examples.rx.proxy.MovieService; import com.netflix.ribbon.proxy.ProxyLifeCycle; @Singleton public class RxMovieProxyExample extends AbstractRxMovieClient { private final MovieService movieService; @Inject public RxMovieProxyExample(MovieService movieService) { this.movieService = movieService; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerMoviesRegistration() { return new Observable[]{ movieService.registerMovie(Movie.ORANGE_IS_THE_NEW_BLACK).toObservable(), movieService.registerMovie(Movie.BREAKING_BAD).toObservable(), movieService.registerMovie(Movie.HOUSE_OF_CARDS).toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsUpdate() { return new Observable[]{ movieService.updateRecommendations(TEST_USER, Movie.ORANGE_IS_THE_NEW_BLACK.getId()).toObservable(), movieService.updateRecommendations(TEST_USER, Movie.BREAKING_BAD.getId()).toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsSearch() { return new Observable[]{ movieService.recommendationsByUserId(TEST_USER).toObservable(), movieService.recommendationsBy("Drama", "Adults").toObservable() }; } @Override public void shutdown() { super.shutdown(); ((ProxyLifeCycle) movieService).shutdown(); } }
3,512
0
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon/guice/RibbonResourceProvider.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.guice; import com.google.inject.Inject; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderWithExtensionVisitor; import com.google.inject.spi.Toolable; import com.netflix.ribbon.RibbonResourceFactory; /** * Guice Provider extension to create a ribbon resource from an injectable * RibbonResourceFactory. * * @author elandau * * @param <T> Type of the client API interface class */ public class RibbonResourceProvider<T> implements ProviderWithExtensionVisitor<T> { private RibbonResourceFactory factory; private final Class<T> contract; public RibbonResourceProvider(Class<T> contract) { this.contract = contract; } @Override public T get() { // TODO: Get name from annotations (not only class name of contract) return factory.from(contract); } /** * This is needed for 'initialize(injector)' below to be called so the provider * can get the injector after it is instantiated. */ @Override public <B, V> V acceptExtensionVisitor( BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @Inject @Toolable protected void initialize(RibbonResourceFactory factory) { this.factory = factory; } }
3,513
0
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon/guice/RibbonModule.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.guice; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.RibbonTransportFactory.DefaultRibbonTransportFactory; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider.DefaultAnnotationProcessorsProvider; /** * Default bindings for Ribbon * * @author elandau * */ public class RibbonModule extends AbstractModule { @Override protected void configure() { bind(ClientConfigFactory.class).toInstance(ClientConfigFactory.DEFAULT); bind(RibbonTransportFactory.class).to(DefaultRibbonTransportFactory.class).in(Scopes.SINGLETON); bind(AnnotationProcessorsProvider.class).to(DefaultAnnotationProcessorsProvider.class).in(Scopes.SINGLETON); bind(RibbonResourceFactory.class).to(DefaultResourceFactory.class).in(Scopes.SINGLETON); } }
3,514
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/DefaultNIWSServerListFilterTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.niws.loadbalancer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import com.netflix.config.ConfigurationBasedDeploymentContext; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.client.ClientFactory; import com.netflix.config.ConfigurationManager; import com.netflix.config.DeploymentContext.ContextKey; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.LoadBalancerStats; import com.netflix.loadbalancer.ZoneAffinityServerListFilter; public class DefaultNIWSServerListFilterTest { @BeforeClass public static void init() { ConfigurationManager.getConfigInstance().setProperty(ContextKey.zone.getKey(), "us-eAst-1C"); } private DiscoveryEnabledServer createServer(String host, String zone) { return createServer(host, 7001, zone); } private DiscoveryEnabledServer createServer(String host, int port, String zone) { AmazonInfo amazonInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, zone).build(); Builder builder = InstanceInfo.Builder.newBuilder(); InstanceInfo info = builder.setAppName("l10nservicegeneral") .setDataCenterInfo(amazonInfo) .setHostName(host) .setPort(port) .build(); DiscoveryEnabledServer server = new DiscoveryEnabledServer(info, false, false); server.setZone(zone); return server; } private DiscoveryEnabledServer createServer(int hostId, String zoneSuffix) { return createServer(zoneSuffix + "-" + "server" + hostId, "Us-east-1" + zoneSuffix); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testZoneAffinityEnabled() throws Exception { ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.DeploymentContextBasedVipAddresses", "l10nservicegeneral.cloud.netflix.net:7001"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.NFLoadBalancerClassName", DynamicServerListLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.EnableZoneAffinity", "true"); DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("DefaultNIWSServerListFilterTest1"); assertTrue(lb.getRule() instanceof AvailabilityFilteringRule); ZoneAffinityServerListFilter filter = (ZoneAffinityServerListFilter) lb.getFilter(); LoadBalancerStats loadBalancerStats = lb.getLoadBalancerStats(); List<DiscoveryEnabledServer> servers = new ArrayList<DiscoveryEnabledServer>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); servers.add(createServer(3, "c")); servers.add(createServer(4, "c")); servers.add(createServer(5, "c")); List<DiscoveryEnabledServer> filtered = filter.getFilteredListOfServers(servers); List<DiscoveryEnabledServer> expected = new ArrayList<DiscoveryEnabledServer>(); expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); expected.add(createServer(4, "c")); expected.add(createServer(5, "c")); assertEquals(expected, filtered); lb.setServersList(filtered); for (int i = 1; i <= 4; i++) { loadBalancerStats.incrementActiveRequestsCount(createServer(i, "c")); } filtered = filter.getFilteredListOfServers(servers); assertEquals(servers, filtered); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testZoneExclusivity() throws Exception { ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.DeploymentContextBasedVipAddresses", "l10nservicegeneral.cloud.netflix.net:7001"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.NFLoadBalancerClassName", DynamicServerListLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.EnableZoneExclusivity", "true"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("DefaultNIWSServerListFilterTest2"); ZoneAffinityServerListFilter filter = (ZoneAffinityServerListFilter) lb.getFilter(); LoadBalancerStats loadBalancerStats = lb.getLoadBalancerStats(); List<DiscoveryEnabledServer> servers = new ArrayList<DiscoveryEnabledServer>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); servers.add(createServer(3, "c")); servers.add(createServer(4, "c")); servers.add(createServer(5, "c")); List<DiscoveryEnabledServer> filtered = filter.getFilteredListOfServers(servers); List<DiscoveryEnabledServer> expected = new ArrayList<DiscoveryEnabledServer>(); expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); expected.add(createServer(4, "c")); expected.add(createServer(5, "c")); assertEquals(expected, filtered); lb.setServersList(filtered); for (int i = 1; i <= 4; i++) { loadBalancerStats.incrementActiveRequestsCount(createServer(i, "c")); } filtered = filter.getFilteredListOfServers(servers); assertEquals(expected, filtered); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testZoneAffinityOverride() throws Exception { ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.DeploymentContextBasedVipAddresses", "l10nservicegeneral.cloud.netflix.net:7001"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.NFLoadBalancerClassName", DynamicServerListLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.EnableZoneAffinity", "true"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.zoneAffinity.minAvailableServers", "3"); DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("DefaultNIWSServerListFilterTest3"); ZoneAffinityServerListFilter filter = (ZoneAffinityServerListFilter) lb.getFilter(); LoadBalancerStats loadBalancerStats = lb.getLoadBalancerStats(); List<DiscoveryEnabledServer> servers = new ArrayList<DiscoveryEnabledServer>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); List<DiscoveryEnabledServer> filtered = filter.getFilteredListOfServers(servers); List<DiscoveryEnabledServer> expected = new ArrayList<DiscoveryEnabledServer>(); /* expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); expected.add(createServer(4, "c")); expected.add(createServer(5, "c")); */ // less than 3 servers in zone c, will not honor zone affinity assertEquals(servers, filtered); lb.setServersList(filtered); servers.add(createServer(3, "c")); filtered = filter.getFilteredListOfServers(servers); expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); filtered = filter.getFilteredListOfServers(servers); // now we have enough servers in C assertEquals(expected, filtered); // make one server black out for (int i = 1; i <= 3; i++) { loadBalancerStats.incrementSuccessiveConnectionFailureCount(createServer(1, "c")); } filtered = filter.getFilteredListOfServers(servers); assertEquals(servers, filtered); // new server added in zone c, zone c should now have enough servers servers.add(createServer(4, "c")); filtered = filter.getFilteredListOfServers(servers); expected.add(createServer(4, "c")); assertEquals(expected, filtered); } }
3,515
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/DiscoveryEnabledLoadBalancerSupportsPortOverrideTest.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.niws.loadbalancer; import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.List; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Verify behavior of the override flag ForceClientPortConfiguration("ForceClientPortConfiguration") * * WARNING: This feature should be treated as temporary workaround to support * more than 2 ports per server until relevant load balancer paradigms * (i.e., Eureka Server/Client) can accommodate more than 2 ports in its metadata. * * Currently only works with the DiscoveryEnabledNIWSServerList since this is where the current limitation is applicable * * See also: https://github.com/Netflix/eureka/issues/71 * * I'll add that testing this is painful due to the DiscoveryManager.getInstance()... singletons man... * * Created by jzarfoss on 1/7/14. */ @RunWith(PowerMockRunner.class) @PrepareForTest( {DiscoveryManager.class, DiscoveryClient.class} ) @PowerMockIgnore("javax.management.*") @SuppressWarnings("PMD.AvoidUsingHardCodedIP") public class DiscoveryEnabledLoadBalancerSupportsPortOverrideTest { @Before public void setupMock(){ List<InstanceInfo> dummyII = LoadBalancerTestUtils.getDummyInstanceInfo("dummy", "http://www.host.com", "1.1.1.1", 8001); List<InstanceInfo> secureDummyII = LoadBalancerTestUtils.getDummyInstanceInfo("secureDummy", "http://www.host.com", "1.1.1.1", 8002); PowerMock.mockStatic(DiscoveryManager.class); PowerMock.mockStatic(DiscoveryClient.class); DiscoveryClient mockedDiscoveryClient = LoadBalancerTestUtils.mockDiscoveryClient(); DiscoveryManager mockedDiscoveryManager = createMock(DiscoveryManager.class); expect(DiscoveryManager.getInstance()).andReturn(mockedDiscoveryManager).anyTimes(); expect(mockedDiscoveryManager.getDiscoveryClient()).andReturn(mockedDiscoveryClient).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress("dummy", false, "region")).andReturn(dummyII).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress("secureDummy", true, "region")).andReturn(secureDummyII).anyTimes(); replay(DiscoveryManager.class); replay(DiscoveryClient.class); replay(mockedDiscoveryManager); replay(mockedDiscoveryClient); } @After public void afterMock(){ verify(DiscoveryManager.class); verify(DiscoveryClient.class); } @Test public void testDefaultHonorsVipPortDefinition() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.Port", "6999"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testDefaultHonorsVipPortDefinition"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(8001, serverList.get(0).getPort()); // vip indicated Assert.assertEquals(8001, serverList.get(0).getInstanceInfo().getPort()); // vip indicated Assert.assertEquals(7002, serverList.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } @Test public void testDefaultHonorsVipSecurePortDefinition() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.DeploymentContextBasedVipAddresses", "secureDummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.IsSecure", "true"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.SecurePort", "6002"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(8002, serverList.get(0).getPort()); // vip indicated Assert.assertEquals(8002, serverList.get(0).getInstanceInfo().getPort()); // vip indicated Assert.assertEquals(7002, serverList.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } @Test public void testVipPortCanBeOverriden() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.Port", "6001"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.ForceClientPortConfiguration", "true"); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testVipPortCanBeOverriden"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(6001, serverList.get(0).getPort()); // client property indicated Assert.assertEquals(6001, serverList.get(0).getInstanceInfo().getPort()); // client property indicated Assert.assertEquals(7002, serverList.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } @Test public void testSecureVipPortCanBeOverriden() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.DeploymentContextBasedVipAddresses", "secureDummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.IsSecure", "true"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.SecurePort", "6002"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.ForceClientPortConfiguration", "true"); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testSecureVipPortCanBeOverriden"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(8002, serverList.get(0).getPort()); // vip indicated Assert.assertEquals(8002, serverList.get(0).getInstanceInfo().getPort()); // vip indicated Assert.assertEquals(6002, serverList.get(0).getInstanceInfo().getSecurePort()); // client property indicated } /** * Tests case where two different clients want to use the same instance, one with overriden ports and one without * * @throws Exception for anything unexpected */ @Test public void testTwoInstancesDontStepOnEachOther() throws Exception{ // setup override client ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.Port", "6001"); // override from 8001 ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.ForceClientPortConfiguration", "true"); // setup non override client ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.Port", "6001"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.ForceClientPortConfiguration", "false"); // check override client DiscoveryEnabledNIWSServerList deList1 = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig1 = DefaultClientConfigImpl.class.newInstance(); clientConfig1.loadProperties("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1"); deList1.initWithNiwsConfig(clientConfig1); List<DiscoveryEnabledServer> serverList1 = deList1.getInitialListOfServers(); Assert.assertEquals(1, serverList1.size()); Assert.assertEquals(6001, serverList1.get(0).getPort()); // client property overridden Assert.assertEquals(6001, serverList1.get(0).getInstanceInfo().getPort()); // client property overridden Assert.assertEquals(7002, serverList1.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default // check non-override client DiscoveryEnabledNIWSServerList deList2 = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig2 = DefaultClientConfigImpl.class.newInstance(); clientConfig2.loadProperties("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2"); deList2.initWithNiwsConfig(clientConfig2); List<DiscoveryEnabledServer> serverList2 = deList2.getInitialListOfServers(); Assert.assertEquals(1, serverList2.size()); Assert.assertEquals(8001, serverList2.get(0).getPort()); // client property indicated in ii Assert.assertEquals(8001, serverList2.get(0).getInstanceInfo().getPort()); // client property indicated in ii Assert.assertEquals(7002, serverList2.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } }
3,516
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdaterTest.java
package com.netflix.niws.loadbalancer; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaEventListener; import com.netflix.loadbalancer.ServerListUpdater; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; 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; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * @author David Liu */ public class EurekaNotificationServerListUpdaterTest { private EurekaClient eurekaClientMock; private EurekaClient eurekaClientMock2; private ThreadPoolExecutor testExecutor; @Before public void setUp() { eurekaClientMock = setUpEurekaClientMock(); eurekaClientMock2 = setUpEurekaClientMock(); // use a test executor so that the tests do not share executors testExecutor = new ThreadPoolExecutor( 2, 2 * 5, 0, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(1000), new ThreadFactoryBuilder() .setNameFormat("EurekaNotificationServerListUpdater-%d") .setDaemon(true) .build() ); } @Test public void testUpdating() throws Exception { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); final AtomicBoolean firstTime = new AtomicBoolean(false); final CountDownLatch firstLatch = new CountDownLatch(1); final CountDownLatch secondLatch = new CountDownLatch(1); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { if (firstTime.compareAndSet(false, true)) { firstLatch.countDown(); } else { secondLatch.countDown(); } } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(firstLatch.await(2, TimeUnit.SECONDS)); // wait a bit for the updateQueued flag to be reset for (int i = 1; i < 10; i++) { if (serverListUpdater.updateQueued.get()) { Thread.sleep(i * 100); } else { break; } } eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(secondLatch.await(2, TimeUnit.SECONDS)); } finally { serverListUpdater.stop(); EasyMock.verify(eurekaClientMock); } } @Test public void testStopWithCommonExecutor() throws Exception { EurekaNotificationServerListUpdater serverListUpdater1 = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); EurekaNotificationServerListUpdater serverListUpdater2 = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock2; } }, testExecutor ); Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); Capture<EurekaEventListener> eventListenerCapture2 = new Capture<EurekaEventListener>(); eurekaClientMock2.registerEventListener(EasyMock.capture(eventListenerCapture2)); EasyMock.replay(eurekaClientMock); EasyMock.replay(eurekaClientMock2); final CountDownLatch updateCountLatch = new CountDownLatch(2); serverListUpdater1.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { updateCountLatch.countDown(); } }); serverListUpdater2.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { updateCountLatch.countDown(); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); eventListenerCapture2.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(updateCountLatch.await(2, TimeUnit.SECONDS)); // latch is for both serverListUpdater1.stop(); serverListUpdater2.stop(); EasyMock.verify(eurekaClientMock); EasyMock.verify(eurekaClientMock2); } @Test public void testTaskAlreadyQueued() throws Exception { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); final CountDownLatch countDownLatch = new CountDownLatch(1); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { if (countDownLatch.getCount() == 0) { Assert.fail("should only countdown once"); } countDownLatch.countDown(); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(countDownLatch.await(2, TimeUnit.SECONDS)); Thread.sleep(100); // sleep a bit more Assert.assertFalse(serverListUpdater.updateQueued.get()); } finally { serverListUpdater.stop(); EasyMock.verify(eurekaClientMock); } } @Test public void testSubmitExceptionClearQueued() { ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class); EasyMock.expect(executorMock.submit(EasyMock.isA(Runnable.class))) .andThrow(new RejectedExecutionException("test exception")); EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.FALSE); EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, executorMock ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); EasyMock.replay(executorMock); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("should not reach here"); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertFalse(serverListUpdater.updateQueued.get()); } finally { serverListUpdater.stop(); EasyMock.verify(executorMock); EasyMock.verify(eurekaClientMock); } } @Test public void testEurekaClientUnregister() { ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class); EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.TRUE); EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, executorMock ); try { Capture<EurekaEventListener> registeredListener = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(registeredListener)); EasyMock.replay(eurekaClientMock); EasyMock.replay(executorMock); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("should not reach here"); } }); registeredListener.getValue().onEvent(new CacheRefreshedEvent()); } finally { EasyMock.verify(executorMock); EasyMock.verify(eurekaClientMock); } } @Test(expected = IllegalStateException.class) public void testFailIfDiscoveryIsNotAvailable() { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return null; } }, testExecutor ); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("Should not reach here"); } }); } private EurekaClient setUpEurekaClientMock() { final EurekaClient eurekaClientMock = EasyMock.createMock(EurekaClient.class); EasyMock .expect(eurekaClientMock.unregisterEventListener(EasyMock.isA(EurekaEventListener.class))) .andReturn(true).times(1); return eurekaClientMock; } }
3,517
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LoadBalancerTestUtils.java
package com.netflix.niws.loadbalancer; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInfo; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import java.util.ArrayList; import java.util.List; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.createMock; public class LoadBalancerTestUtils { static List<InstanceInfo> getDummyInstanceInfo(String appName, String host, String ipAddr, int port){ List<InstanceInfo> list = new ArrayList<InstanceInfo>(); InstanceInfo info = InstanceInfo.Builder.newBuilder().setAppName(appName) .setHostName(host) .setIPAddr(ipAddr) .setPort(port) .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) .build(); list.add(info); return list; } static DiscoveryClient mockDiscoveryClient() { DiscoveryClient mockedDiscoveryClient = createMock(DiscoveryClient.class); expect(mockedDiscoveryClient.getEurekaClientConfig()).andReturn(new DefaultEurekaClientConfig()).anyTimes(); return mockedDiscoveryClient; } }
3,518
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LBBuilderTest.java
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; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.DummyPing; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.PollingServerListUpdater; import com.netflix.loadbalancer.RoundRobinRule; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ServerListFilter; import com.netflix.loadbalancer.ServerListUpdater; import com.netflix.loadbalancer.ZoneAffinityServerListFilter; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.apache.commons.configuration.Configuration; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.List; import static org.easymock.EasyMock.expect; import static org.junit.Assert.*; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.replay; @RunWith(PowerMockRunner.class) @PrepareForTest( {DiscoveryManager.class, DiscoveryClient.class} ) @PowerMockIgnore({"javax.management.*", "com.sun.jersey.*", "com.sun.*", "org.apache.*", "weblogic.*", "com.netflix.config.*", "com.sun.jndi.dns.*", "javax.naming.*", "com.netflix.logging.*", "javax.ws.*", "com.google.*"}) public class LBBuilderTest { static Server expected = new Server("www.example.com", 8001); static class NiwsClientConfig extends DefaultClientConfigImpl { public NiwsClientConfig() { super(); } @Override public String getNameSpace() { return "niws.client"; } } @Before public void setupMock(){ List<InstanceInfo> instances = LoadBalancerTestUtils.getDummyInstanceInfo("dummy", expected.getHost(), "127.0.0.1", expected.getPort()); PowerMock.mockStatic(DiscoveryManager.class); PowerMock.mockStatic(DiscoveryClient.class); DiscoveryClient mockedDiscoveryClient = LoadBalancerTestUtils.mockDiscoveryClient(); DiscoveryManager mockedDiscoveryManager = createMock(DiscoveryManager.class); expect(DiscoveryManager.getInstance()).andReturn(mockedDiscoveryManager).anyTimes(); expect(mockedDiscoveryManager.getDiscoveryClient()).andReturn(mockedDiscoveryClient).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress("dummy:7001", false, null)).andReturn(instances).anyTimes(); replay(DiscoveryManager.class); replay(DiscoveryClient.class); replay(mockedDiscoveryManager); replay(mockedDiscoveryClient); } @Test public void testBuildWithDiscoveryEnabledNIWSServerList() { IRule rule = new AvailabilityFilteringRule(); ServerList<DiscoveryEnabledServer> list = new DiscoveryEnabledNIWSServerList("dummy:7001"); ServerListFilter<DiscoveryEnabledServer> filter = new ZoneAffinityServerListFilter<>(); ZoneAwareLoadBalancer<DiscoveryEnabledServer> lb = LoadBalancerBuilder.<DiscoveryEnabledServer>newBuilder() .withDynamicServerList(list) .withRule(rule) .withServerListFilter(filter) .buildDynamicServerListLoadBalancer(); assertNotNull(lb); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); Server server = lb.chooseServer(); // make sure load balancer does not recreate the server instance assertTrue(server instanceof DiscoveryEnabledServer); } @Test public void testBuildWithDiscoveryEnabledNIWSServerListAndUpdater() { IRule rule = new AvailabilityFilteringRule(); ServerList<DiscoveryEnabledServer> list = new DiscoveryEnabledNIWSServerList("dummy:7001"); ServerListFilter<DiscoveryEnabledServer> filter = new ZoneAffinityServerListFilter<>(); ServerListUpdater updater = new PollingServerListUpdater(); ZoneAwareLoadBalancer<DiscoveryEnabledServer> lb = LoadBalancerBuilder.<DiscoveryEnabledServer>newBuilder() .withDynamicServerList(list) .withRule(rule) .withServerListFilter(filter) .withServerListUpdater(updater) .buildDynamicServerListLoadBalancerWithUpdater(); assertNotNull(lb); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); assertSame(updater, lb.getServerListUpdater()); Server server = lb.chooseServer(); // make sure load balancer does not recreate the server instance assertTrue(server instanceof DiscoveryEnabledServer); } @Test public void testBuildWithArchaiusProperties() { Configuration config = ConfigurationManager.getConfigInstance(); config.setProperty("client1.niws.client." + Keys.DeploymentContextBasedVipAddresses, "dummy:7001"); config.setProperty("client1.niws.client." + Keys.InitializeNFLoadBalancer, "true"); config.setProperty("client1.niws.client." + Keys.NFLoadBalancerClassName, DynamicServerListLoadBalancer.class.getName()); config.setProperty("client1.niws.client." + Keys.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName()); config.setProperty("client1.niws.client." + Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); config.setProperty("client1.niws.client." + Keys.NIWSServerListFilterClassName, ZoneAffinityServerListFilter.class.getName()); config.setProperty("client1.niws.client." + Keys.ServerListUpdaterClassName, PollingServerListUpdater.class.getName()); IClientConfig clientConfig = IClientConfig.Builder.newBuilder(NiwsClientConfig.class, "client1").build(); ILoadBalancer lb = LoadBalancerBuilder.newBuilder().withClientConfig(clientConfig).buildLoadBalancerFromConfigWithReflection(); assertNotNull(lb); assertEquals(DynamicServerListLoadBalancer.class.getName(), lb.getClass().getName()); DynamicServerListLoadBalancer<Server> dynamicLB = (DynamicServerListLoadBalancer<Server>) lb; assertTrue(dynamicLB.getServerListUpdater() instanceof PollingServerListUpdater); assertTrue(dynamicLB.getFilter() instanceof ZoneAffinityServerListFilter); assertTrue(dynamicLB.getRule() instanceof RoundRobinRule); assertTrue(dynamicLB.getPing() instanceof DummyPing); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); } @Test public void testBuildStaticServerListLoadBalancer() { List<Server> list = Lists.newArrayList(expected, expected); IRule rule = new AvailabilityFilteringRule(); IClientConfig clientConfig = IClientConfig.Builder.newBuilder() .withDefaultValues() .withMaxAutoRetriesNextServer(3).build(); assertEquals(3, clientConfig.get(Keys.MaxAutoRetriesNextServer).intValue()); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder() .withRule(rule) .buildFixedServerListLoadBalancer(list); assertEquals(list, lb.getAllServers()); assertSame(rule, lb.getRule()); } }
3,519
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/DiscoveryEnabledLoadBalancerSupportsUseIpAddrTest.java
/* * * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.niws.loadbalancer; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.loadbalancer.Server; /** * Verify behavior of the override flag DiscoveryEnabledNIWSServerList.useIpAddr * * Currently only works with the DiscoveryEnabledNIWSServerList since this is where the current limitation is applicable * * See also: https://groups.google.com/forum/#!topic/eureka_netflix/7M28bK-SCZU * * Created by aspyker on 8/21/14. */ @RunWith(PowerMockRunner.class) @PrepareForTest( {DiscoveryManager.class, DiscoveryClient.class} ) @PowerMockIgnore("javax.management.*") @SuppressWarnings("PMD.AvoidUsingHardCodedIP") public class DiscoveryEnabledLoadBalancerSupportsUseIpAddrTest { static final String IP1 = "1.1.1.1"; static final String HOST1 = "server1.app.host.com"; static final String IP2 = "1.1.1.2"; static final String HOST2 = "server1.app.host.com"; @Before public void setupMock(){ List<InstanceInfo> servers = LoadBalancerTestUtils.getDummyInstanceInfo("dummy", HOST1, IP1, 8080); List<InstanceInfo> servers2 = LoadBalancerTestUtils.getDummyInstanceInfo("dummy", HOST2, IP2, 8080); servers.addAll(servers2); PowerMock.mockStatic(DiscoveryManager.class); PowerMock.mockStatic(DiscoveryClient.class); DiscoveryClient mockedDiscoveryClient = LoadBalancerTestUtils.mockDiscoveryClient(); DiscoveryManager mockedDiscoveryManager = createMock(DiscoveryManager.class); expect(DiscoveryManager.getInstance()).andReturn(mockedDiscoveryManager).anyTimes(); expect(mockedDiscoveryManager.getDiscoveryClient()).andReturn(mockedDiscoveryClient).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress("dummy", false, "region")).andReturn(servers).anyTimes(); replay(DiscoveryManager.class); replay(DiscoveryClient.class); replay(mockedDiscoveryManager); replay(mockedDiscoveryClient); } /** * Generic method to help with various tests * @param globalspecified if false, will clear property DiscoveryEnabledNIWSServerList.useIpAddr * @param global value of DiscoveryEnabledNIWSServerList.useIpAddr * @param clientspecified if false, will not set property on client config * @param client value of client.namespace.ribbon.UseIPAddrForServer */ private List<Server> testUsesIpAddr(boolean globalSpecified, boolean global, boolean clientSpecified, boolean client) throws Exception{ if (globalSpecified) { ConfigurationManager.getConfigInstance().setProperty("ribbon.UseIPAddrForServer", global); } else { ConfigurationManager.getConfigInstance().clearProperty("ribbon.UseIPAddrForServer"); } if (clientSpecified) { ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.UseIPAddrForServer", client); } else { ConfigurationManager.getConfigInstance().clearProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.UseIPAddrForServer"); } System.out.println("r = " + ConfigurationManager.getConfigInstance().getProperty("ribbon.UseIPAddrForServer")); System.out.println("d = " + ConfigurationManager.getConfigInstance().getProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.UseIPAddrForServer")); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.TargetRegion", "region"); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList("TESTVIP:8080"); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testUsesIpAddr"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(2, serverList.size()); List<Server> servers = new ArrayList<Server>(); for (DiscoveryEnabledServer server : serverList) { servers.add((Server)server); } return servers; } /** * Test the case where the property has been used specific to client with true * @throws Exception */ @Test public void testUsesIpAddrByWhenClientTrueOnly() throws Exception{ List<Server> servers = testUsesIpAddr(false, false, true, true); Assert.assertEquals(servers.get(0).getHost(), IP1); Assert.assertEquals(servers.get(1).getHost(), IP2); } /** * Test the case where the property has been used specific to client with false * @throws Exception */ @Test public void testUsesIpAddrByWhenClientFalseOnly() throws Exception{ List<Server> servers = testUsesIpAddr(false, false, true, false); Assert.assertEquals(servers.get(0).getHost(), HOST1); Assert.assertEquals(servers.get(1).getHost(), HOST2); } @Test /** * Test the case where the property has been used globally with true * @throws Exception */ public void testUsesIpAddrByWhenGlobalTrueOnly() throws Exception{ List<Server> servers = testUsesIpAddr(true, true, false, false); Assert.assertEquals(servers.get(0).getHost(), IP1); Assert.assertEquals(servers.get(1).getHost(), IP2); } @Test /** * Test the case where the property has been used globally with false * @throws Exception */ public void testUsesIpAddrByWhenGlobalFalseOnly() throws Exception{ List<Server> servers = testUsesIpAddr(true, false, false, false); Assert.assertEquals(servers.get(0).getHost(), HOST1); Assert.assertEquals(servers.get(1).getHost(), HOST2); } @Test /** * Test the case where the property hasn't been used at the global or client level * @throws Exception */ public void testUsesHostnameByDefault() throws Exception{ List<Server> servers = testUsesIpAddr(false, false, false, false); Assert.assertEquals(servers.get(0).getHost(), HOST1); Assert.assertEquals(servers.get(1).getHost(), HOST2); } @After public void afterMock(){ verify(DiscoveryManager.class); verify(DiscoveryClient.class); } }
3,520
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/loadbalancer/EurekaDynamicServerListLoadBalancerTest.java
package com.netflix.loadbalancer; import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaEventListener; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; import com.netflix.niws.loadbalancer.EurekaNotificationServerListUpdater; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import javax.inject.Provider; import java.util.List; import java.util.concurrent.TimeUnit; /** * A test for {@link com.netflix.loadbalancer.DynamicServerListLoadBalancer} using the * {@link com.netflix.niws.loadbalancer.EurekaNotificationServerListUpdater} instead of the default. * * @author David Liu */ @RunWith(PowerMockRunner.class) @PrepareForTest(DiscoveryClient.class) @PowerMockIgnore("javax.management.*") public class EurekaDynamicServerListLoadBalancerTest { private final List<InstanceInfo> servers = InstanceInfoGenerator.newBuilder(10, 1).build().toInstanceList(); private final int initialServerListSize = 4; private final int secondServerListSize = servers.size() - initialServerListSize; private final String vipAddress = servers.get(0).getVIPAddress(); private DefaultClientConfigImpl config; private EurekaClient eurekaClientMock; private Provider<EurekaClient> eurekaClientProvider; @Before public void setUp() { PowerMock.mockStatic(DiscoveryClient.class); EasyMock .expect(DiscoveryClient.getZone(EasyMock.isA(InstanceInfo.class))) .andReturn("zone") .anyTimes(); eurekaClientMock = setUpEurekaClientMock(servers); eurekaClientProvider = new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }; config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); config.set(CommonClientConfigKey.DeploymentContextBasedVipAddresses, vipAddress); config.set(CommonClientConfigKey.ServerListUpdaterClassName, EurekaNotificationServerListUpdater.class.getName()); } @Test public void testLoadBalancerHappyCase() throws Exception { Assert.assertNotEquals("the two test server list counts should be different", secondServerListSize, initialServerListSize); DynamicServerListLoadBalancer<DiscoveryEnabledServer> lb = null; try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); PowerMock.replay(DiscoveryClient.class); PowerMock.replay(eurekaClientMock); // actual testing // initial creation and loading of the first serverlist lb = new DynamicServerListLoadBalancer<DiscoveryEnabledServer>( config, new AvailabilityFilteringRule(), new DummyPing(), new DiscoveryEnabledNIWSServerList(vipAddress, eurekaClientProvider), new ZoneAffinityServerListFilter<DiscoveryEnabledServer>(), new EurekaNotificationServerListUpdater(eurekaClientProvider) ); Assert.assertEquals(initialServerListSize, lb.getServerCount(false)); // trigger an eureka CacheRefreshEvent eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(verifyFinalServerListCount(secondServerListSize, lb)); } finally { if (lb != null) { lb.shutdown(); PowerMock.verify(eurekaClientMock); PowerMock.verify(DiscoveryClient.class); } } } @Test public void testShutdownMultiple() { try { eurekaClientMock.registerEventListener(EasyMock.anyObject(EurekaEventListener.class)); EasyMock.expectLastCall().anyTimes(); PowerMock.replay(DiscoveryClient.class); PowerMock.replay(eurekaClientMock); DynamicServerListLoadBalancer<DiscoveryEnabledServer> lb1 = new DynamicServerListLoadBalancer<DiscoveryEnabledServer>( config, new AvailabilityFilteringRule(), new DummyPing(), new DiscoveryEnabledNIWSServerList(vipAddress, eurekaClientProvider), new ZoneAffinityServerListFilter<DiscoveryEnabledServer>(), new EurekaNotificationServerListUpdater(eurekaClientProvider) ); DynamicServerListLoadBalancer<DiscoveryEnabledServer> lb2 = new DynamicServerListLoadBalancer<DiscoveryEnabledServer>( config, new AvailabilityFilteringRule(), new DummyPing(), new DiscoveryEnabledNIWSServerList(vipAddress, eurekaClientProvider), new ZoneAffinityServerListFilter<DiscoveryEnabledServer>(), new EurekaNotificationServerListUpdater(eurekaClientProvider) ); DynamicServerListLoadBalancer<DiscoveryEnabledServer> lb3 = new DynamicServerListLoadBalancer<DiscoveryEnabledServer>( config, new AvailabilityFilteringRule(), new DummyPing(), new DiscoveryEnabledNIWSServerList(vipAddress, eurekaClientProvider), new ZoneAffinityServerListFilter<DiscoveryEnabledServer>(), new EurekaNotificationServerListUpdater(eurekaClientProvider) ); lb3.shutdown(); lb1.shutdown(); lb2.shutdown(); } finally { PowerMock.verify(eurekaClientMock); PowerMock.verify(DiscoveryClient.class); } } // a hacky thread sleep loop to get around some minor async behaviour // max wait time is 2 seconds, but should complete well before that. private boolean verifyFinalServerListCount(int finalCount, DynamicServerListLoadBalancer lb) throws Exception { long stepSize = TimeUnit.MILLISECONDS.convert(50l, TimeUnit.MILLISECONDS); long maxTime = TimeUnit.MILLISECONDS.convert(2l, TimeUnit.SECONDS); for (int i = 0; i < maxTime; i += stepSize) { if (finalCount == lb.getServerCount(false)) { return true; } else { Thread.sleep(stepSize); } } return false; } private EurekaClient setUpEurekaClientMock(List<InstanceInfo> servers) { final EurekaClient eurekaClientMock = PowerMock.createMock(EurekaClient.class); EasyMock.expect(eurekaClientMock.getEurekaClientConfig()).andReturn(new DefaultEurekaClientConfig()).anyTimes(); EasyMock .expect(eurekaClientMock.getInstancesByVipAddress(EasyMock.anyString(), EasyMock.anyBoolean(), EasyMock.anyString())) .andReturn(servers.subList(0, initialServerListSize)).times(1) .andReturn(servers.subList(initialServerListSize, servers.size())).anyTimes(); EasyMock .expectLastCall(); EasyMock .expect(eurekaClientMock.unregisterEventListener(EasyMock.isA(EurekaEventListener.class))) .andReturn(true).anyTimes(); return eurekaClientMock; } }
3,521
0
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/DiscoveryEnabledNIWSServerList.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.niws.loadbalancer; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.loadbalancer.AbstractServerList; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Provider; /** * The server list class that fetches the server information from Eureka client. ServerList is used by * {@link DynamicServerListLoadBalancer} to get server list dynamically. * * @author stonse * */ public class DiscoveryEnabledNIWSServerList extends AbstractServerList<DiscoveryEnabledServer>{ private static final Logger logger = LoggerFactory.getLogger(DiscoveryEnabledNIWSServerList.class); String clientName; String vipAddresses; boolean isSecure = false; boolean prioritizeVipAddressBasedServers = true; String datacenter; String targetRegion; int overridePort = CommonClientConfigKey.Port.defaultValue(); boolean shouldUseOverridePort = false; boolean shouldUseIpAddr = false; private final Provider<EurekaClient> eurekaClientProvider; /** * @deprecated use {@link #DiscoveryEnabledNIWSServerList(String)} * or {@link #DiscoveryEnabledNIWSServerList(IClientConfig)} */ @Deprecated public DiscoveryEnabledNIWSServerList() { this.eurekaClientProvider = new LegacyEurekaClientProvider(); } /** * @deprecated * use {@link #DiscoveryEnabledNIWSServerList(String, javax.inject.Provider)} * @param vipAddresses */ @Deprecated public DiscoveryEnabledNIWSServerList(String vipAddresses) { this(vipAddresses, new LegacyEurekaClientProvider()); } /** * @deprecated * use {@link #DiscoveryEnabledNIWSServerList(com.netflix.client.config.IClientConfig, javax.inject.Provider)} * @param clientConfig */ @Deprecated public DiscoveryEnabledNIWSServerList(IClientConfig clientConfig) { this(clientConfig, new LegacyEurekaClientProvider()); } public DiscoveryEnabledNIWSServerList(String vipAddresses, Provider<EurekaClient> eurekaClientProvider) { this(createClientConfig(vipAddresses), eurekaClientProvider); } public DiscoveryEnabledNIWSServerList(IClientConfig clientConfig, Provider<EurekaClient> eurekaClientProvider) { this.eurekaClientProvider = eurekaClientProvider; initWithNiwsConfig(clientConfig); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { clientName = clientConfig.getClientName(); vipAddresses = clientConfig.resolveDeploymentContextbasedVipAddresses(); if (vipAddresses == null && ConfigurationManager.getConfigInstance().getBoolean("DiscoveryEnabledNIWSServerList.failFastOnNullVip", true)) { throw new NullPointerException("VIP address for client " + clientName + " is null"); } isSecure = clientConfig.get(CommonClientConfigKey.IsSecure, false); prioritizeVipAddressBasedServers = clientConfig.get(CommonClientConfigKey.PrioritizeVipAddressBasedServers, prioritizeVipAddressBasedServers); datacenter = ConfigurationManager.getDeploymentContext().getDeploymentDatacenter(); targetRegion = clientConfig.get(CommonClientConfigKey.TargetRegion); shouldUseIpAddr = clientConfig.getOrDefault(CommonClientConfigKey.UseIPAddrForServer); // override client configuration and use client-defined port if (clientConfig.get(CommonClientConfigKey.ForceClientPortConfiguration, false)) { if (isSecure) { final Integer port = clientConfig.get(CommonClientConfigKey.SecurePort); if (port != null) { overridePort = port; shouldUseOverridePort = true; } else { logger.warn(clientName + " set to force client port but no secure port is set, so ignoring"); } } else { final Integer port = clientConfig.get(CommonClientConfigKey.Port); if (port != null) { overridePort = port; shouldUseOverridePort = true; } else{ logger.warn(clientName + " set to force client port but no port is set, so ignoring"); } } } } @Override public List<DiscoveryEnabledServer> getInitialListOfServers(){ return obtainServersViaDiscovery(); } @Override public List<DiscoveryEnabledServer> getUpdatedListOfServers(){ return obtainServersViaDiscovery(); } private List<DiscoveryEnabledServer> obtainServersViaDiscovery() { List<DiscoveryEnabledServer> serverList = new ArrayList<DiscoveryEnabledServer>(); if (eurekaClientProvider == null || eurekaClientProvider.get() == null) { logger.warn("EurekaClient has not been initialized yet, returning an empty list"); return new ArrayList<DiscoveryEnabledServer>(); } EurekaClient eurekaClient = eurekaClientProvider.get(); if (vipAddresses!=null){ for (String vipAddress : vipAddresses.split(",")) { // if targetRegion is null, it will be interpreted as the same region of client List<InstanceInfo> listOfInstanceInfo = eurekaClient.getInstancesByVipAddress(vipAddress, isSecure, targetRegion); for (InstanceInfo ii : listOfInstanceInfo) { if (ii.getStatus().equals(InstanceStatus.UP)) { if(shouldUseOverridePort){ if(logger.isDebugEnabled()){ logger.debug("Overriding port on client name: " + clientName + " to " + overridePort); } // copy is necessary since the InstanceInfo builder just uses the original reference, // and we don't want to corrupt the global eureka copy of the object which may be // used by other clients in our system InstanceInfo copy = new InstanceInfo(ii); if(isSecure){ ii = new InstanceInfo.Builder(copy).setSecurePort(overridePort).build(); }else{ ii = new InstanceInfo.Builder(copy).setPort(overridePort).build(); } } DiscoveryEnabledServer des = createServer(ii, isSecure, shouldUseIpAddr); serverList.add(des); } } if (serverList.size()>0 && prioritizeVipAddressBasedServers){ break; // if the current vipAddress has servers, we dont use subsequent vipAddress based servers } } } return serverList; } protected DiscoveryEnabledServer createServer(final InstanceInfo instanceInfo, boolean useSecurePort, boolean useIpAddr) { DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, useSecurePort, useIpAddr); // Get availabilty zone for this instance. EurekaClientConfig clientConfig = eurekaClientProvider.get().getEurekaClientConfig(); String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion()); String instanceZone = InstanceInfo.getZone(availZones, instanceInfo); server.setZone(instanceZone); return server; } public String getVipAddresses() { return vipAddresses; } public void setVipAddresses(String vipAddresses) { this.vipAddresses = vipAddresses; } public String toString(){ StringBuilder sb = new StringBuilder("DiscoveryEnabledNIWSServerList:"); sb.append("; clientName:").append(clientName); sb.append("; Effective vipAddresses:").append(vipAddresses); sb.append("; isSecure:").append(isSecure); sb.append("; datacenter:").append(datacenter); return sb.toString(); } private static IClientConfig createClientConfig(String vipAddresses) { IClientConfig clientConfig = ClientConfigFactory.DEFAULT.newConfig(); clientConfig.set(Keys.DeploymentContextBasedVipAddresses, vipAddresses); return clientConfig; } }
3,522
0
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/NIWSDiscoveryPing.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.niws.loadbalancer; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerPing; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.Server; /** * "Ping" Discovery Client * i.e. we dont do a real "ping". We just assume that the server is up if Discovery Client says so * @author stonse * */ public class NIWSDiscoveryPing extends AbstractLoadBalancerPing { BaseLoadBalancer lb = null; public NIWSDiscoveryPing() { } public BaseLoadBalancer getLb() { return lb; } /** * Non IPing interface method - only set this if you care about the "newServers Feature" * @param lb */ public void setLb(BaseLoadBalancer lb) { this.lb = lb; } public boolean isAlive(Server server) { boolean isAlive = true; if (server!=null && server instanceof DiscoveryEnabledServer){ DiscoveryEnabledServer dServer = (DiscoveryEnabledServer)server; InstanceInfo instanceInfo = dServer.getInstanceInfo(); if (instanceInfo!=null){ InstanceStatus status = instanceInfo.getStatus(); if (status!=null){ isAlive = status.equals(InstanceStatus.UP); } } } return isAlive; } @Override public void initWithNiwsConfig( IClientConfig clientConfig) { } }
3,523
0
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdater.java
package com.netflix.niws.loadbalancer; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.config.DynamicIntProperty; import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaEvent; import com.netflix.discovery.EurekaEventListener; import com.netflix.loadbalancer.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Provider; import java.util.Date; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * A server list updater for the {@link com.netflix.loadbalancer.DynamicServerListLoadBalancer} that * utilizes eureka's event listener to trigger LB cache updates. * * Note that when a cache refreshed notification is received, the actual update on the serverList is * done on a separate scheduler as the notification is delivered on an eurekaClient thread. * * @author David Liu */ public class EurekaNotificationServerListUpdater implements ServerListUpdater { private static final Logger logger = LoggerFactory.getLogger(EurekaNotificationServerListUpdater.class); private static class LazyHolder { private final static String CORE_THREAD = "EurekaNotificationServerListUpdater.ThreadPoolSize"; private final static String QUEUE_SIZE = "EurekaNotificationServerListUpdater.queueSize"; private final static LazyHolder SINGLETON = new LazyHolder(); private final DynamicIntProperty poolSizeProp = new DynamicIntProperty(CORE_THREAD, 2); private final DynamicIntProperty queueSizeProp = new DynamicIntProperty(QUEUE_SIZE, 1000); private final ThreadPoolExecutor defaultServerListUpdateExecutor; private final Thread shutdownThread; private LazyHolder() { int corePoolSize = getCorePoolSize(); defaultServerListUpdateExecutor = new ThreadPoolExecutor( corePoolSize, corePoolSize * 5, 0, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(queueSizeProp.get()), new ThreadFactoryBuilder() .setNameFormat("EurekaNotificationServerListUpdater-%d") .setDaemon(true) .build() ); poolSizeProp.addCallback(new Runnable() { @Override public void run() { int corePoolSize = getCorePoolSize(); defaultServerListUpdateExecutor.setCorePoolSize(corePoolSize); defaultServerListUpdateExecutor.setMaximumPoolSize(corePoolSize * 5); } }); shutdownThread = new Thread(new Runnable() { @Override public void run() { logger.info("Shutting down the Executor for EurekaNotificationServerListUpdater"); try { defaultServerListUpdateExecutor.shutdown(); Runtime.getRuntime().removeShutdownHook(shutdownThread); } catch (Exception e) { // this can happen in the middle of a real shutdown, and that's ok. } } }); Runtime.getRuntime().addShutdownHook(shutdownThread); } private int getCorePoolSize() { int propSize = poolSizeProp.get(); if (propSize > 0) { return propSize; } return 2; // default } } public static ExecutorService getDefaultRefreshExecutor() { return LazyHolder.SINGLETON.defaultServerListUpdateExecutor; } /* visible for testing */ final AtomicBoolean updateQueued = new AtomicBoolean(false); private final AtomicBoolean isActive = new AtomicBoolean(false); private final AtomicLong lastUpdated = new AtomicLong(System.currentTimeMillis()); private final Provider<EurekaClient> eurekaClientProvider; private final ExecutorService refreshExecutor; private volatile EurekaEventListener updateListener; private volatile EurekaClient eurekaClient; public EurekaNotificationServerListUpdater() { this(new LegacyEurekaClientProvider()); } public EurekaNotificationServerListUpdater(final Provider<EurekaClient> eurekaClientProvider) { this(eurekaClientProvider, getDefaultRefreshExecutor()); } public EurekaNotificationServerListUpdater(final Provider<EurekaClient> eurekaClientProvider, ExecutorService refreshExecutor) { this.eurekaClientProvider = eurekaClientProvider; this.refreshExecutor = refreshExecutor; } @Override public synchronized void start(final UpdateAction updateAction) { if (isActive.compareAndSet(false, true)) { this.updateListener = new EurekaEventListener() { @Override public void onEvent(EurekaEvent event) { if (event instanceof CacheRefreshedEvent) { if (!updateQueued.compareAndSet(false, true)) { // if an update is already queued logger.info("an update action is already queued, returning as no-op"); return; } if (!refreshExecutor.isShutdown()) { try { refreshExecutor.submit(new Runnable() { @Override public void run() { try { updateAction.doUpdate(); lastUpdated.set(System.currentTimeMillis()); } catch (Exception e) { logger.warn("Failed to update serverList", e); } finally { updateQueued.set(false); } } }); // fire and forget } catch (Exception e) { logger.warn("Error submitting update task to executor, skipping one round of updates", e); updateQueued.set(false); // if submit fails, need to reset updateQueued to false } } else { logger.debug("stopping EurekaNotificationServerListUpdater, as refreshExecutor has been shut down"); stop(); } } } }; if (eurekaClient == null) { eurekaClient = eurekaClientProvider.get(); } if (eurekaClient != null) { eurekaClient.registerEventListener(updateListener); } else { logger.error("Failed to register an updateListener to eureka client, eureka client is null"); throw new IllegalStateException("Failed to start the updater, unable to register the update listener due to eureka client being null."); } } else { logger.info("Update listener already registered, no-op"); } } @Override public synchronized void stop() { if (isActive.compareAndSet(true, false)) { if (eurekaClient != null) { eurekaClient.unregisterEventListener(updateListener); } } else { logger.info("Not currently active, no-op"); } } @Override public String getLastUpdate() { return new Date(lastUpdated.get()).toString(); } @Override public long getDurationSinceLastUpdateMs() { return System.currentTimeMillis() - lastUpdated.get(); } @Override public int getNumberMissedCycles() { return 0; } @Override public int getCoreThreads() { if (isActive.get()) { if (refreshExecutor != null && refreshExecutor instanceof ThreadPoolExecutor) { return ((ThreadPoolExecutor) refreshExecutor).getCorePoolSize(); } } return 0; } }
3,524
0
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/DiscoveryEnabledServer.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.niws.loadbalancer; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.PortType; import com.netflix.loadbalancer.Server; /** * Servers that were obtained via Discovery and hence contain * meta data in the form of InstanceInfo * @author stonse * */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EQ_DOESNT_OVERRIDE_EQUALS") public class DiscoveryEnabledServer extends Server{ private final InstanceInfo instanceInfo; private final MetaInfo serviceInfo; public DiscoveryEnabledServer(final InstanceInfo instanceInfo, boolean useSecurePort) { this(instanceInfo, useSecurePort, false); } public DiscoveryEnabledServer(final InstanceInfo instanceInfo, boolean useSecurePort, boolean useIpAddr) { super(useIpAddr ? instanceInfo.getIPAddr() : instanceInfo.getHostName(), instanceInfo.getPort()); if(useSecurePort && instanceInfo.isPortEnabled(PortType.SECURE)) super.setPort(instanceInfo.getSecurePort()); this.instanceInfo = instanceInfo; this.serviceInfo = new MetaInfo() { @Override public String getAppName() { return instanceInfo.getAppName(); } @Override public String getServerGroup() { return instanceInfo.getASGName(); } @Override public String getServiceIdForDiscovery() { return instanceInfo.getVIPAddress(); } @Override public String getInstanceId() { return instanceInfo.getId(); } }; } public InstanceInfo getInstanceInfo() { return instanceInfo; } @Override public MetaInfo getMetaInfo() { return serviceInfo; } }
3,525
0
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/main/java/com/netflix/niws/loadbalancer/LegacyEurekaClientProvider.java
package com.netflix.niws.loadbalancer; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClient; import javax.inject.Provider; /** * A legacy class to provide eurekaclient via static singletons */ class LegacyEurekaClientProvider implements Provider<EurekaClient> { private volatile EurekaClient eurekaClient; @Override public synchronized EurekaClient get() { if (eurekaClient == null) { eurekaClient = DiscoveryManager.getInstance().getDiscoveryClient(); } return eurekaClient; } }
3,526
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/RibbonTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import com.netflix.ribbon.http.HttpRequestTemplate; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.hystrix.FallbackHandler; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*; public class RibbonTest { private static String toStringBlocking(RibbonRequest<ByteBuf> request) { return request.toObservable().map(new Func1<ByteBuf, String>() { @Override public String call(ByteBuf t1) { return t1.toString(Charset.defaultCharset()); } }).toBlocking().single(); } @BeforeClass public static void init() { LogManager.getRootLogger().setLevel(Level.DEBUG); } @Test public void testCommand() throws IOException, InterruptedException, ExecutionException { MockWebServer server = new MockWebServer(); String content = "Hello world"; MockResponse response = new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content); server.enqueue(response); server.enqueue(response); server.enqueue(response); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withMaxAutoRetriesNextServer(3) .withReadTimeout(300000) .withConfigurationBasedServerList("localhost:12345, localhost:10092, localhost:" + server.getPort())); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class) .withUriTemplate("/") .withMethod("GET") .build(); RibbonRequest<ByteBuf> request = template.requestBuilder().build(); String result = request.execute().toString(Charset.defaultCharset()); assertEquals(content, result); // repeat the same request ByteBuf raw = request.execute(); result = raw.toString(Charset.defaultCharset()); raw.release(); assertEquals(content, result); result = request.queue().get().toString(Charset.defaultCharset()); assertEquals(content, result); } @Test public void testHystrixCache() throws IOException { // LogManager.getRootLogger().setLevel((Level)Level.DEBUG); MockWebServer server = new MockWebServer(); String content = "Hello world"; MockResponse response = new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content); server.enqueue(response); server.enqueue(response); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("myclient").build(); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class) .withUriTemplate("http://localhost:" + server.getPort()) .withMethod("GET") .withRequestCacheKey("xyz") .build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { RibbonResponse<ByteBuf> ribbonResponse = request.withMetadata().execute(); assertFalse(ribbonResponse.getHystrixInfo().isResponseFromCache()); ribbonResponse = request.withMetadata().execute(); assertTrue(ribbonResponse.getHystrixInfo().isResponseFromCache()); } finally { context.shutdown(); } } @Test @Ignore public void testCommandWithMetaData() throws IOException, InterruptedException, ExecutionException { // LogManager.getRootLogger().setLevel((Level)Level.DEBUG); MockWebServer server = new MockWebServer(); String content = "Hello world"; for (int i = 0; i < 6; i++) { server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content)); } server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withConfigurationBasedServerList("localhost:" + server.getPort()) .withMaxAutoRetriesNextServer(3)); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test") .withUriTemplate("/") .withMethod("GET") .withCacheProvider("somekey", new CacheProvider<ByteBuf>(){ @Override public Observable<ByteBuf> get(String key, Map<String, Object> vars) { return Observable.error(new Exception("Cache miss")); } }).build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); final AtomicBoolean success = new AtomicBoolean(false); RequestWithMetaData<ByteBuf> metaRequest = request.withMetadata(); Observable<String> result = metaRequest.toObservable().flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<String>>(){ @Override public Observable<String> call( final RibbonResponse<Observable<ByteBuf>> response) { success.set(response.getHystrixInfo().isSuccessfulExecution()); return response.content().map(new Func1<ByteBuf, String>(){ @Override public String call(ByteBuf t1) { return t1.toString(Charset.defaultCharset()); } }); } }); String s = result.toBlocking().single(); assertEquals(content, s); assertTrue(success.get()); Future<RibbonResponse<ByteBuf>> future = metaRequest.queue(); RibbonResponse<ByteBuf> response = future.get(); assertTrue(future.isDone()); assertEquals(content, response.content().toString(Charset.defaultCharset())); assertTrue(response.getHystrixInfo().isSuccessfulExecution()); RibbonResponse<ByteBuf> result1 = metaRequest.execute(); assertEquals(content, result1.content().toString(Charset.defaultCharset())); assertTrue(result1.getHystrixInfo().isSuccessfulExecution()); } @Test public void testValidator() throws IOException, InterruptedException { // LogManager.getRootLogger().setLevel((Level)Level.DEBUG); MockWebServer server = new MockWebServer(); String content = "Hello world"; server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content)); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withConfigurationBasedServerList("localhost:" + server.getPort())); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class) .withUriTemplate("/") .withMethod("GET") .withResponseValidator(new ResponseValidator<HttpClientResponse<ByteBuf>>() { @Override public void validate(HttpClientResponse<ByteBuf> t1) throws UnsuccessfulResponseException { throw new UnsuccessfulResponseException("error", new IllegalArgumentException()); } }).build(); RibbonRequest<ByteBuf> request = template.requestBuilder().build(); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); request.toObservable().subscribe(new Action1<ByteBuf>() { @Override public void call(ByteBuf t1) { } }, new Action1<Throwable>(){ @Override public void call(Throwable t1) { error.set(t1); latch.countDown(); } }, new Action0() { @Override public void call() { } }); latch.await(); assertTrue(error.get() instanceof HystrixBadRequestException); assertTrue(error.get().getCause() instanceof UnsuccessfulResponseException); } @Test public void testFallback() throws IOException { HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withConfigurationBasedServerList("localhost:12345") .withMaxAutoRetriesNextServer(1)); final String fallback = "fallback"; HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class) .withUriTemplate("/") .withMethod("GET") .withFallbackProvider(new FallbackHandler<ByteBuf>() { @Override public Observable<ByteBuf> getFallback( HystrixInvokableInfo<?> hystrixInfo, Map<String, Object> requestProperties) { try { return Observable.just(Unpooled.buffer().writeBytes(fallback.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { return Observable.error(e); } } }).build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); final AtomicReference<HystrixInvokableInfo<?>> hystrixInfo = new AtomicReference<HystrixInvokableInfo<?>>(); final AtomicBoolean failed = new AtomicBoolean(false); Observable<String> result = request.withMetadata().toObservable().flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<String>>(){ @Override public Observable<String> call( final RibbonResponse<Observable<ByteBuf>> response) { hystrixInfo.set(response.getHystrixInfo()); failed.set(response.getHystrixInfo().isFailedExecution()); return response.content().map(new Func1<ByteBuf, String>(){ @Override public String call(ByteBuf t1) { return t1.toString(Charset.defaultCharset()); } }); } }); String s = result.toBlocking().single(); // this returns true only after the blocking call is done assertTrue(hystrixInfo.get().isResponseFromFallback()); assertTrue(failed.get()); assertEquals(fallback, s); } @Test public void testCacheHit() { HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withConfigurationBasedServerList("localhost:12345") .withMaxAutoRetriesNextServer(1)); final String content = "from cache"; final String cacheKey = "somekey"; HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test") .withCacheProvider(cacheKey, new CacheProvider<ByteBuf>(){ @Override public Observable<ByteBuf> get(String key, Map<String, Object> vars) { if (key.equals(cacheKey)) { try { return Observable.just(Unpooled.buffer().writeBytes(content.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { return Observable.error(e); } } else { return Observable.error(new Exception("Cache miss")); } } }).withUriTemplate("/") .withMethod("GET").build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); String result = request.execute().toString(Charset.defaultCharset()); assertEquals(content, result); } @Test public void testObserve() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); String content = "Hello world"; server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content)); server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content)); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withMaxAutoRetriesNextServer(3) .withReadTimeout(300000) .withConfigurationBasedServerList("localhost:12345, localhost:10092, localhost:" + server.getPort())); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class) .withUriTemplate("/") .withMethod("GET").build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); Observable<ByteBuf> result = request.observe(); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<String> fromCommand = new AtomicReference<String>(); // We need to wait until the response is received and processed by event loop // and make sure that subscribing to it again will not cause ByteBuf ref count issue result.toBlocking().last(); result.subscribe(new Action1<ByteBuf>() { @Override public void call(ByteBuf t1) { try { fromCommand.set(t1.toString(Charset.defaultCharset())); } catch (Exception e) { e.printStackTrace(); } latch.countDown(); } }); latch.await(); assertEquals(content, fromCommand.get()); Observable<RibbonResponse<Observable<ByteBuf>>> metaResult = request.withMetadata().observe(); String result2 = ""; // We need to wait until the response is received and processed by event loop // and make sure that subscribing to it again will not cause ByteBuf ref count issue metaResult.toBlocking().last(); result2 = metaResult.flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<ByteBuf>>(){ @Override public Observable<ByteBuf> call( RibbonResponse<Observable<ByteBuf>> t1) { return t1.content(); } }).map(new Func1<ByteBuf, String>(){ @Override public String call(ByteBuf t1) { return t1.toString(Charset.defaultCharset()); } }).toBlocking().single(); assertEquals(content, result2); } @Test public void testCacheMiss() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); String content = "Hello world"; server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody(content)); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create() .withConfigurationBasedServerList("localhost:" + server.getPort()) .withMaxAutoRetriesNextServer(1)); final String cacheKey = "somekey"; HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test") .withCacheProvider(cacheKey, new CacheProvider<ByteBuf>(){ @Override public Observable<ByteBuf> get(String key, Map<String, Object> vars) { return Observable.error(new Exception("Cache miss again")); } }) .withMethod("GET") .withUriTemplate("/").build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); String result = toStringBlocking(request); assertEquals(content, result); } }
3,527
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/DiscoveryEnabledServerListTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.config.ConfigurationManager; import com.netflix.loadbalancer.Server; import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; import com.netflix.ribbon.http.HttpRequestTemplate; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.testutils.MockedDiscoveryServerListTest; import io.netty.buffer.ByteBuf; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; /** * Created by awang on 7/15/14. */ @PowerMockIgnore("com.google.*") public class DiscoveryEnabledServerListTest extends MockedDiscoveryServerListTest { static MockWebServer server; @BeforeClass public static void init() throws IOException { server = new MockWebServer(); String content = "Hello world"; MockResponse response = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain") .setBody(content); server.enqueue(response); server.play(); } @AfterClass public static void shutdown() { try { server.shutdown(); } catch (IOException e) { e.printStackTrace(); } } @Override protected List<Server> getMockServerList() { List<Server> servers = new ArrayList<Server>(); servers.add(new Server("localhost", 12345)); servers.add(new Server("localhost", server.getPort())); return servers; } @Override protected String getVipAddress() { return "MyService"; } @Test public void testDynamicServers() { ConfigurationManager.getConfigInstance().setProperty("MyService.ribbon." + Keys.DeploymentContextBasedVipAddresses, getVipAddress()); ConfigurationManager.getConfigInstance().setProperty("MyService.ribbon." + Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("MyService") .withClientOptions(ClientOptions.create() .withMaxAutoRetriesNextServer(3) .withReadTimeout(300000)).build(); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class) .withUriTemplate("/") .withMethod("GET").build(); RibbonRequest<ByteBuf> request = template .requestBuilder().build(); String result = request.execute().toString(Charset.defaultCharset()); assertEquals("Hello world", result); } }
3,528
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/MethodTemplateExecutorTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.ribbon.CacheProvider; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.http.HttpRequestBuilder; import com.netflix.ribbon.http.HttpRequestTemplate; import com.netflix.ribbon.http.HttpRequestTemplate.Builder; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.sample.HystrixHandlers.MovieFallbackHandler; import com.netflix.ribbon.proxy.sample.HystrixHandlers.SampleHttpResponseValidator; import com.netflix.ribbon.proxy.sample.Movie; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieService; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.ShortMovieService; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.ContentTransformer; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import rx.Observable; import java.lang.reflect.Method; import java.util.Map; import static com.netflix.ribbon.proxy.Utils.methodByName; import static junit.framework.Assert.assertEquals; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; /** * @author Tomasz Bak */ @RunWith(PowerMockRunner.class) @PrepareForTest({MethodTemplateExecutor.class}) @PowerMockIgnore("javax.management.*") public class MethodTemplateExecutorTest { @Mock private RibbonRequest ribbonRequestMock = createMock(RibbonRequest.class); @Mock private HttpRequestBuilder requestBuilderMock = createMock(HttpRequestBuilder.class); @Mock private Builder httpRequestTemplateBuilderMock = createMock(Builder.class); @Mock private HttpRequestTemplate httpRequestTemplateMock = createMock(HttpRequestTemplate.class); @Mock private HttpResourceGroup httpResourceGroupMock = createMock(HttpResourceGroup.class); @BeforeClass public static void setup() { RibbonDynamicProxy.registerAnnotationProcessors(AnnotationProcessorsProvider.DEFAULT); } @Before public void setUp() throws Exception { expect(requestBuilderMock.build()).andReturn(ribbonRequestMock); expect(httpRequestTemplateBuilderMock.build()).andReturn(httpRequestTemplateMock); expect(httpRequestTemplateMock.requestBuilder()).andReturn(requestBuilderMock); } @Test public void testGetQueryWithDomainObjectResult() throws Exception { expectUrlBase("GET", "/movies/{id}"); expect(requestBuilderMock.withRequestProperty("id", "id123")).andReturn(requestBuilderMock); expect(httpResourceGroupMock.newTemplateBuilder("findMovieById")).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withHeader("X-MyHeader1", "value1.1")).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withHeader("X-MyHeader1", "value1.2")).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withHeader("X-MyHeader2", "value2")).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withRequestCacheKey("findMovieById/{id}")).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withFallbackProvider(anyObject(MovieFallbackHandler.class))).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withResponseValidator(anyObject(SampleHttpResponseValidator.class))).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withCacheProvider(anyObject(String.class), anyObject(CacheProvider.class))).andReturn(httpRequestTemplateBuilderMock); replayAll(); MethodTemplateExecutor executor = createExecutor(SampleMovieService.class, "findMovieById"); RibbonRequest ribbonRequest = executor.executeFromTemplate(new Object[]{"id123"}); verifyAll(); assertEquals(ribbonRequestMock, ribbonRequest); } @Test public void testGetQueryWithByteBufResult() throws Exception { expectUrlBase("GET", "/rawMovies/{id}"); expect(requestBuilderMock.withRequestProperty("id", "id123")).andReturn(requestBuilderMock); expect(httpResourceGroupMock.newTemplateBuilder("findRawMovieById")).andReturn(httpRequestTemplateBuilderMock); replayAll(); MethodTemplateExecutor executor = createExecutor(SampleMovieService.class, "findRawMovieById"); RibbonRequest ribbonRequest = executor.executeFromTemplate(new Object[]{"id123"}); verifyAll(); assertEquals(ribbonRequestMock, ribbonRequest); } @Test public void testPostWithDomainObjectAndTransformer() throws Exception { doTestPostWith("/movies", "registerMovie", new Movie()); } @Test public void testPostWithString() throws Exception { doTestPostWith("/titles", "registerTitle", "some title"); } @Test public void testPostWithByteBuf() throws Exception { doTestPostWith("/binaries/byteBuf", "registerByteBufBinary", createMock(ByteBuf.class)); } @Test public void testPostWithByteArray() throws Exception { doTestPostWith("/binaries/byteArray", "registerByteArrayBinary", new byte[]{1}); } private void doTestPostWith(String uriTemplate, String methodName, Object contentObject) { expectUrlBase("POST", uriTemplate); expect(httpResourceGroupMock.newTemplateBuilder(methodName)).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withRequestCacheKey(methodName)).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withFallbackProvider(anyObject(MovieFallbackHandler.class))).andReturn(httpRequestTemplateBuilderMock); expect(requestBuilderMock.withRawContentSource(anyObject(Observable.class), anyObject(ContentTransformer.class))).andReturn(requestBuilderMock); replayAll(); MethodTemplateExecutor executor = createExecutor(SampleMovieService.class, methodName); RibbonRequest ribbonRequest = executor.executeFromTemplate(new Object[]{contentObject}); verifyAll(); assertEquals(ribbonRequestMock, ribbonRequest); } @Test public void testFromFactory() throws Exception { expect(httpResourceGroupMock.newTemplateBuilder(anyObject(String.class))).andReturn(httpRequestTemplateBuilderMock).anyTimes(); expect(httpRequestTemplateBuilderMock.withMethod(anyObject(String.class))).andReturn(httpRequestTemplateBuilderMock).anyTimes(); expect(httpRequestTemplateBuilderMock.withUriTemplate(anyObject(String.class))).andReturn(httpRequestTemplateBuilderMock).anyTimes(); replayAll(); Map<Method, MethodTemplateExecutor> executorMap = MethodTemplateExecutor.from(httpResourceGroupMock, ShortMovieService.class, AnnotationProcessorsProvider.DEFAULT); assertEquals(ShortMovieService.class.getMethods().length, executorMap.size()); } private void expectUrlBase(String method, String path) { expect(httpRequestTemplateBuilderMock.withMethod(method)).andReturn(httpRequestTemplateBuilderMock); expect(httpRequestTemplateBuilderMock.withUriTemplate(path)).andReturn(httpRequestTemplateBuilderMock); } private MethodTemplateExecutor createExecutor(Class<?> clientInterface, String methodName) { MethodTemplate methodTemplate = new MethodTemplate(methodByName(clientInterface, methodName)); return new MethodTemplateExecutor(httpResourceGroupMock, methodTemplate, AnnotationProcessorsProvider.DEFAULT); } }
3,529
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/MethodTemplateTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.ribbon.proxy.sample.Movie; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.BrokenMovieService; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.PostsWithDifferentContentTypes; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieService; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.TemplateNameDerivedFromMethodName; import com.netflix.ribbon.proxy.sample.MovieTransformer; import io.netty.buffer.ByteBuf; import org.junit.Test; import static com.netflix.ribbon.proxy.Utils.methodByName; import static org.junit.Assert.*; /** * @author Tomasz Bak */ public class MethodTemplateTest { @Test public void testGetWithOneParameter() throws Exception { MethodTemplate template = new MethodTemplate(methodByName(SampleMovieService.class, "findMovieById")); assertEquals("id", template.getParamName(0)); assertEquals("findMovieById", template.getTemplateName()); assertEquals(0, template.getParamPosition(0)); assertEquals(template.getResultType(), ByteBuf.class); } @Test public void testGetWithTwoParameters() throws Exception { MethodTemplate template = new MethodTemplate(methodByName(SampleMovieService.class, "findMovie")); assertEquals("findMovie", template.getTemplateName()); assertEquals("name", template.getParamName(0)); assertEquals(0, template.getParamPosition(0)); assertEquals("author", template.getParamName(1)); assertEquals(1, template.getParamPosition(1)); } @Test public void testTemplateNameCanBeDerivedFromMethodName() throws Exception { MethodTemplate template = new MethodTemplate(methodByName(TemplateNameDerivedFromMethodName.class, "myTemplateName")); assertEquals("myTemplateName", template.getTemplateName()); } @Test public void testWithRawContentSourceContent() throws Exception { MethodTemplate methodTemplate = new MethodTemplate(methodByName(PostsWithDifferentContentTypes.class, "postwithRawContentSource")); assertEquals(2, methodTemplate.getContentArgPosition()); assertNotNull(methodTemplate.getContentTransformerClass()); assertEquals(Movie.class, methodTemplate.getGenericContentType()); } @Test public void testWithByteBufContent() throws Exception { MethodTemplate methodTemplate = new MethodTemplate(methodByName(PostsWithDifferentContentTypes.class, "postwithByteBufContent")); assertEquals(0, methodTemplate.getContentArgPosition()); assertNull(methodTemplate.getContentTransformerClass()); } @Test public void testWithByteArrayContent() throws Exception { MethodTemplate methodTemplate = new MethodTemplate(methodByName(PostsWithDifferentContentTypes.class, "postwithByteArrayContent")); assertEquals(0, methodTemplate.getContentArgPosition()); assertNull(methodTemplate.getContentTransformerClass()); } @Test public void testWithStringContent() throws Exception { MethodTemplate methodTemplate = new MethodTemplate(methodByName(PostsWithDifferentContentTypes.class, "postwithStringContent")); assertEquals(0, methodTemplate.getContentArgPosition()); assertNull(methodTemplate.getContentTransformerClass()); } @Test public void testWithUserClassContent() throws Exception { MethodTemplate methodTemplate = new MethodTemplate(methodByName(PostsWithDifferentContentTypes.class, "postwithMovieContent")); assertEquals(0, methodTemplate.getContentArgPosition()); assertNotNull(methodTemplate.getContentTransformerClass()); assertTrue(MovieTransformer.class.equals(methodTemplate.getContentTransformerClass())); } @Test(expected = ProxyAnnotationException.class) public void testWithUserClassContentAndNotDefinedContentTransformer() { new MethodTemplate(methodByName(PostsWithDifferentContentTypes.class, "postwithMovieContentBroken")); } @Test public void testFromFactory() throws Exception { MethodTemplate[] methodTemplates = MethodTemplate.from(SampleMovieService.class); assertEquals(SampleMovieService.class.getMethods().length, methodTemplates.length); } @Test(expected = ProxyAnnotationException.class) public void testDetectsInvalidResultType() throws Exception { new MethodTemplate(methodByName(BrokenMovieService.class, "returnTypeNotRibbonRequest")); } @Test(expected = ProxyAnnotationException.class) public void testMissingHttpMethod() throws Exception { new MethodTemplate(methodByName(BrokenMovieService.class, "missingHttpAnnotation")); } @Test(expected = ProxyAnnotationException.class) public void testMultipleContentParameters() throws Exception { new MethodTemplate(methodByName(BrokenMovieService.class, "multipleContentParameters")); } }
3,530
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/ClassTemplateTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import org.junit.Test; import com.netflix.ribbon.proxy.ClassTemplate; import com.netflix.ribbon.proxy.RibbonProxyException; import static com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.*; import static org.junit.Assert.*; /** * @author Tomasz Bak */ public class ClassTemplateTest { @Test public void testResourceGroupAnnotationMissing() throws Exception { ClassTemplate classTemplate = new ClassTemplate(SampleMovieService.class); assertNull("resource group class not expected", classTemplate.getResourceGroupClass()); assertNull("resource name not expected", classTemplate.getResourceGroupName()); } @Test public void testCreateWithResourceGroupNameAnnotation() throws Exception { ClassTemplate classTemplate = new ClassTemplate(SampleMovieServiceWithResourceGroupNameAnnotation.class); assertNull("resource group class not expected", classTemplate.getResourceGroupClass()); assertNotNull("resource name expected", classTemplate.getResourceGroupName()); } @Test public void testCreateWithResourceGroupClassAnnotation() throws Exception { ClassTemplate classTemplate = new ClassTemplate(SampleMovieServiceWithResourceGroupClassAnnotation.class); assertNotNull("resource group class expected", classTemplate.getResourceGroupClass()); assertNull("resource name not expected", classTemplate.getResourceGroupName()); } @Test(expected = RibbonProxyException.class) public void testBothNameAndResourceGroupClassInAnnotation() throws Exception { new ClassTemplate(BrokenMovieServiceWithResourceGroupNameAndClassAnnotation.class); } }
3,531
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/ShutDownTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieService; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import org.junit.Test; import rx.Observable; import rx.Subscription; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertTrue; /** * @author Allen Wang */ public class ShutDownTest { @Test public void testLifeCycleShutdown() throws Exception { final AtomicBoolean shutDownCalled = new AtomicBoolean(false); final HttpClient<ByteBuf, ByteBuf> client = new HttpClient<ByteBuf, ByteBuf>() { @Override public Observable<HttpClientResponse<ByteBuf>> submit(HttpClientRequest<ByteBuf> request) { return null; } @Override public Observable<HttpClientResponse<ByteBuf>> submit(HttpClientRequest<ByteBuf> request, ClientConfig config) { return null; } @Override public Observable<ObservableConnection<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>>> connect() { return null; } @Override public void shutdown() { shutDownCalled.set(true); } @Override public String name() { return "SampleMovieService"; } @Override public Subscription subscribe(MetricEventsListener<? extends ClientMetricsEvent<?>> listener) { return null; } }; RibbonTransportFactory transportFactory = new RibbonTransportFactory(ClientConfigFactory.DEFAULT) { @Override public HttpClient<ByteBuf, ByteBuf> newHttpClient(IClientConfig config) { return client; } }; HttpResourceGroup.Builder groupBuilder = HttpResourceGroup.Builder.newBuilder("SampleMovieService", ClientConfigFactory.DEFAULT, transportFactory); HttpResourceGroup group = groupBuilder.build(); SampleMovieService service = RibbonDynamicProxy.newInstance(SampleMovieService.class, group); ProxyLifeCycle proxyLifeCycle = (ProxyLifeCycle) service; proxyLifeCycle.shutdown(); assertTrue(proxyLifeCycle.isShutDown()); assertTrue(shutDownCalled.get()); } }
3,532
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/UtilsTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import org.junit.Test; import java.io.InputStream; import java.lang.reflect.Method; import static junit.framework.Assert.*; /** * @author Tomasz Bak */ public class UtilsTest { @Test public void testMethodByName() throws Exception { Method source = Utils.methodByName(String.class, "equals"); assertNotNull(source); assertEquals("equals", source.getName()); assertNull(Utils.methodByName(String.class, "not_equals")); } @Test public void testExecuteOnInstance() throws Exception { Method source = Utils.methodByName(String.class, "equals"); Object obj = new Object(); assertEquals(Boolean.TRUE, Utils.executeOnInstance(obj, source, new Object[]{obj})); assertEquals(Boolean.FALSE, Utils.executeOnInstance(obj, source, new Object[]{this})); } @Test(expected = IllegalArgumentException.class) public void testExecuteNotExistingMethod() throws Exception { Method source = Utils.methodByName(String.class, "getChars"); Utils.executeOnInstance(new Object(), source, new Object[]{}); } @Test public void testNewInstance() throws Exception { assertNotNull(Utils.newInstance(Object.class)); } @Test(expected = RibbonProxyException.class) public void testNewInstanceForFailure() throws Exception { Utils.newInstance(InputStream.class); } }
3,533
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/RibbonDynamicProxyTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieService; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieServiceWithResourceGroupNameAnnotation; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import static com.netflix.ribbon.proxy.Utils.methodByName; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; import static org.junit.Assert.*; /** * @author Tomasz Bak */ @RunWith(PowerMockRunner.class) @PrepareForTest({RibbonDynamicProxy.class, MethodTemplateExecutor.class}) public class RibbonDynamicProxyTest { @Mock private HttpResourceGroup httpResourceGroupMock; @Mock private ProxyHttpResourceGroupFactory httpResourceGroupFactoryMock; @Mock private RibbonRequest ribbonRequestMock; @Mock private HttpClient<ByteBuf, ByteBuf> httpClientMock; @Before public void setUp() throws Exception { expect(httpResourceGroupFactoryMock.createResourceGroup()).andReturn(httpResourceGroupMock); } @Test(expected = IllegalArgumentException.class) public void testAcceptsInterfaceOnly() throws Exception { RibbonDynamicProxy.newInstance(Object.class, null); } @Test public void testSetupWithExplicitResourceGroupObject() throws Exception { replayAll(); RibbonDynamicProxy.newInstance(SampleMovieServiceWithResourceGroupNameAnnotation.class, httpResourceGroupMock); } @Test public void testSetupWithResourceGroupNameInAnnotation() throws Exception { mockStatic(ProxyHttpResourceGroupFactory.class); expectNew(ProxyHttpResourceGroupFactory.class, new Class[]{ClassTemplate.class, RibbonResourceFactory.class, AnnotationProcessorsProvider.class }, anyObject(), anyObject(), anyObject()).andReturn(httpResourceGroupFactoryMock); replayAll(); RibbonDynamicProxy.newInstance(SampleMovieServiceWithResourceGroupNameAnnotation.class); } @Test public void testTypedClientGetWithPathParameter() throws Exception { initializeSampleMovieServiceMocks(); replayAll(); SampleMovieService service = RibbonDynamicProxy.newInstance(SampleMovieService.class, httpResourceGroupMock); RibbonRequest<ByteBuf> ribbonMovie = service.findMovieById("123"); assertNotNull(ribbonMovie); } @Test public void testPlainObjectInvocations() throws Exception { initializeSampleMovieServiceMocks(); replayAll(); SampleMovieService service = RibbonDynamicProxy.newInstance(SampleMovieService.class, httpResourceGroupMock); assertFalse(service.equals(this)); assertEquals(service.toString(), "RibbonDynamicProxy{...}"); } private void initializeSampleMovieServiceMocks() { MethodTemplateExecutor tgMock = createMock(MethodTemplateExecutor.class); expect(tgMock.executeFromTemplate(anyObject(Object[].class))).andReturn(ribbonRequestMock); Map<Method, MethodTemplateExecutor> tgMap = new HashMap<Method, MethodTemplateExecutor>(); tgMap.put(methodByName(SampleMovieService.class, "findMovieById"), tgMock); mockStatic(MethodTemplateExecutor.class); expect(MethodTemplateExecutor.from(httpResourceGroupMock, SampleMovieService.class, AnnotationProcessorsProvider.DEFAULT)).andReturn(tgMap); } }
3,534
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/ClientPropertiesTest.java
package com.netflix.ribbon.proxy; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.config.ConfigurationManager; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.RibbonTransportFactory.DefaultRibbonTransportFactory; import com.netflix.ribbon.proxy.annotation.ClientProperties; import com.netflix.ribbon.proxy.annotation.ClientProperties.Property; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieService; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClient; import org.apache.commons.configuration.Configuration; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author Allen Wang */ public class ClientPropertiesTest { private static class MyTransportFactory extends DefaultRibbonTransportFactory { private IClientConfig config; public MyTransportFactory(ClientConfigFactory clientConfigFactory) { super(clientConfigFactory); } @Override public HttpClient<ByteBuf, ByteBuf> newHttpClient(IClientConfig config) { this.config = config; return super.newHttpClient(config); } public IClientConfig getClientConfig() { return this.config; } } @ClientProperties(properties = { @Property(name="ReadTimeout", value="3000"), @Property(name="ConnectTimeout", value="1000"), @Property(name="MaxAutoRetriesNextServer", value="0") }) public static interface MovieService extends SampleMovieService { } @Test public void testAnnotation() { MyTransportFactory transportFactory = new MyTransportFactory(ClientConfigFactory.DEFAULT); RibbonResourceFactory resourceFactory = new DefaultResourceFactory(ClientConfigFactory.DEFAULT, transportFactory); RibbonDynamicProxy.newInstance(SampleMovieService.class, resourceFactory, ClientConfigFactory.DEFAULT, transportFactory); IClientConfig clientConfig = transportFactory.getClientConfig(); assertEquals(1000, clientConfig.get(Keys.ConnectTimeout).longValue()); assertEquals(2000, clientConfig.get(Keys.ReadTimeout).longValue()); Configuration config = ConfigurationManager.getConfigInstance(); assertEquals("2000", config.getProperty("SampleMovieService.ribbon.ReadTimeout")); assertEquals("1000", config.getProperty("SampleMovieService.ribbon.ConnectTimeout")); config.setProperty("SampleMovieService.ribbon.ReadTimeout", "5000"); assertEquals(5000, clientConfig.get(Keys.ReadTimeout).longValue()); } @Test public void testNoExportToArchaius() { MyTransportFactory transportFactory = new MyTransportFactory(ClientConfigFactory.DEFAULT); RibbonResourceFactory resourceFactory = new DefaultResourceFactory(ClientConfigFactory.DEFAULT, transportFactory); RibbonDynamicProxy.newInstance(MovieService.class, resourceFactory, ClientConfigFactory.DEFAULT, transportFactory); IClientConfig clientConfig = transportFactory.getClientConfig(); assertEquals(1000, clientConfig.get(Keys.ConnectTimeout).longValue()); assertEquals(3000, clientConfig.get(Keys.ReadTimeout).longValue()); assertEquals(0, clientConfig.get(Keys.MaxAutoRetriesNextServer).longValue()); Configuration config = ConfigurationManager.getConfigInstance(); assertNull(config.getProperty("MovieService.ribbon.ReadTimeout")); config.setProperty("MovieService.ribbon.ReadTimeout", "5000"); assertEquals(5000, clientConfig.get(Keys.ReadTimeout).longValue()); } }
3,535
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/HttpResourceGroupFactoryTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieService; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieServiceWithResourceGroupClassAnnotation; import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieServiceWithResourceGroupNameAnnotation; import com.netflix.ribbon.proxy.sample.ResourceGroupClasses.SampleHttpResourceGroup; import org.junit.Test; import static org.junit.Assert.*; /** * @author Tomasz Bak */ public class HttpResourceGroupFactoryTest { @Test public void testResourceGroupAnnotationMissing() throws Exception { ClassTemplate<SampleMovieService> classTemplate = new ClassTemplate<SampleMovieService>(SampleMovieService.class); new ProxyHttpResourceGroupFactory<SampleMovieService>(classTemplate, new DefaultResourceFactory(ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT, AnnotationProcessorsProvider.DEFAULT), AnnotationProcessorsProvider.DEFAULT).createResourceGroup(); } @Test public void testCreateWithResourceGroupNameAnnotation() throws Exception { testResourceGroupCreation(SampleMovieServiceWithResourceGroupNameAnnotation.class, HttpResourceGroup.class); } @Test public void testCreateWithResourceGroupClassAnnotation() throws Exception { testResourceGroupCreation(SampleMovieServiceWithResourceGroupClassAnnotation.class, SampleHttpResourceGroup.class); } private void testResourceGroupCreation(Class<?> clientInterface, Class<? extends HttpResourceGroup> httpResourceGroupClass) { ClassTemplate classTemplate = new ClassTemplate(clientInterface); HttpResourceGroup resourceGroup = new ProxyHttpResourceGroupFactory(classTemplate).createResourceGroup(); assertNotNull("got null and expected instance of " + httpResourceGroupClass, resourceGroup); } }
3,536
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/sample/SampleCacheProviderFactory.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.sample; import com.netflix.ribbon.CacheProvider; import com.netflix.ribbon.CacheProviderFactory; import rx.Observable; import java.util.Map; /** * @author Tomasz Bak */ public class SampleCacheProviderFactory implements CacheProviderFactory<Object> { @Override public CacheProvider<Object> createCacheProvider() { return new SampleCacheProvider(); } public static class SampleCacheProvider implements CacheProvider<Object> { @Override public Observable<Object> get(String key, Map requestProperties) { return null; } } }
3,537
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/sample/ResourceGroupClasses.java
package com.netflix.ribbon.proxy.sample; import com.netflix.ribbon.http.HttpResourceGroup; /** * @author Tomasz Bak */ public class ResourceGroupClasses { public static class SampleHttpResourceGroup extends HttpResourceGroup { public SampleHttpResourceGroup() { super("myTestGroup"); } } }
3,538
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/sample/MovieTransformer.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.sample; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.reactivex.netty.channel.ContentTransformer; /** * @author Tomasz Bak */ public class MovieTransformer implements ContentTransformer<MovieTransformer> { @Override public ByteBuf call(MovieTransformer toTransform, ByteBufAllocator byteBufAllocator) { return null; } }
3,539
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/sample/MovieServiceInterfaces.java
package com.netflix.ribbon.proxy.sample; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.proxy.annotation.CacheProvider; import com.netflix.ribbon.proxy.annotation.ClientProperties; import com.netflix.ribbon.proxy.annotation.ClientProperties.Property; import com.netflix.ribbon.proxy.annotation.Content; import com.netflix.ribbon.proxy.annotation.ContentTransformerClass; import com.netflix.ribbon.proxy.annotation.Http; import com.netflix.ribbon.proxy.annotation.Http.Header; import com.netflix.ribbon.proxy.annotation.Http.HttpMethod; import com.netflix.ribbon.proxy.annotation.Hystrix; import com.netflix.ribbon.proxy.annotation.ResourceGroup; import com.netflix.ribbon.proxy.annotation.TemplateName; import com.netflix.ribbon.proxy.annotation.Var; import com.netflix.ribbon.proxy.sample.HystrixHandlers.MovieFallbackHandler; import com.netflix.ribbon.proxy.sample.HystrixHandlers.SampleHttpResponseValidator; import io.netty.buffer.ByteBuf; import rx.Observable; import java.util.concurrent.atomic.AtomicReference; import static com.netflix.ribbon.proxy.sample.ResourceGroupClasses.SampleHttpResourceGroup; /** * @author Tomasz Bak */ public class MovieServiceInterfaces { @ClientProperties(properties = { @Property(name="ReadTimeout", value="2000"), @Property(name="ConnectTimeout", value="1000"), @Property(name="MaxAutoRetriesNextServer", value="2") }, exportToArchaius = true) public static interface SampleMovieService { @TemplateName("findMovieById") @Http( method = HttpMethod.GET, uri = "/movies/{id}", headers = { @Header(name = "X-MyHeader1", value = "value1.1"), @Header(name = "X-MyHeader1", value = "value1.2"), @Header(name = "X-MyHeader2", value = "value2") }) @Hystrix( cacheKey = "findMovieById/{id}", validator = SampleHttpResponseValidator.class, fallbackHandler = MovieFallbackHandler.class) @CacheProvider(key = "findMovieById_{id}", provider = SampleCacheProviderFactory.class) RibbonRequest<ByteBuf> findMovieById(@Var("id") String id); @TemplateName("findRawMovieById") @Http(method = HttpMethod.GET, uri = "/rawMovies/{id}") RibbonRequest<ByteBuf> findRawMovieById(@Var("id") String id); @TemplateName("findMovie") @Http(method = HttpMethod.GET, uri = "/movies?name={name}&author={author}") RibbonRequest<ByteBuf> findMovie(@Var("name") String name, @Var("author") String author); @TemplateName("registerMovie") @Http(method = HttpMethod.POST, uri = "/movies") @Hystrix(cacheKey = "registerMovie", fallbackHandler = MovieFallbackHandler.class) @ContentTransformerClass(MovieTransformer.class) RibbonRequest<ByteBuf> registerMovie(@Content Movie movie); @Http(method = HttpMethod.PUT, uri = "/movies/{id}") @ContentTransformerClass(MovieTransformer.class) RibbonRequest<ByteBuf> updateMovie(@Var("id") String id, @Content Movie movie); @Http(method = HttpMethod.PATCH, uri = "/movies/{id}") @ContentTransformerClass(MovieTransformer.class) RibbonRequest<ByteBuf> updateMoviePartial(@Var("id") String id, @Content Movie movie); @TemplateName("registerTitle") @Http(method = HttpMethod.POST, uri = "/titles") @Hystrix(cacheKey = "registerTitle", fallbackHandler = MovieFallbackHandler.class) RibbonRequest<ByteBuf> registerTitle(@Content String title); @TemplateName("registerByteBufBinary") @Http(method = HttpMethod.POST, uri = "/binaries/byteBuf") @Hystrix(cacheKey = "registerByteBufBinary", fallbackHandler = MovieFallbackHandler.class) RibbonRequest<ByteBuf> registerByteBufBinary(@Content ByteBuf binary); @TemplateName("registerByteArrayBinary") @Http(method = HttpMethod.POST, uri = "/binaries/byteArray") @Hystrix(cacheKey = "registerByteArrayBinary", fallbackHandler = MovieFallbackHandler.class) RibbonRequest<ByteBuf> registerByteArrayBinary(@Content byte[] binary); @TemplateName("deleteMovie") @Http(method = HttpMethod.DELETE, uri = "/movies/{id}") RibbonRequest<ByteBuf> deleteMovie(@Var("id") String id); } public static interface ShortMovieService { @TemplateName("findMovieById") @Http(method = HttpMethod.GET, uri = "/movies/{id}") RibbonRequest<ByteBuf> findMovieById(@Var("id") String id); @TemplateName("findMovieById") @Http(method = HttpMethod.GET, uri = "/movies") RibbonRequest<ByteBuf> findAll(); } public static interface BrokenMovieService { @Http(method = HttpMethod.GET) Movie returnTypeNotRibbonRequest(); Movie missingHttpAnnotation(); @Http(method = HttpMethod.GET) RibbonRequest<ByteBuf> multipleContentParameters(@Content Movie content1, @Content Movie content2); } @ResourceGroup(name = "testResourceGroup") public static interface SampleMovieServiceWithResourceGroupNameAnnotation { } @ResourceGroup(resourceGroupClass = SampleHttpResourceGroup.class) public static interface SampleMovieServiceWithResourceGroupClassAnnotation { } @ResourceGroup(name = "testResourceGroup", resourceGroupClass = SampleHttpResourceGroup.class) public static interface BrokenMovieServiceWithResourceGroupNameAndClassAnnotation { } @ResourceGroup(name = "testResourceGroup") public static interface TemplateNameDerivedFromMethodName { @Http(method = HttpMethod.GET, uri = "/template") RibbonRequest<ByteBuf> myTemplateName(); } @ResourceGroup(name = "testResourceGroup") public static interface HystrixOptionalAnnotationValues { @TemplateName("hystrix1") @Http(method = HttpMethod.GET, uri = "/hystrix/1") @Hystrix(cacheKey = "findMovieById/{id}") RibbonRequest<ByteBuf> hystrixWithCacheKeyOnly(); @TemplateName("hystrix2") @Http(method = HttpMethod.GET, uri = "/hystrix/2") @Hystrix(validator = SampleHttpResponseValidator.class) RibbonRequest<ByteBuf> hystrixWithValidatorOnly(); @TemplateName("hystrix3") @Http(method = HttpMethod.GET, uri = "/hystrix/3") @Hystrix(fallbackHandler = MovieFallbackHandler.class) RibbonRequest<ByteBuf> hystrixWithFallbackHandlerOnly(); } @ResourceGroup(name = "testResourceGroup") public static interface PostsWithDifferentContentTypes { @TemplateName("rawContentSource") @Http(method = HttpMethod.POST, uri = "/content/rawContentSource") @ContentTransformerClass(MovieTransformer.class) RibbonRequest<ByteBuf> postwithRawContentSource(AtomicReference<Object> arg1, int arg2, @Content Observable<Movie> movie); @TemplateName("byteBufContent") @Http(method = HttpMethod.POST, uri = "/content/byteBufContent") RibbonRequest<ByteBuf> postwithByteBufContent(@Content ByteBuf byteBuf); @TemplateName("byteArrayContent") @Http(method = HttpMethod.POST, uri = "/content/byteArrayContent") RibbonRequest<ByteBuf> postwithByteArrayContent(@Content byte[] bytes); @TemplateName("stringContent") @Http(method = HttpMethod.POST, uri = "/content/stringContent") RibbonRequest<ByteBuf> postwithStringContent(@Content String content); @TemplateName("movieContent") @Http(method = HttpMethod.POST, uri = "/content/movieContent") @ContentTransformerClass(MovieTransformer.class) RibbonRequest<ByteBuf> postwithMovieContent(@Content Movie movie); @TemplateName("movieContentBroken") @Http(method = HttpMethod.POST, uri = "/content/movieContentBroken") RibbonRequest<ByteBuf> postwithMovieContentBroken(@Content Movie movie); } }
3,540
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/sample/HystrixHandlers.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.sample; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.ribbon.ServerError; import com.netflix.ribbon.UnsuccessfulResponseException; import com.netflix.ribbon.http.HttpResponseValidator; import com.netflix.ribbon.hystrix.FallbackHandler; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import rx.Observable; import java.util.Map; /** * @author Tomasz Bak */ public class HystrixHandlers { public static class SampleHttpResponseValidator implements HttpResponseValidator { @Override public void validate(HttpClientResponse<ByteBuf> response) throws UnsuccessfulResponseException, ServerError { } } public static class MovieFallbackHandler implements FallbackHandler<Movie> { @Override public Observable<Movie> getFallback(HystrixInvokableInfo<?> hystrixInfo, Map<String, Object> requestProperties) { return null; } } }
3,541
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/proxy/sample/Movie.java
package com.netflix.ribbon.proxy.sample; /** * @author Tomasz Bak */ public class Movie { }
3,542
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/http/TemplateBuilderTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.ribbon.CacheProvider; import com.netflix.ribbon.ClientOptions; import com.netflix.ribbon.Ribbon; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.hystrix.HystrixObservableCommandChain; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpRequestHeaders; import org.junit.Test; import rx.Observable; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; public class TemplateBuilderTest { private static class FakeCacheProvider implements CacheProvider<ByteBuf> { String id; FakeCacheProvider(String id) { this.id = id; } @Override public Observable<ByteBuf> get(final String key, Map<String, Object> requestProperties) { if (key.equals(id)) { return Observable.just(Unpooled.buffer().writeBytes(id.getBytes(Charset.defaultCharset()))); } else { return Observable.error(new IllegalArgumentException()); } }; } @Test public void testVarReplacement() { HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("test").build(); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("testVarReplacement", ByteBuf.class) .withMethod("GET") .withUriTemplate("/foo/{id}?name={name}").build(); HttpClientRequest<ByteBuf> request = template .requestBuilder() .withRequestProperty("id", "3") .withRequestProperty("name", "netflix") .createClientRequest(); assertEquals("/foo/3?name=netflix", request.getUri()); } @Test public void testCacheKeyTemplates() { HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("test").build(); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("testCacheKeyTemplates", ByteBuf.class) .withUriTemplate("/foo/{id}") .withMethod("GET") .withCacheProvider("/cache/{id}", new FakeCacheProvider("/cache/5")) .build(); RibbonRequest<ByteBuf> request = template.requestBuilder().withRequestProperty("id", 5).build(); ByteBuf result = request.execute(); assertEquals("/cache/5", result.toString(Charset.defaultCharset())); } @Test public void testHttpHeaders() { HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("test") .withHeader("header1", "group").build(); HttpRequestTemplate<String> template = group.newTemplateBuilder("testHttpHeaders", String.class) .withUriTemplate("/foo/bar") .withMethod("GET") .withHeader("header2", "template") .withHeader("header1", "template").build(); HttpRequestBuilder<String> requestBuilder = template.requestBuilder(); requestBuilder.withHeader("header3", "builder").withHeader("header1", "builder"); HttpClientRequest<ByteBuf> request = requestBuilder.createClientRequest(); HttpRequestHeaders headers = request.getHeaders(); List<String> header1 = headers.getAll("header1"); assertEquals(3, header1.size()); assertEquals("group", header1.get(0)); assertEquals("template", header1.get(1)); assertEquals("builder", header1.get(2)); List<String> header2 = headers.getAll("header2"); assertEquals(1, header2.size()); assertEquals("template", header2.get(0)); List<String> header3 = headers.getAll("header3"); assertEquals(1, header3.size()); assertEquals("builder", header3.get(0)); } @Test public void testHystrixProperties() { ClientOptions clientOptions = ClientOptions.create() .withMaxAutoRetriesNextServer(1) .withMaxAutoRetries(1) .withConnectTimeout(1000) .withMaxTotalConnections(400) .withReadTimeout(2000); HttpResourceGroup group = Ribbon.createHttpResourceGroup("test", clientOptions); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("testHystrixProperties", ByteBuf.class) .withMethod("GET") .withUriTemplate("/foo/bar").build(); HttpRequest<ByteBuf> request = (HttpRequest<ByteBuf>) template .requestBuilder().build(); HystrixObservableCommandChain<ByteBuf> hystrixCommandChain = request.createHystrixCommandChain(); HystrixCommandProperties props = hystrixCommandChain.getCommands().get(0).getProperties(); assertEquals(400, props.executionIsolationSemaphoreMaxConcurrentRequests().get().intValue()); assertEquals(12000, props.executionIsolationThreadTimeoutInMilliseconds().get().intValue()); } }
3,543
0
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/test/java/com/netflix/ribbon/hystrix/HystrixCommandChainTest.java
package com.netflix.ribbon.hystrix; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import rx.Notification; import rx.Observable; import rx.Observer; import rx.subjects.ReplaySubject; import rx.subjects.Subject; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; /** * @author Tomasz Bak */ public class HystrixCommandChainTest { private TestableHystrixObservableCommand command1 = new TestableHystrixObservableCommand("result1"); private TestableHystrixObservableCommand command2 = new TestableHystrixObservableCommand("result2"); private TestableHystrixObservableCommand errorCommand1 = new TestableHystrixObservableCommand(new RuntimeException("error1")); private TestableHystrixObservableCommand errorCommand2 = new TestableHystrixObservableCommand(new RuntimeException("error2")); @Test public void testMaterializedNotificationObservableFirstOK() throws Exception { HystrixObservableCommandChain<String> commandChain = new HystrixObservableCommandChain<String>(command1, errorCommand1); ResultCommandPair<String> pair = commandChain.toResultCommandPairObservable().toBlocking().single(); assertEquals("result1", pair.getResult()); assertEquals("expected first hystrix command", command1, pair.getCommand()); } @Test public void testMaterializedNotificationObservableLastOK() throws Exception { HystrixObservableCommandChain<String> commandChain = new HystrixObservableCommandChain<String>(errorCommand1, command2); ResultCommandPair<String> pair = commandChain.toResultCommandPairObservable().toBlocking().single(); assertEquals("result2", pair.getResult()); assertEquals("expected first hystrix command", command2, pair.getCommand()); } @Test public void testMaterializedNotificationObservableError() throws Exception { HystrixObservableCommandChain<String> commandChain = new HystrixObservableCommandChain<String>(errorCommand1, errorCommand2); Notification<ResultCommandPair<String>> notification = commandChain.toResultCommandPairObservable().materialize().toBlocking().single(); assertTrue("onError notification expected", notification.isOnError()); assertEquals(errorCommand2, commandChain.getLastCommand()); } @Test public void testObservableOK() throws Exception { HystrixObservableCommandChain<String> commandChain = new HystrixObservableCommandChain<String>(command1, errorCommand1); String value = commandChain.toObservable().toBlocking().single(); assertEquals("result1", value); } @Test(expected = RuntimeException.class) public void testObservableError() throws Exception { HystrixObservableCommandChain<String> commandChain = new HystrixObservableCommandChain<String>(errorCommand1, errorCommand2); commandChain.toObservable().toBlocking().single(); } private static final class TestableHystrixObservableCommand extends HystrixObservableCommand<String> { private final String[] values; private final Throwable error; private TestableHystrixObservableCommand(String... values) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("test"))); this.values = values; error = null; } private TestableHystrixObservableCommand(Throwable error) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("test"))); values = null; this.error = error; } @Override protected Observable<String> construct() { Subject<String, String> subject = ReplaySubject.create(); fireEvents(subject); return subject; } public void fireEvents(Observer<String> observer) { if (values != null) { for (String v : values) { observer.onNext(v); } } if (error == null) { observer.onCompleted(); } else { observer.onError(error); } } } }
3,544
0
Create_ds/ribbon/ribbon/src/examples/java/com/netflix
Create_ds/ribbon/ribbon/src/examples/java/com/netflix/ribbon/RibbonExamples.java
package com.netflix.ribbon; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import java.util.Map; import rx.Observable; import rx.functions.Func1; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.ribbon.http.HttpRequestTemplate; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.hystrix.FallbackHandler; public class RibbonExamples { public static void main(String[] args) { HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient"); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("GetUser") .withResponseValidator(new ResponseValidator<HttpClientResponse<ByteBuf>>() { @Override public void validate(HttpClientResponse<ByteBuf> response) throws UnsuccessfulResponseException, ServerError { if (response.getStatus().code() >= 500) { throw new ServerError("Unexpected response"); } } }) .withFallbackProvider(new FallbackHandler<ByteBuf>() { @Override public Observable<ByteBuf> getFallback(HystrixInvokableInfo<?> t1, Map<String, Object> vars) { return Observable.empty(); } }) .withHystrixProperties((HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("mygroup")) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationThreadTimeoutInMilliseconds(2000)))) .withUriTemplate("/{id}").build(); template.requestBuilder().withRequestProperty("id", 1).build().execute(); // example showing the use case of getting the entity with Hystrix meta data template.requestBuilder().withRequestProperty("id", 3).build().withMetadata().observe() .flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<String>>() { @Override public Observable<String> call(RibbonResponse<Observable<ByteBuf>> t1) { if (t1.getHystrixInfo().isResponseFromFallback()) { return Observable.empty(); } return t1.content().map(new Func1<ByteBuf, String>(){ @Override public String call(ByteBuf t1) { return t1.toString(); } }); } }); } }
3,545
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/RequestWithMetaData.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import java.util.concurrent.Future; import rx.Observable; /** * A decorated request object whose response content contains the execution meta data. * * @author Allen Wang * */ public interface RequestWithMetaData<T> { /** * Non blocking API that returns an {@link Observable} while the execution is started asynchronously. * Subscribing to the returned {@link Observable} is guaranteed to get the complete sequence from * the beginning, which might be replayed by the framework. */ Observable<RibbonResponse<Observable<T>>> observe(); /** * Non blocking API that returns an Observable. The execution is not started until the returned Observable is subscribed to. */ Observable<RibbonResponse<Observable<T>>> toObservable(); /** * Non blocking API that returns a {@link Future}, where its {@link Future#get()} method is blocking and returns a * single (or last element if there is a sequence of objects from the execution) element */ Future<RibbonResponse<T>> queue(); /** * Blocking API that returns a single (or last element if there is a sequence of objects from the execution) element */ RibbonResponse<T> execute(); }
3,546
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/CacheProvider.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import java.util.Map; import com.netflix.ribbon.RequestTemplate.RequestBuilder; import rx.Observable; public interface CacheProvider<T> { /** * @param keyTemplate A key template which may contain variable, e.g., /foo/bar/{id}, * where the variable will be substituted with real value by {@link RequestBuilder} * * @param requestProperties Key value pairs provided via {@link RequestBuilder#withRequestProperty(String, Object)} * * @return Cache content as a lazy {@link Observable}. It is assumed that * the actual cache retrieval does not happen until the returned {@link Observable} * is subscribed to. */ Observable<T> get(String keyTemplate, Map<String, Object> requestProperties); }
3,547
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/ServerError.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; @SuppressWarnings("serial") public class ServerError extends Exception { public ServerError(String message, Throwable cause) { super(message, cause); } public ServerError(String message) { super(message); } public ServerError(Throwable cause) { super(cause); } }
3,548
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/CacheProviderFactory.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; public interface CacheProviderFactory<T> { CacheProvider<T> createCacheProvider(); }
3,549
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/ClientOptions.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * API to construct Ribbon client options to be used by {@link ResourceGroup} * * @author awang * */ public final class ClientOptions { private Map<IClientConfigKey<?>, Object> options; private ClientOptions() { options = new ConcurrentHashMap<>(); } public static ClientOptions create() { return new ClientOptions(); } public static ClientOptions from(IClientConfig config) { ClientOptions options = new ClientOptions(); for (IClientConfigKey key: IClientConfigKey.Keys.keys()) { Object value = config.get(key); if (value != null) { options.options.put(key, value); } } return options; } public ClientOptions withDiscoveryServiceIdentifier(String identifier) { options.put(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, identifier); return this; } public ClientOptions withConfigurationBasedServerList(String serverList) { options.put(IClientConfigKey.Keys.ListOfServers, serverList); return this; } public ClientOptions withMaxAutoRetries(int value) { options.put(IClientConfigKey.Keys.MaxAutoRetries, value); return this; } public ClientOptions withMaxAutoRetriesNextServer(int value) { options.put(IClientConfigKey.Keys.MaxAutoRetriesNextServer, value); return this; } public ClientOptions withRetryOnAllOperations(boolean value) { options.put(IClientConfigKey.Keys.OkToRetryOnAllOperations, value); return this; } public ClientOptions withMaxConnectionsPerHost(int value) { options.put(IClientConfigKey.Keys.MaxConnectionsPerHost, value); return this; } public ClientOptions withMaxTotalConnections(int value) { options.put(IClientConfigKey.Keys.MaxTotalConnections, value); return this; } public ClientOptions withConnectTimeout(int value) { options.put(IClientConfigKey.Keys.ConnectTimeout, value); return this; } public ClientOptions withReadTimeout(int value) { options.put(IClientConfigKey.Keys.ReadTimeout, value); return this; } public ClientOptions withFollowRedirects(boolean value) { options.put(IClientConfigKey.Keys.FollowRedirects, value); return this; } public ClientOptions withConnectionPoolIdleEvictTimeMilliseconds(int value) { options.put(IClientConfigKey.Keys.ConnIdleEvictTimeMilliSeconds, value); return this; } public ClientOptions withLoadBalancerEnabled(boolean value) { options.put(IClientConfigKey.Keys.InitializeNFLoadBalancer, value); return this; } Map<IClientConfigKey<?>, Object> getOptions() { return options; } }
3,550
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/Ribbon.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.http.HttpResourceGroup.Builder; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; /** * A class that can be used to create {@link com.netflix.ribbon.http.HttpResourceGroup}, {@link com.netflix.ribbon.http.HttpResourceGroup.Builder}, * and dynamic proxy of service interfaces. It delegates to a default {@link com.netflix.ribbon.RibbonResourceFactory} to do the work. * For better configurability or in DI enabled application, it is recommended to use {@link com.netflix.ribbon.RibbonResourceFactory} directly. * */ public final class Ribbon { private static final RibbonResourceFactory factory = new DefaultResourceFactory(ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT, AnnotationProcessorsProvider.DEFAULT); private Ribbon() { } /** * Create the {@link com.netflix.ribbon.http.HttpResourceGroup.Builder} with a name, where further options can be set to * build the {@link com.netflix.ribbon.http.HttpResourceGroup}. * * @param name name of the resource group, as well as the transport client that will be created once * the HttpResourceGroup is built */ public static Builder createHttpResourceGroupBuilder(String name) { return factory.createHttpResourceGroupBuilder(name); } /** * Create the {@link com.netflix.ribbon.http.HttpResourceGroup} with a name. * * @param name name of the resource group, as well as the transport client that will be created once * the HttpResourceGroup is built */ public static HttpResourceGroup createHttpResourceGroup(String name) { return factory.createHttpResourceGroup(name); } /** * Create the {@link com.netflix.ribbon.http.HttpResourceGroup} with a name. * * @param name name of the resource group, as well as the transport client * @param options Options to override the client configuration created */ public static HttpResourceGroup createHttpResourceGroup(String name, ClientOptions options) { return factory.createHttpResourceGroup(name, options); } /** * Create an instance of remote service interface. * * @param contract interface class of the remote service * * @param <T> Type of the instance */ public static <T> T from(Class<T> contract) { return factory.from(contract); } }
3,551
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/ResponseValidator.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import io.reactivex.netty.protocol.http.client.HttpClientResponse; /** * * @author awang * * @param <T> Protocol specific response meta data, e.g., HttpClientResponse */ public interface ResponseValidator<T> { /** * @param response Protocol specific response object, e.g., {@link HttpClientResponse} * @throws UnsuccessfulResponseException throw if server is able to execute the request, but * returns an an unsuccessful response. * For example, HTTP response with 404 status code. This will be treated as a valid * response and will not trigger Hystrix fallback * @throws ServerError throw if the response indicates that there is an server error in executing the request. * For example, HTTP response with 500 status code. This will trigger Hystrix fallback. */ public void validate(T response) throws UnsuccessfulResponseException, ServerError; }
3,552
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/RibbonResponse.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.hystrix.HystrixInvokableInfo; /** * Response object from {@link RequestWithMetaData} that contains the content * and the meta data from execution. * * @author Allen Wang * * @param <T> Data type of the returned object */ public abstract class RibbonResponse<T> { public abstract T content(); public abstract HystrixInvokableInfo<?> getHystrixInfo(); }
3,553
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/RibbonResourceFactory.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.http.HttpResourceGroup.Builder; import com.netflix.ribbon.proxy.RibbonDynamicProxy; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; /** * Factory for creating an HttpResourceGroup or dynamic proxy from an annotated interface. * For DI either bind DefaultHttpResourceGroupFactory * or implement your own to customize or override HttpResourceGroup. * * @author elandau */ public abstract class RibbonResourceFactory { protected final ClientConfigFactory clientConfigFactory; protected final RibbonTransportFactory transportFactory; protected final AnnotationProcessorsProvider annotationProcessors; public static final RibbonResourceFactory DEFAULT = new DefaultResourceFactory(ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT, AnnotationProcessorsProvider.DEFAULT); public RibbonResourceFactory(ClientConfigFactory configFactory, RibbonTransportFactory transportFactory, AnnotationProcessorsProvider processors) { this.clientConfigFactory = configFactory; this.transportFactory = transportFactory; this.annotationProcessors = processors; } public Builder createHttpResourceGroupBuilder(String name) { Builder builder = HttpResourceGroup.Builder.newBuilder(name, clientConfigFactory, transportFactory); return builder; } public HttpResourceGroup createHttpResourceGroup(String name) { Builder builder = createHttpResourceGroupBuilder(name); return builder.build(); } public <T> T from(Class<T> classType) { return RibbonDynamicProxy.newInstance(classType, this, clientConfigFactory, transportFactory, annotationProcessors); } public HttpResourceGroup createHttpResourceGroup(String name, ClientOptions options) { Builder builder = createHttpResourceGroupBuilder(name); builder.withClientOptions(options); return builder.build(); } public final RibbonTransportFactory getTransportFactory() { return transportFactory; } public final ClientConfigFactory getClientConfigFactory() { return clientConfigFactory; } }
3,554
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/DefaultResourceFactory.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import javax.inject.Inject; public class DefaultResourceFactory extends RibbonResourceFactory { @Inject public DefaultResourceFactory(ClientConfigFactory clientConfigFactory, RibbonTransportFactory transportFactory, AnnotationProcessorsProvider annotationProcessorsProvider) { super(clientConfigFactory, transportFactory, annotationProcessorsProvider); } public DefaultResourceFactory(ClientConfigFactory clientConfigFactory, RibbonTransportFactory transportFactory) { super(clientConfigFactory, transportFactory, AnnotationProcessorsProvider.DEFAULT); } }
3,555
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/RibbonRequest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import java.util.concurrent.Future; import rx.Observable; /** * Request that provides blocking and non-blocking APIs to fetch the content. * * @author Allen Wang * */ public interface RibbonRequest<T> { /** * Blocking API that returns a single (or last element if there is a sequence of objects from the execution) element */ public T execute(); /** * Non blocking API that returns a {@link Future}, where its {@link Future#get()} method is blocking and returns a * single (or last element if there is a sequence of objects from the execution) element */ public Future<T> queue(); /** * Non blocking API that returns an {@link Observable} while the execution is started asynchronously. * Subscribing to the returned {@link Observable} is guaranteed to get the complete sequence from * the beginning, which might be replayed by the framework. Use this API for "fire and forget". */ public Observable<T> observe(); /** * Non blocking API that returns an Observable. The execution is not started until the returned Observable is subscribed to. */ public Observable<T> toObservable(); /** * Create a decorated {@link RequestWithMetaData} where you can call its similar blocking or non blocking * APIs to get {@link RibbonResponse}, which in turn contains returned object(s) and * some meta data from Hystrix execution. */ public RequestWithMetaData<T> withMetadata(); }
3,556
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/RequestTemplate.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; /** * @author awang * * @param <T> response entity type * @param <R> response meta data, e.g. HttpClientResponse */ public abstract class RequestTemplate<T, R> { public abstract RequestBuilder<T> requestBuilder(); public abstract String name(); public abstract RequestTemplate<T, R> copy(String name); public static abstract class RequestBuilder<T> { public abstract RequestBuilder<T> withRequestProperty(String key, Object value); public abstract RibbonRequest<T> build(); } }
3,557
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/UnsuccessfulResponseException.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; @SuppressWarnings("serial") public class UnsuccessfulResponseException extends Exception { public UnsuccessfulResponseException(String arg0, Throwable arg1) { super(arg0, arg1); } public UnsuccessfulResponseException(String arg0) { super(arg0); } public UnsuccessfulResponseException(Throwable arg0) { super(arg0); } }
3,558
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/ResourceGroup.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.ribbon.hystrix.FallbackHandler; public abstract class ResourceGroup<T extends RequestTemplate<?, ?>> { protected final String name; protected final IClientConfig clientConfig; protected final ClientConfigFactory configFactory; protected final RibbonTransportFactory transportFactory; public static abstract class GroupBuilder<T extends ResourceGroup> { public abstract T build(); public abstract GroupBuilder withClientOptions(ClientOptions options); } public static abstract class TemplateBuilder<S, R, T extends RequestTemplate<S, R>> { public abstract TemplateBuilder withFallbackProvider(FallbackHandler<S> fallbackProvider); public abstract TemplateBuilder withResponseValidator(ResponseValidator<R> transformer); /** * Calling this method will enable both Hystrix request cache and supplied external cache providers * on the supplied cache key. Caller can explicitly disable Hystrix request cache by calling * {@link #withHystrixProperties(com.netflix.hystrix.HystrixObservableCommand.Setter)} * * @param cacheKeyTemplate * @return */ public abstract TemplateBuilder withRequestCacheKey(String cacheKeyTemplate); public abstract TemplateBuilder withCacheProvider(String cacheKeyTemplate, CacheProvider<S> cacheProvider); public abstract TemplateBuilder withHystrixProperties(HystrixObservableCommand.Setter setter); public abstract T build(); } protected ResourceGroup(String name) { this(name, ClientOptions.create(), ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT); } protected ResourceGroup(String name, ClientOptions options, ClientConfigFactory configFactory, RibbonTransportFactory transportFactory) { this.name = name; clientConfig = configFactory.newConfig(); clientConfig.loadProperties(name); if (options != null) { for (IClientConfigKey key: options.getOptions().keySet()) { clientConfig.set(key, options.getOptions().get(key)); } } this.configFactory = configFactory; this.transportFactory = transportFactory; } protected final IClientConfig getClientConfig() { return clientConfig; } public final String name() { return name; } public abstract <S> TemplateBuilder<S, ?, ?> newTemplateBuilder(String name, Class<? extends S> classType); }
3,559
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/MethodTemplate.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.proxy.annotation.Content; import com.netflix.ribbon.proxy.annotation.ContentTransformerClass; import com.netflix.ribbon.proxy.annotation.TemplateName; import com.netflix.ribbon.proxy.annotation.Var; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.ContentTransformer; import rx.Observable; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import static java.lang.String.format; /** * Extracts information from Ribbon annotated method, to automatically populate the Ribbon request template. * A few validations are performed as well: * - a return type must be {@link com.netflix.ribbon.RibbonRequest} * - HTTP method must be always specified explicitly (there are no defaults) * - only one parameter with {@link com.netflix.ribbon.proxy.annotation.Content} annotation is allowed * * @author Tomasz Bak */ class MethodTemplate { private final Method method; private final String templateName; private final String[] paramNames; private final int[] valueIdxs; private final int contentArgPosition; private final Class<? extends ContentTransformer<?>> contentTansformerClass; private final Class<?> resultType; private final Class<?> genericContentType; MethodTemplate(Method method) { this.method = method; MethodAnnotationValues values = new MethodAnnotationValues(method); templateName = values.templateName; paramNames = values.paramNames; valueIdxs = values.valueIdxs; contentArgPosition = values.contentArgPosition; contentTansformerClass = values.contentTansformerClass; resultType = values.resultType; genericContentType = values.genericContentType; } public String getTemplateName() { return templateName; } public Method getMethod() { return method; } public String getParamName(int idx) { return paramNames[idx]; } public int getParamPosition(int idx) { return valueIdxs[idx]; } public int getParamSize() { return paramNames.length; } public int getContentArgPosition() { return contentArgPosition; } public Class<? extends ContentTransformer<?>> getContentTransformerClass() { return contentTansformerClass; } public Class<?> getResultType() { return resultType; } public Class<?> getGenericContentType() { return genericContentType; } public static <T> MethodTemplate[] from(Class<T> clientInterface) { List<MethodTemplate> list = new ArrayList<MethodTemplate>(clientInterface.getMethods().length); for (Method m : clientInterface.getMethods()) { list.add(new MethodTemplate(m)); } return list.toArray(new MethodTemplate[list.size()]); } static class CacheProviderEntry { private final String key; private final com.netflix.ribbon.CacheProvider cacheProvider; CacheProviderEntry(String key, com.netflix.ribbon.CacheProvider cacheProvider) { this.key = key; this.cacheProvider = cacheProvider; } public String getKey() { return key; } public com.netflix.ribbon.CacheProvider getCacheProvider() { return cacheProvider; } } private static class MethodAnnotationValues { private final Method method; private String templateName; private String[] paramNames; private int[] valueIdxs; private int contentArgPosition; private Class<? extends ContentTransformer<?>> contentTansformerClass; private Class<?> resultType; private Class<?> genericContentType; private MethodAnnotationValues(Method method) { this.method = method; extractTemplateName(); extractParamNamesWithIndexes(); extractContentArgPosition(); extractContentTransformerClass(); extractResultType(); } private void extractParamNamesWithIndexes() { List<String> nameList = new ArrayList<String>(); List<Integer> idxList = new ArrayList<Integer>(); Annotation[][] params = method.getParameterAnnotations(); for (int i = 0; i < params.length; i++) { for (Annotation a : params[i]) { if (a.annotationType().equals(Var.class)) { String name = ((Var) a).value(); nameList.add(name); idxList.add(i); } } } int size = nameList.size(); paramNames = new String[size]; valueIdxs = new int[size]; for (int i = 0; i < size; i++) { paramNames[i] = nameList.get(i); valueIdxs[i] = idxList.get(i); } } private void extractContentArgPosition() { Annotation[][] params = method.getParameterAnnotations(); int pos = -1; int count = 0; for (int i = 0; i < params.length; i++) { for (Annotation a : params[i]) { if (a.annotationType().equals(Content.class)) { pos = i; count++; } } } if (count > 1) { throw new ProxyAnnotationException(format("Method %s annotates multiple parameters as @Content - at most one is allowed ", methodName())); } contentArgPosition = pos; if (contentArgPosition >= 0) { Type type = method.getGenericParameterTypes()[contentArgPosition]; if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; if (pType.getActualTypeArguments() != null) { genericContentType = (Class<?>) pType.getActualTypeArguments()[0]; } } } } private void extractContentTransformerClass() { ContentTransformerClass annotation = method.getAnnotation(ContentTransformerClass.class); if (contentArgPosition == -1) { if (annotation != null) { throw new ProxyAnnotationException(format("ContentTransformClass defined on method %s with no @Content parameter", method.getName())); } return; } if (annotation == null) { Class<?> contentType = method.getParameterTypes()[contentArgPosition]; if (Observable.class.isAssignableFrom(contentType) && ByteBuf.class.isAssignableFrom(genericContentType) || ByteBuf.class.isAssignableFrom(contentType) || byte[].class.isAssignableFrom(contentType) || String.class.isAssignableFrom(contentType)) { return; } throw new ProxyAnnotationException(format("ContentTransformerClass annotation missing for content type %s in method %s", contentType.getName(), methodName())); } contentTansformerClass = annotation.value(); } private void extractTemplateName() { TemplateName annotation = method.getAnnotation(TemplateName.class); if (null != annotation) { templateName = annotation.value(); } else { templateName = method.getName(); } } private void extractResultType() { Class<?> returnClass = method.getReturnType(); if (!returnClass.isAssignableFrom(RibbonRequest.class)) { throw new ProxyAnnotationException(format("Method %s must return RibbonRequest<ByteBuf> type not %s", methodName(), returnClass.getSimpleName())); } ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType(); resultType = (Class<?>) returnType.getActualTypeArguments()[0]; if (!ByteBuf.class.isAssignableFrom(resultType)) { throw new ProxyAnnotationException(format("Method %s must return RibbonRequest<ByteBuf> type; instead %s type parameter found", methodName(), resultType.getSimpleName())); } } private String methodName() { return method.getDeclaringClass().getSimpleName() + '.' + method.getName(); } } }
3,560
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/ProxyHttpResourceGroupFactory.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.processor.AnnotationProcessor; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; /** * @author Tomasz Bak */ public class ProxyHttpResourceGroupFactory<T> { private final ClassTemplate<T> classTemplate; private final RibbonResourceFactory httpResourceGroupFactory; private final AnnotationProcessorsProvider processors; ProxyHttpResourceGroupFactory(ClassTemplate<T> classTemplate) { this(classTemplate, new DefaultResourceFactory(ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT, AnnotationProcessorsProvider.DEFAULT), AnnotationProcessorsProvider.DEFAULT); } ProxyHttpResourceGroupFactory(ClassTemplate<T> classTemplate, RibbonResourceFactory httpResourceGroupFactory, AnnotationProcessorsProvider processors) { this.classTemplate = classTemplate; this.httpResourceGroupFactory = httpResourceGroupFactory; this.processors = processors; } public HttpResourceGroup createResourceGroup() { Class<? extends HttpResourceGroup> resourceClass = classTemplate.getResourceGroupClass(); if (resourceClass != null) { return Utils.newInstance(resourceClass); } else { String name = classTemplate.getResourceGroupName(); if (name == null) { name = classTemplate.getClientInterface().getSimpleName(); } HttpResourceGroup.Builder builder = httpResourceGroupFactory.createHttpResourceGroupBuilder(name); for (AnnotationProcessor processor: processors.getProcessors()) { processor.process(name, builder, httpResourceGroupFactory, classTemplate.getClientInterface()); } return builder.build(); } } }
3,561
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/RibbonProxyException.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; /** * @author Tomasz Bak */ public class RibbonProxyException extends RuntimeException { private static final long serialVersionUID = -1; public RibbonProxyException(String message) { super(message); } public RibbonProxyException(String message, Throwable cause) { super(message, cause); } }
3,562
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/ProxyLifeCycle.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; public interface ProxyLifeCycle { boolean isShutDown(); void shutdown(); }
3,563
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/Utils.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import java.lang.reflect.Method; import static java.lang.String.*; /** * A collection of helper methods. * * @author Tomasz Bak */ public final class Utils { private Utils() { } public static <T> Method methodByName(Class<T> aClass, String name) { for (Method m : aClass.getMethods()) { if (m.getName().equals(name)) { return m; } } return null; } public static Object executeOnInstance(Object object, Method method, Object[] args) { Method targetMethod = methodByName(object.getClass(), method.getName()); if (targetMethod == null) { throw new IllegalArgumentException(format( "Signature of method %s is not compatible with the object %s", method.getName(), object.getClass().getSimpleName())); } try { return targetMethod.invoke(object, args); } catch (Exception ex) { throw new RibbonProxyException(format( "Failed to execute method %s on object %s", method.getName(), object.getClass().getSimpleName()), ex); } } public static <T> T newInstance(Class<T> aClass) { try { return aClass.newInstance(); } catch (Exception e) { throw new RibbonProxyException("Cannot instantiate object from class " + aClass, e); } } }
3,564
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/ClassTemplate.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.annotation.ResourceGroup; /** * @author Tomasz Bak */ class ClassTemplate<T> { private final Class<T> clientInterface; private final String resourceGroupName; private final Class<? extends HttpResourceGroup> resourceGroupClass; ClassTemplate(Class<T> clientInterface) { this.clientInterface = clientInterface; ResourceGroup annotation = clientInterface.getAnnotation(ResourceGroup.class); if (annotation != null) { String name = annotation.name().trim(); resourceGroupName = name.isEmpty() ? null : annotation.name(); if (annotation.resourceGroupClass().length == 0) { resourceGroupClass = null; } else if (annotation.resourceGroupClass().length == 1) { resourceGroupClass = annotation.resourceGroupClass()[0]; } else { throw new ProxyAnnotationException("only one resource group may be defined with @ResourceGroup annotation"); } verify(); } else { resourceGroupName = null; resourceGroupClass = null; } } public Class<T> getClientInterface() { return clientInterface; } public String getResourceGroupName() { return resourceGroupName; } public Class<? extends HttpResourceGroup> getResourceGroupClass() { return resourceGroupClass; } public static <T> ClassTemplate<T> from(Class<T> clientInterface) { return new ClassTemplate<T>(clientInterface); } private void verify() { if (resourceGroupName != null && resourceGroupClass != null) { throw new RibbonProxyException("Both resource group name and class defined with @ResourceGroup"); } } }
3,565
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/RibbonDynamicProxy.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.processor.CacheProviderAnnotationProcessor; import com.netflix.ribbon.proxy.processor.ClientPropertiesProcessor; import com.netflix.ribbon.proxy.processor.HttpAnnotationProcessor; import com.netflix.ribbon.proxy.processor.HystrixAnnotationProcessor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; /** * @author Tomasz Bak */ public class RibbonDynamicProxy<T> implements InvocationHandler { private final ProxyLifeCycle lifeCycle; private final Map<Method, MethodTemplateExecutor> templateExecutorMap; RibbonDynamicProxy(Class<T> clientInterface, HttpResourceGroup httpResourceGroup) { AnnotationProcessorsProvider processors = AnnotationProcessorsProvider.DEFAULT; registerAnnotationProcessors(processors); lifeCycle = new ProxyLifecycleImpl(httpResourceGroup); templateExecutorMap = MethodTemplateExecutor.from(httpResourceGroup, clientInterface, processors); } public RibbonDynamicProxy(Class<T> clientInterface, RibbonResourceFactory resourceGroupFactory, ClientConfigFactory configFactory, RibbonTransportFactory transportFactory, AnnotationProcessorsProvider processors) { registerAnnotationProcessors(processors); ClassTemplate<T> classTemplate = ClassTemplate.from(clientInterface); HttpResourceGroup httpResourceGroup = new ProxyHttpResourceGroupFactory<T>(classTemplate, resourceGroupFactory, processors).createResourceGroup(); templateExecutorMap = MethodTemplateExecutor.from(httpResourceGroup, clientInterface, processors); lifeCycle = new ProxyLifecycleImpl(httpResourceGroup); } static void registerAnnotationProcessors(AnnotationProcessorsProvider processors) { processors.register(new HttpAnnotationProcessor()); processors.register(new HystrixAnnotationProcessor()); processors.register(new CacheProviderAnnotationProcessor()); processors.register(new ClientPropertiesProcessor()); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { MethodTemplateExecutor template = templateExecutorMap.get(method); if (template != null) { return template.executeFromTemplate(args); } if (ProxyLifeCycle.class.isAssignableFrom(method.getDeclaringClass())) { return handleProxyLifeCycle(method, args); } // This must be one of the Object methods. Lets run it on the handler itself. return Utils.executeOnInstance(this, method, args); } private Object handleProxyLifeCycle(Method method, Object[] args) { try { return method.invoke(lifeCycle, args); } catch (Exception e) { throw new RibbonProxyException("ProxyLifeCycle call failure on method " + method.getName(), e); } } @Override public String toString() { return "RibbonDynamicProxy{...}"; } private static class ProxyLifecycleImpl implements ProxyLifeCycle { private final HttpResourceGroup httpResourceGroup; private volatile boolean shutdownFlag; ProxyLifecycleImpl(HttpResourceGroup httpResourceGroup) { this.httpResourceGroup = httpResourceGroup; } @Override public boolean isShutDown() { return shutdownFlag; } @Override public synchronized void shutdown() { if (!shutdownFlag) { httpResourceGroup.getClient().shutdown(); shutdownFlag = true; } } } public static <T> T newInstance(Class<T> clientInterface) { return newInstance(clientInterface, new DefaultResourceFactory(ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT, AnnotationProcessorsProvider.DEFAULT), ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT, AnnotationProcessorsProvider.DEFAULT); } @SuppressWarnings("unchecked") static <T> T newInstance(Class<T> clientInterface, HttpResourceGroup httpResourceGroup) { if (!clientInterface.isInterface()) { throw new IllegalArgumentException(clientInterface.getName() + " is a class not interface"); } if (httpResourceGroup == null) { throw new NullPointerException("HttpResourceGroup is null"); } return (T) Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class[]{clientInterface, ProxyLifeCycle.class}, new RibbonDynamicProxy<T>(clientInterface, httpResourceGroup) ); } @SuppressWarnings("unchecked") public static <T> T newInstance(Class<T> clientInterface, RibbonResourceFactory resourceGroupFactory, ClientConfigFactory configFactory, RibbonTransportFactory transportFactory, AnnotationProcessorsProvider processors) { if (!clientInterface.isInterface()) { throw new IllegalArgumentException(clientInterface.getName() + " is a class not interface"); } return (T) Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class[]{clientInterface, ProxyLifeCycle.class}, new RibbonDynamicProxy<T>(clientInterface, resourceGroupFactory, configFactory, transportFactory, processors) ); } public static <T> T newInstance(Class<T> clientInterface, RibbonResourceFactory resourceGroupFactory, ClientConfigFactory configFactory, RibbonTransportFactory transportFactory) { return newInstance(clientInterface, resourceGroupFactory, configFactory, transportFactory, AnnotationProcessorsProvider.DEFAULT); } }
3,566
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/ProxyAnnotationException.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; /** * @author Tomasz Bak */ public class ProxyAnnotationException extends RibbonProxyException { private static final long serialVersionUID = 1584867992816375583L; public ProxyAnnotationException(String message) { super(message); } }
3,567
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/MethodTemplateExecutor.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.http.HttpRequestBuilder; import com.netflix.ribbon.http.HttpRequestTemplate.Builder; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.processor.AnnotationProcessor; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.reactivex.netty.channel.ContentTransformer; import io.reactivex.netty.channel.StringTransformer; import rx.Observable; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * @author Tomasz Bak */ class MethodTemplateExecutor { private static final ContentTransformer<ByteBuf> BYTE_BUF_TRANSFORMER = new ContentTransformer<ByteBuf>() { @Override public ByteBuf call(ByteBuf toTransform, ByteBufAllocator byteBufAllocator) { return toTransform; } }; private static final ContentTransformer<byte[]> BYTE_ARRAY_TRANSFORMER = new ContentTransformer<byte[]>() { @Override public ByteBuf call(byte[] toTransform, ByteBufAllocator byteBufAllocator) { ByteBuf byteBuf = byteBufAllocator.buffer(toTransform.length); byteBuf.writeBytes(toTransform); return byteBuf; } }; private static final StringTransformer STRING_TRANSFORMER = new StringTransformer(); private final HttpResourceGroup httpResourceGroup; private final MethodTemplate methodTemplate; private final Builder<?> httpRequestTemplateBuilder; MethodTemplateExecutor(HttpResourceGroup httpResourceGroup, MethodTemplate methodTemplate, AnnotationProcessorsProvider annotations) { this.httpResourceGroup = httpResourceGroup; this.methodTemplate = methodTemplate; httpRequestTemplateBuilder = createHttpRequestTemplateBuilder(); for (AnnotationProcessor processor: annotations.getProcessors()) { processor.process(methodTemplate.getTemplateName(), httpRequestTemplateBuilder, methodTemplate.getMethod()); } } @SuppressWarnings("unchecked") public <O> RibbonRequest<O> executeFromTemplate(Object[] args) { HttpRequestBuilder<?> requestBuilder = httpRequestTemplateBuilder.build().requestBuilder(); withParameters(requestBuilder, args); withContent(requestBuilder, args); return (RibbonRequest<O>) requestBuilder.build(); } private Builder<?> createHttpRequestTemplateBuilder() { Builder<?> httpRequestTemplateBuilder = createBaseHttpRequestTemplate(httpResourceGroup); return httpRequestTemplateBuilder; } private Builder<?> createBaseHttpRequestTemplate(HttpResourceGroup httpResourceGroup) { Builder<?> httpRequestTemplate; if (ByteBuf.class.isAssignableFrom(methodTemplate.getResultType())) { httpRequestTemplate = httpResourceGroup.newTemplateBuilder(methodTemplate.getTemplateName()); } else { httpRequestTemplate = httpResourceGroup.newTemplateBuilder(methodTemplate.getTemplateName(), methodTemplate.getResultType()); } return httpRequestTemplate; } private void withParameters(HttpRequestBuilder<?> requestBuilder, Object[] args) { int length = methodTemplate.getParamSize(); for (int i = 0; i < length; i++) { String name = methodTemplate.getParamName(i); Object value = args[methodTemplate.getParamPosition(i)]; requestBuilder.withRequestProperty(name, value); } } @SuppressWarnings({"unchecked", "rawtypes"}) private void withContent(HttpRequestBuilder<?> requestBuilder, Object[] args) { if (methodTemplate.getContentArgPosition() < 0) { return; } Object contentValue = args[methodTemplate.getContentArgPosition()]; if (contentValue instanceof Observable) { if (ByteBuf.class.isAssignableFrom(methodTemplate.getGenericContentType())) { requestBuilder.withContent((Observable<ByteBuf>) contentValue); } else { ContentTransformer contentTransformer = Utils.newInstance(methodTemplate.getContentTransformerClass()); requestBuilder.withRawContentSource((Observable) contentValue, contentTransformer); } } else if (contentValue instanceof ByteBuf) { requestBuilder.withRawContentSource(Observable.just((ByteBuf) contentValue), BYTE_BUF_TRANSFORMER); } else if (contentValue instanceof byte[]) { requestBuilder.withRawContentSource(Observable.just((byte[]) contentValue), BYTE_ARRAY_TRANSFORMER); } else if (contentValue instanceof String) { requestBuilder.withRawContentSource(Observable.just((String) contentValue), STRING_TRANSFORMER); } else { ContentTransformer contentTransformer = Utils.newInstance(methodTemplate.getContentTransformerClass()); requestBuilder.withRawContentSource(Observable.just(contentValue), contentTransformer); } } public static Map<Method, MethodTemplateExecutor> from(HttpResourceGroup httpResourceGroup, Class<?> clientInterface, AnnotationProcessorsProvider annotations) { MethodTemplate[] methodTemplates = MethodTemplate.from(clientInterface); Map<Method, MethodTemplateExecutor> tgm = new HashMap<Method, MethodTemplateExecutor>(); for (MethodTemplate mt : methodTemplates) { tgm.put(mt.getMethod(), new MethodTemplateExecutor(httpResourceGroup, mt, annotations)); } return tgm; } }
3,568
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/processor/AnnotationProcessorsProvider.java
package com.netflix.ribbon.proxy.processor; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList; /** * @author Tomasz Bak */ public abstract class AnnotationProcessorsProvider { public static final AnnotationProcessorsProvider DEFAULT = new DefaultAnnotationProcessorsProvider(); private final List<AnnotationProcessor> processors = new CopyOnWriteArrayList<AnnotationProcessor>(); public static class DefaultAnnotationProcessorsProvider extends AnnotationProcessorsProvider { protected DefaultAnnotationProcessorsProvider() { ServiceLoader<AnnotationProcessor> loader = ServiceLoader.load(AnnotationProcessor.class); Iterator<AnnotationProcessor> iterator = loader.iterator(); while (iterator.hasNext()) { register(iterator.next()); } } } public void register(AnnotationProcessor processor) { processors.add(processor); } public List<AnnotationProcessor> getProcessors() { return processors; } }
3,569
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/processor/HystrixAnnotationProcessor.java
package com.netflix.ribbon.proxy.processor; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.http.HttpRequestTemplate.Builder; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.http.HttpResponseValidator; import com.netflix.ribbon.hystrix.FallbackHandler; import com.netflix.ribbon.proxy.ProxyAnnotationException; import com.netflix.ribbon.proxy.Utils; import com.netflix.ribbon.proxy.annotation.Hystrix; import java.lang.reflect.Method; import static java.lang.String.format; /** * @author Allen Wang */ public class HystrixAnnotationProcessor implements AnnotationProcessor<HttpResourceGroup.Builder, Builder> { @Override public void process(String templateName, Builder templateBuilder, Method method) { Hystrix annotation = method.getAnnotation(Hystrix.class); if (annotation == null) { return; } String cacheKey = annotation.cacheKey().trim(); if (!cacheKey.isEmpty()) { templateBuilder.withRequestCacheKey(cacheKey); } if (annotation.fallbackHandler().length == 1) { FallbackHandler<?> hystrixFallbackHandler = Utils.newInstance(annotation.fallbackHandler()[0]); templateBuilder.withFallbackProvider(hystrixFallbackHandler); } else if (annotation.fallbackHandler().length > 1) { throw new ProxyAnnotationException(format("more than one fallback handler defined for method %s", method.getName())); } if (annotation.validator().length == 1) { HttpResponseValidator hystrixResponseValidator = Utils.newInstance(annotation.validator()[0]); templateBuilder.withResponseValidator(hystrixResponseValidator); } else if (annotation.validator().length > 1) { throw new ProxyAnnotationException(format("more than one validator defined for method %s", method.getName())); } } @Override public void process(String groupName, HttpResourceGroup.Builder groupBuilder, RibbonResourceFactory resourceFactory, Class<?> interfaceClass) { } }
3,570
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/processor/CacheProviderAnnotationProcessor.java
package com.netflix.ribbon.proxy.processor; import com.netflix.ribbon.CacheProviderFactory; import com.netflix.ribbon.ResourceGroup.GroupBuilder; import com.netflix.ribbon.ResourceGroup.TemplateBuilder; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.proxy.Utils; import com.netflix.ribbon.proxy.annotation.CacheProvider; import java.lang.reflect.Method; /** * @author Allen Wang */ public class CacheProviderAnnotationProcessor implements AnnotationProcessor<GroupBuilder, TemplateBuilder> { @Override public void process(String templateName, TemplateBuilder templateBuilder, Method method) { CacheProvider annotation = method.getAnnotation(CacheProvider.class); if (annotation != null) { CacheProviderFactory<?> factory = Utils.newInstance(annotation.provider()); templateBuilder.withCacheProvider(annotation.key(), factory.createCacheProvider()); } } @Override public void process(String groupName, GroupBuilder groupBuilder, RibbonResourceFactory resourceFactory, Class<?> interfaceClass) { } }
3,571
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/processor/AnnotationProcessor.java
package com.netflix.ribbon.proxy.processor; import com.netflix.ribbon.ResourceGroup.GroupBuilder; import com.netflix.ribbon.ResourceGroup.TemplateBuilder; import com.netflix.ribbon.RibbonResourceFactory; import java.lang.reflect.Method; /** * @author Tomasz Bak */ public interface AnnotationProcessor<T extends GroupBuilder, S extends TemplateBuilder> { void process(String templateName, S templateBuilder, Method method); void process(String groupName, T groupBuilder, RibbonResourceFactory resourceFactory, Class<?> interfaceClass); }
3,572
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/processor/ClientPropertiesProcessor.java
package com.netflix.ribbon.proxy.processor; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.config.AggregatedConfiguration; import com.netflix.config.ConcurrentMapConfiguration; import com.netflix.config.ConfigurationManager; import com.netflix.ribbon.ClientOptions; import com.netflix.ribbon.ResourceGroup.GroupBuilder; import com.netflix.ribbon.ResourceGroup.TemplateBuilder; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.proxy.annotation.ClientProperties; import com.netflix.ribbon.proxy.annotation.ClientProperties.Property; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.Configuration; import java.lang.reflect.Method; import java.util.Map; /** * @author Allen Wang */ public class ClientPropertiesProcessor implements AnnotationProcessor<GroupBuilder, TemplateBuilder> { @Override public void process(String templateName, TemplateBuilder templateBuilder, Method method) { } @Override public void process(String groupName, GroupBuilder groupBuilder, RibbonResourceFactory resourceFactory, Class<?> interfaceClass) { ClientProperties properties = interfaceClass.getAnnotation(ClientProperties.class); if (properties != null) { IClientConfig config = resourceFactory.getClientConfigFactory().newConfig(); for (Property prop : properties.properties()) { String name = prop.name(); config.set(CommonClientConfigKey.valueOf(name), prop.value()); } ClientOptions options = ClientOptions.from(config); groupBuilder.withClientOptions(options); if (properties.exportToArchaius()) { exportPropertiesToArchaius(groupName, config, interfaceClass.getName()); } } } private void exportPropertiesToArchaius(String groupName, IClientConfig config, String configName) { Map<String, Object> map = config.getProperties(); Configuration configuration = ConfigurationManager.getConfigInstance(); if (configuration instanceof AggregatedConfiguration) { AggregatedConfiguration ac = (AggregatedConfiguration) configuration; configuration = ac.getConfiguration(configName); if (configuration == null) { configuration = new ConcurrentMapConfiguration(); ac.addConfiguration((AbstractConfiguration) configuration, configName); } } for (Map.Entry<String, Object> entry : map.entrySet()) { configuration.setProperty(groupName + "." + config.getNameSpace() + "." + entry.getKey(), entry.getValue()); } } }
3,573
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/processor/HttpAnnotationProcessor.java
package com.netflix.ribbon.proxy.processor; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.http.HttpRequestTemplate.Builder; import com.netflix.ribbon.http.HttpResourceGroup; import com.netflix.ribbon.proxy.ProxyAnnotationException; import com.netflix.ribbon.proxy.annotation.Http; import com.netflix.ribbon.proxy.annotation.Http.Header; import com.netflix.ribbon.proxy.annotation.Http.HttpMethod; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static java.lang.String.format; /** * Http annotation */ public class HttpAnnotationProcessor implements AnnotationProcessor<HttpResourceGroup.Builder, Builder> { @Override public void process(String templateName, Builder templateBuilder, Method method) { Http annotation = method.getAnnotation(Http.class); if (null == annotation) { throw new ProxyAnnotationException(format("Method %s misses @Http annotation", method.getName())); } final HttpMethod httpMethod = annotation.method(); final String uriTemplate = annotation.uri(); final Map<String, List<String>> headers = annotation.headers().length == 0 ? null : new HashMap<String, List<String>>(); for (Header h : annotation.headers()) { if (!headers.containsKey(h.name())) { ArrayList<String> values = new ArrayList<String>(); values.add(h.value()); headers.put(h.name(), values); } else { headers.get(h.name()).add(h.value()); } } templateBuilder.withMethod(httpMethod.name()); // uri if (uriTemplate != null) { templateBuilder.withUriTemplate(uriTemplate); } // headers if (headers != null) { for (Entry<String, List<String>> header : headers.entrySet()) { String key = header.getKey(); for (String value : header.getValue()) { templateBuilder.withHeader(key, value); } } } } @Override public void process(String groupName, HttpResourceGroup.Builder groupBuilder, RibbonResourceFactory resourceFactory, Class<?> interfaceClass) { } }
3,574
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/TemplateName.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TemplateName { String value(); }
3,575
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/ClientProperties.java
package com.netflix.ribbon.proxy.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Allen Wang */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ClientProperties { @interface Property { String name(); String value(); } Property[] properties() default {}; boolean exportToArchaius() default false; }
3,576
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/CacheProvider.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import com.netflix.ribbon.CacheProviderFactory; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface CacheProvider { String key(); Class<? extends CacheProviderFactory<?>> provider(); }
3,577
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/Var.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Var { String value(); }
3,578
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/Http.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Tomasz Bak */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Http { enum HttpMethod { DELETE, GET, POST, PATCH, PUT } HttpMethod method(); String uri() default ""; Header[] headers() default {}; @interface Header { String name(); String value(); } }
3,579
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/Hystrix.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import com.netflix.ribbon.http.HttpResponseValidator; import com.netflix.ribbon.hystrix.FallbackHandler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Hystrix { String cacheKey() default ""; Class<? extends FallbackHandler<?>>[] fallbackHandler() default {}; Class<? extends HttpResponseValidator>[] validator() default {}; }
3,580
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/ContentTransformerClass.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import io.reactivex.netty.channel.ContentTransformer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ContentTransformerClass { Class<? extends ContentTransformer<?>> value(); }
3,581
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/ResourceGroup.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import com.netflix.ribbon.http.HttpResourceGroup; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ResourceGroup { String name() default ""; Class<? extends HttpResourceGroup>[] resourceGroupClass() default {}; }
3,582
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/proxy/annotation/Content.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.proxy.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Content { }
3,583
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/template/ParsedTemplate.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.template; import java.util.List; public class ParsedTemplate { private List<Object> parsed; private String template; public ParsedTemplate(List<Object> parsed, String template) { super(); this.parsed = parsed; this.template = template; } public final List<Object> getParsed() { return parsed; } public final String getTemplate() { return template; } public static ParsedTemplate create(String template) { List<Object> parsed = TemplateParser.parseTemplate(template); return new ParsedTemplate(parsed, template); } }
3,584
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/template/TemplateParser.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.template; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.common.collect.Maps; /** * Created by mcohen on 5/1/14. */ public class TemplateParser { public static List<Object> parseTemplate(String template) { List<Object> templateParts = new ArrayList<Object>(); if (template == null) { return templateParts; } StringBuilder val = new StringBuilder(); String key; for (char c : template.toCharArray()) { switch (c) { case '{': key = val.toString(); val = new StringBuilder(); templateParts.add(key); break; case '}': key = val.toString(); val = new StringBuilder(); if (key.charAt(0) == ';') { templateParts.add(new MatrixVar(key.substring(1))); } else { templateParts.add(new PathVar(key)); } break; default: val.append(c); } } key = val.toString(); if (!key.isEmpty()) { templateParts.add(key); } return templateParts; } public static String toData(Map<String, Object> variables, ParsedTemplate parsedTemplate) throws TemplateParsingException { return toData(variables, parsedTemplate.getTemplate(), parsedTemplate.getParsed()); } public static String toData(Map<String, Object> variables, String template, List<Object> parsedList) throws TemplateParsingException { int params = variables.size(); // skip expansion if there's no valid variables set. ex. {a} is the // first valid if (variables.isEmpty() && template.indexOf('{') == 0) { return template; } StringBuilder builder = new StringBuilder(); for (Object part : parsedList) { if (part instanceof TemplateVar) { Object var = variables.get(part.toString()); if (part instanceof MatrixVar) { if (var != null) { builder.append(';').append(part.toString()).append('=').append(var); params--; } } else if (part instanceof PathVar) { if (var == null) { throw new TemplateParsingException(String.format("template variable %s was not supplied for template %s", part.toString(), template)); } else { builder.append(var); params--; } } else { throw new TemplateParsingException(String.format("template variable type %s is not supplied for template template %s", part.getClass().getCanonicalName(), template)); } } else { builder.append(part.toString()); } } return builder.toString(); } public static void main(String[] args) throws TemplateParsingException { String template = "/abc/{id}?name={name}"; Map<String, Object> vars = Maps.newHashMap(); vars.put("id", "5"); vars.put("name", "netflix"); List<Object> list = parseTemplate(template); System.out.println(toData(vars, template, list)); } }
3,585
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/template/TemplateVar.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.template; /** * TemplateVar is a base type for use in the template parser &amp; URI Fragment builder to isolate template values from * static values */ class TemplateVar { private final String val; TemplateVar(String val) { this.val = val; } public String toString() { return val; } }
3,586
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/template/MatrixVar.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.template; /** * MatrixVar is used to represent a matrix parameter in a URI template. eg var in /template{;var} */ class MatrixVar extends TemplateVar { MatrixVar(String val) { super(val); } }
3,587
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/template/PathVar.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.template; /** * PathVar is used to represent a variable path portion of a URI template. eg {var} in /template/{var} */ class PathVar extends TemplateVar { PathVar(String val) { super(val); } }
3,588
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/template/TemplateParsingException.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.template; public class TemplateParsingException extends Exception { /** * */ private static final long serialVersionUID = 1910187667077051723L; public TemplateParsingException(String arg0, Throwable arg1) { super(arg0, arg1); } public TemplateParsingException(String arg0) { super(arg0); } }
3,589
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpResponseValidator.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import com.netflix.ribbon.ResponseValidator; public interface HttpResponseValidator extends ResponseValidator<HttpClientResponse<ByteBuf>> { }
3,590
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpRequestTemplate.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import com.netflix.ribbon.transport.netty.LoadBalancingRxClient; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.hystrix.HystrixObservableCommand.Setter; import com.netflix.ribbon.CacheProvider; import com.netflix.ribbon.RequestTemplate; import com.netflix.ribbon.ResourceGroup.TemplateBuilder; import com.netflix.ribbon.ResponseValidator; import com.netflix.ribbon.hystrix.FallbackHandler; import com.netflix.ribbon.template.ParsedTemplate; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import java.util.HashMap; import java.util.Map; /** * Provides API to construct a request template for HTTP resource. * <p> * <b>Note:</b> This class is not thread safe. It is advised that the template is created and * constructed in same thread at initialization of the application. Users can call {@link #requestBuilder()} * later on which returns a {@link RequestBuilder} which is thread safe. * * @author Allen Wang * * @param <T> Type for the return Object of the Http resource */ public class HttpRequestTemplate<T> extends RequestTemplate<T, HttpClientResponse<ByteBuf>> { public static final String CACHE_HYSTRIX_COMMAND_SUFFIX = "_cache"; public static final int DEFAULT_CACHE_TIMEOUT = 20; public static class Builder<T> extends TemplateBuilder<T, HttpClientResponse<ByteBuf>, HttpRequestTemplate<T>> { private String name; private HttpResourceGroup resourceGroup; private Class<? extends T> classType; private FallbackHandler<T> fallbackHandler; private HttpMethod method; private ParsedTemplate parsedUriTemplate; private ParsedTemplate cacheKeyTemplate; private CacheProviderWithKeyTemplate<T> cacheProvider; private HttpHeaders headers; private Setter setter; private Map<String, ParsedTemplate> parsedTemplates; private ResponseValidator<HttpClientResponse<ByteBuf>> validator; private Builder(String name, HttpResourceGroup resourceGroup, Class<? extends T> classType) { this.name = name; this.resourceGroup = resourceGroup; this.classType = classType; headers = new DefaultHttpHeaders(); headers.add(resourceGroup.getHeaders()); parsedTemplates = new HashMap<String, ParsedTemplate>(); } private ParsedTemplate createParsedTemplate(String template) { ParsedTemplate parsedTemplate = parsedTemplates.get(template); if (parsedTemplate == null) { parsedTemplate = ParsedTemplate.create(template); parsedTemplates.put(template, parsedTemplate); } return parsedTemplate; } public static <T> Builder<T> newBuilder(String templateName, HttpResourceGroup group, Class<? extends T> classType) { return new Builder(templateName, group, classType); } @Override public Builder<T> withFallbackProvider(FallbackHandler<T> fallbackHandler) { this.fallbackHandler = fallbackHandler; return this; } @Override public Builder<T> withResponseValidator(ResponseValidator<HttpClientResponse<ByteBuf>> validator) { this.validator = validator; return this; } public Builder<T> withMethod(String method) { this.method = HttpMethod.valueOf(method); return this; } public Builder<T> withUriTemplate(String uriTemplate) { this.parsedUriTemplate = createParsedTemplate(uriTemplate); return this; } @Override public Builder<T> withRequestCacheKey(String cacheKeyTemplate) { this.cacheKeyTemplate = createParsedTemplate(cacheKeyTemplate); return this; } @Override public Builder<T> withCacheProvider(String keyTemplate, CacheProvider<T> cacheProvider) { ParsedTemplate template = createParsedTemplate(keyTemplate); this.cacheProvider = new CacheProviderWithKeyTemplate<T>(template, cacheProvider); return this; } public Builder<T> withHeader(String name, String value) { headers.add(name, value); return this; } @Override public Builder<T> withHystrixProperties( Setter propertiesSetter) { this.setter = propertiesSetter; return this; } public HttpRequestTemplate<T> build() { return new HttpRequestTemplate<T>(name, resourceGroup, classType, setter, method, headers, parsedUriTemplate, fallbackHandler, validator, cacheProvider, cacheKeyTemplate); } } private final HttpClient<ByteBuf, ByteBuf> client; private final int maxResponseTime; private final HystrixObservableCommand.Setter setter; private final HystrixObservableCommand.Setter cacheSetter; private final FallbackHandler<T> fallbackHandler; private final ParsedTemplate parsedUriTemplate; private final ResponseValidator<HttpClientResponse<ByteBuf>> validator; private final HttpMethod method; private final String name; private final CacheProviderWithKeyTemplate<T> cacheProvider; private final ParsedTemplate hystrixCacheKeyTemplate; private final Class<? extends T> classType; private final int concurrentRequestLimit; private final HttpHeaders headers; private final HttpResourceGroup group; public static class CacheProviderWithKeyTemplate<T> { private final ParsedTemplate keyTemplate; private final CacheProvider<T> provider; public CacheProviderWithKeyTemplate(ParsedTemplate keyTemplate, CacheProvider<T> provider) { this.keyTemplate = keyTemplate; this.provider = provider; } public final ParsedTemplate getKeyTemplate() { return keyTemplate; } public final CacheProvider<T> getProvider() { return provider; } } protected HttpRequestTemplate(String name, HttpResourceGroup group, Class<? extends T> classType, HystrixObservableCommand.Setter setter, HttpMethod method, HttpHeaders headers, ParsedTemplate uriTemplate, FallbackHandler<T> fallbackHandler, ResponseValidator<HttpClientResponse<ByteBuf>> validator, CacheProviderWithKeyTemplate<T> cacheProvider, ParsedTemplate hystrixCacheKeyTemplate) { this.group = group; this.name = name; this.classType = classType; this.method = method; this.parsedUriTemplate = uriTemplate; this.fallbackHandler = fallbackHandler; this.validator = validator; this.cacheProvider = cacheProvider; this.hystrixCacheKeyTemplate = hystrixCacheKeyTemplate; this.client = group.getClient(); this.headers = headers; if (client instanceof LoadBalancingRxClient) { LoadBalancingRxClient ribbonClient = (LoadBalancingRxClient) client; maxResponseTime = ribbonClient.getResponseTimeOut(); concurrentRequestLimit = ribbonClient.getMaxConcurrentRequests(); } else { maxResponseTime = -1; concurrentRequestLimit = -1; } String cacheName = name + CACHE_HYSTRIX_COMMAND_SUFFIX; cacheSetter = HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(cacheName)) .andCommandKey(HystrixCommandKey.Factory.asKey(cacheName)); HystrixCommandProperties.Setter cacheCommandProps = HystrixCommandProperties.Setter(); cacheCommandProps.withExecutionIsolationThreadTimeoutInMilliseconds(DEFAULT_CACHE_TIMEOUT); cacheSetter.andCommandPropertiesDefaults(cacheCommandProps); if (setter != null) { this.setter = setter; } else { this.setter = HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(client.name())) .andCommandKey(HystrixCommandKey.Factory.asKey(name())); HystrixCommandProperties.Setter commandProps = HystrixCommandProperties.Setter(); if (maxResponseTime > 0) { commandProps.withExecutionIsolationThreadTimeoutInMilliseconds(maxResponseTime); } if (concurrentRequestLimit > 0) { commandProps.withExecutionIsolationSemaphoreMaxConcurrentRequests(concurrentRequestLimit); } this.setter.andCommandPropertiesDefaults(commandProps); } } @Override public HttpRequestBuilder<T> requestBuilder() { return new HttpRequestBuilder<T>(this); } protected final ParsedTemplate hystrixCacheKeyTemplate() { return hystrixCacheKeyTemplate; } protected final CacheProviderWithKeyTemplate<T> cacheProvider() { return cacheProvider; } protected final ResponseValidator<HttpClientResponse<ByteBuf>> responseValidator() { return validator; } protected final FallbackHandler<T> fallbackHandler() { return fallbackHandler; } protected final ParsedTemplate uriTemplate() { return parsedUriTemplate; } protected final HttpMethod method() { return method; } protected final Class<? extends T> getClassType() { return this.classType; } protected final HttpHeaders getHeaders() { return this.headers; } @Override public String name() { return name; } @Override public HttpRequestTemplate<T> copy(String name) { HttpRequestTemplate<T> newTemplate = new HttpRequestTemplate<T>(name, group, classType, setter, method, headers, parsedUriTemplate, fallbackHandler, validator, cacheProvider, hystrixCacheKeyTemplate); return newTemplate; } protected final Setter hystrixProperties() { return this.setter; } protected final Setter cacheHystrixProperties() { return cacheSetter; } protected final HttpClient<ByteBuf, ByteBuf> getClient() { return this.client; } }
3,591
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpResourceGroup.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.ClientOptions; import com.netflix.ribbon.ResourceGroup; import com.netflix.ribbon.RibbonTransportFactory; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpHeaders; import io.reactivex.netty.protocol.http.client.HttpClient; public class HttpResourceGroup extends ResourceGroup<HttpRequestTemplate<?>> { private final HttpClient<ByteBuf, ByteBuf> client; private final HttpHeaders headers; public static class Builder extends GroupBuilder<HttpResourceGroup> { private ClientOptions clientOptions; private HttpHeaders httpHeaders = new DefaultHttpHeaders(); private ClientConfigFactory clientConfigFactory; private RibbonTransportFactory transportFactory; private String name; private Builder(String name, ClientConfigFactory configFactory, RibbonTransportFactory transportFactory) { this.name = name; this.clientConfigFactory = configFactory; this.transportFactory = transportFactory; } public static Builder newBuilder(String groupName, ClientConfigFactory configFactory, RibbonTransportFactory transportFactory) { return new Builder(groupName, configFactory, transportFactory); } @Override public Builder withClientOptions(ClientOptions options) { this.clientOptions = options; return this; } public Builder withHeader(String name, String value) { httpHeaders.add(name, value); return this; } @Override public HttpResourceGroup build() { return new HttpResourceGroup(name, clientOptions, clientConfigFactory, transportFactory, httpHeaders); } } protected HttpResourceGroup(String groupName) { super(groupName, ClientOptions.create(), ClientConfigFactory.DEFAULT, RibbonTransportFactory.DEFAULT); client = transportFactory.newHttpClient(getClientConfig()); headers = HttpHeaders.EMPTY_HEADERS; } protected HttpResourceGroup(String groupName, ClientOptions options, ClientConfigFactory configFactory, RibbonTransportFactory transportFactory, HttpHeaders headers) { super(groupName, options, configFactory, transportFactory); client = transportFactory.newHttpClient(getClientConfig()); this.headers = headers; } @Override public <T> HttpRequestTemplate.Builder newTemplateBuilder(String name, Class<? extends T> classType) { return HttpRequestTemplate.Builder.newBuilder(name, this, classType); } public HttpRequestTemplate.Builder<ByteBuf> newTemplateBuilder(String name) { return HttpRequestTemplate.Builder.newBuilder(name, this, ByteBuf.class); } public final HttpHeaders getHeaders() { return headers; } public final HttpClient<ByteBuf, ByteBuf> getClient() { return client; } }
3,592
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpResourceObservableCommand.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.ribbon.ResponseValidator; import com.netflix.ribbon.ServerError; import com.netflix.ribbon.UnsuccessfulResponseException; import com.netflix.ribbon.hystrix.FallbackHandler; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import rx.Observable; import rx.functions.Func1; import java.util.Map; public class HttpResourceObservableCommand<T> extends HystrixObservableCommand<T> { private final HttpClient<ByteBuf, ByteBuf> httpClient; private final HttpClientRequest<ByteBuf> httpRequest; private final String hystrixCacheKey; private final Map<String, Object> requestProperties; private final FallbackHandler<T> fallbackHandler; private final Class<? extends T> classType; private final ResponseValidator<HttpClientResponse<ByteBuf>> validator; public HttpResourceObservableCommand(HttpClient<ByteBuf, ByteBuf> httpClient, HttpClientRequest<ByteBuf> httpRequest, String hystrixCacheKey, Map<String, Object> requestProperties, FallbackHandler<T> fallbackHandler, ResponseValidator<HttpClientResponse<ByteBuf>> validator, Class<? extends T> classType, HystrixObservableCommand.Setter setter) { super(setter); this.httpClient = httpClient; this.fallbackHandler = fallbackHandler; this.validator = validator; this.httpRequest = httpRequest; this.hystrixCacheKey = hystrixCacheKey; this.classType = classType; this.requestProperties = requestProperties; } @Override protected String getCacheKey() { if (hystrixCacheKey == null) { return super.getCacheKey(); } else { return hystrixCacheKey; } } @Override protected Observable<T> resumeWithFallback() { if (fallbackHandler == null) { return super.resumeWithFallback(); } else { return fallbackHandler.getFallback(this, this.requestProperties); } } @Override protected Observable<T> construct() { Observable<HttpClientResponse<ByteBuf>> httpResponseObservable = httpClient.submit(httpRequest); if (validator != null) { httpResponseObservable = httpResponseObservable.map(new Func1<HttpClientResponse<ByteBuf>, HttpClientResponse<ByteBuf>>() { @Override public HttpClientResponse<ByteBuf> call(HttpClientResponse<ByteBuf> t1) { try { validator.validate(t1); } catch (UnsuccessfulResponseException e) { throw new HystrixBadRequestException("Unsuccessful response", e); } catch (ServerError e) { throw new RuntimeException(e); } return t1; } }); } return httpResponseObservable.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<T>>() { @Override public Observable<T> call(HttpClientResponse<ByteBuf> t1) { return t1.getContent().map(new Func1<ByteBuf, T>() { @Override public T call(ByteBuf t1) { return classType.cast(t1); } }); } }); } }
3,593
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpMetaRequest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.ribbon.RequestWithMetaData; import com.netflix.ribbon.RibbonResponse; import com.netflix.ribbon.hystrix.HystrixObservableCommandChain; import com.netflix.ribbon.hystrix.ResultCommandPair; import io.netty.buffer.ByteBuf; import rx.Notification; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func1; import rx.subjects.ReplaySubject; import rx.subjects.Subject; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; class HttpMetaRequest<T> implements RequestWithMetaData<T> { private static class ResponseWithSubject<T> extends RibbonResponse<Observable<T>> { Subject<T, T> subject; HystrixInvokableInfo<?> info; public ResponseWithSubject(Subject<T, T> subject, HystrixInvokableInfo<?> info) { this.subject = subject; this.info = info; } @Override public Observable<T> content() { return subject; } @Override public HystrixInvokableInfo<?> getHystrixInfo() { return info; } } private final HttpRequest<T> request; HttpMetaRequest(HttpRequest<T> request) { this.request = request; } @Override public Observable<RibbonResponse<Observable<T>>> toObservable() { HystrixObservableCommandChain<T> commandChain = request.createHystrixCommandChain(); return convertToRibbonResponse(commandChain, commandChain.toResultCommandPairObservable()); } @Override public Observable<RibbonResponse<Observable<T>>> observe() { HystrixObservableCommandChain<T> commandChain = request.createHystrixCommandChain(); Observable<ResultCommandPair<T>> notificationObservable = commandChain.toResultCommandPairObservable(); notificationObservable = retainBufferIfNeeded(notificationObservable); ReplaySubject<ResultCommandPair<T>> subject = ReplaySubject.create(); notificationObservable.subscribe(subject); return convertToRibbonResponse(commandChain, subject); } @Override public Future<RibbonResponse<T>> queue() { Observable<ResultCommandPair<T>> resultObservable = request.createHystrixCommandChain().toResultCommandPairObservable(); resultObservable = retainBufferIfNeeded(resultObservable); final Future<ResultCommandPair<T>> f = resultObservable.toBlocking().toFuture(); return new Future<RibbonResponse<T>>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return f.cancel(mayInterruptIfRunning); } @Override public RibbonResponse<T> get() throws InterruptedException, ExecutionException { final ResultCommandPair<T> pair = f.get(); return new HttpMetaResponse<T>(pair.getResult(), pair.getCommand()); } @Override public RibbonResponse<T> get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { final ResultCommandPair<T> pair = f.get(timeout, timeUnit); return new HttpMetaResponse<T>(pair.getResult(), pair.getCommand()); } @Override public boolean isCancelled() { return f.isCancelled(); } @Override public boolean isDone() { return f.isDone(); } }; } @Override public RibbonResponse<T> execute() { RibbonResponse<Observable<T>> response = observe().toBlocking().last(); return new HttpMetaResponse<T>(response.content().toBlocking().last(), response.getHystrixInfo()); } private Observable<ResultCommandPair<T>> retainBufferIfNeeded(Observable<ResultCommandPair<T>> resultObservable) { if (request.isByteBufResponse()) { resultObservable = resultObservable.map(new Func1<ResultCommandPair<T>, ResultCommandPair<T>>() { @Override public ResultCommandPair<T> call(ResultCommandPair<T> pair) { ((ByteBuf) pair.getResult()).retain(); return pair; } }); } return resultObservable; } private Observable<RibbonResponse<Observable<T>>> convertToRibbonResponse( final HystrixObservableCommandChain<T> commandChain, final Observable<ResultCommandPair<T>> hystrixNotificationObservable) { return Observable.create(new OnSubscribe<RibbonResponse<Observable<T>>>() { @Override public void call( final Subscriber<? super RibbonResponse<Observable<T>>> t1) { final Subject<T, T> subject = ReplaySubject.create(); hystrixNotificationObservable.materialize().subscribe(new Action1<Notification<ResultCommandPair<T>>>() { AtomicBoolean first = new AtomicBoolean(true); @Override public void call(Notification<ResultCommandPair<T>> notification) { if (first.compareAndSet(true, false)) { HystrixObservableCommand<T> command = notification.isOnError() ? commandChain.getLastCommand() : notification.getValue().getCommand(); t1.onNext(new ResponseWithSubject<T>(subject, command)); t1.onCompleted(); } if (notification.isOnNext()) { subject.onNext(notification.getValue().getResult()); } else if (notification.isOnCompleted()) { subject.onCompleted(); } else { // onError subject.onError(notification.getThrowable()); } } }); } }); } }
3,594
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpMetaResponse.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.ribbon.RibbonResponse; class HttpMetaResponse<O> extends RibbonResponse<O> { private O content; private HystrixInvokableInfo<?> hystrixInfo; public HttpMetaResponse(O content, HystrixInvokableInfo<?> hystrixInfo) { this.content = content; this.hystrixInfo = hystrixInfo; } @Override public O content() { return content; } @Override public HystrixInvokableInfo<?> getHystrixInfo() { return hystrixInfo; } }
3,595
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpRequest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.ribbon.CacheProvider; import com.netflix.ribbon.RequestWithMetaData; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.hystrix.CacheObservableCommand; import com.netflix.ribbon.hystrix.HystrixObservableCommandChain; import com.netflix.ribbon.template.TemplateParser; import com.netflix.ribbon.template.TemplateParsingException; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import rx.Observable; import rx.functions.Func1; import rx.subjects.ReplaySubject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; class HttpRequest<T> implements RibbonRequest<T> { static class CacheProviderWithKey<T> { CacheProvider<T> cacheProvider; String key; public CacheProviderWithKey(CacheProvider<T> cacheProvider, String key) { this.cacheProvider = cacheProvider; this.key = key; } public final CacheProvider<T> getCacheProvider() { return cacheProvider; } public final String getKey() { return key; } } private static final Func1<ByteBuf, ByteBuf> refCountIncrementer = new Func1<ByteBuf, ByteBuf>() { @Override public ByteBuf call(ByteBuf t1) { t1.retain(); return t1; } }; private final HttpClientRequest<ByteBuf> httpRequest; private final String hystrixCacheKey; private final String cacheHystrixCacheKey; private final CacheProviderWithKey<T> cacheProvider; private final Map<String, Object> requestProperties; private final HttpClient<ByteBuf, ByteBuf> client; /* package private for HttpMetaRequest */ final HttpRequestTemplate<T> template; HttpRequest(HttpRequestBuilder<T> requestBuilder) throws TemplateParsingException { client = requestBuilder.template().getClient(); httpRequest = requestBuilder.createClientRequest(); hystrixCacheKey = requestBuilder.hystrixCacheKey(); cacheHystrixCacheKey = hystrixCacheKey == null ? null : hystrixCacheKey + HttpRequestTemplate.CACHE_HYSTRIX_COMMAND_SUFFIX; requestProperties = new HashMap<String, Object>(requestBuilder.requestProperties()); if (requestBuilder.cacheProvider() != null) { CacheProvider<T> provider = requestBuilder.cacheProvider().getProvider(); String key = TemplateParser.toData(this.requestProperties, requestBuilder.cacheProvider().getKeyTemplate()); cacheProvider = new CacheProviderWithKey<T>(provider, key); } else { cacheProvider = null; } template = requestBuilder.template(); if (!ByteBuf.class.isAssignableFrom(template.getClassType())) { throw new IllegalArgumentException("Return type other than ByteBuf is not currently supported as serialization functionality is still work in progress"); } } HystrixObservableCommandChain<T> createHystrixCommandChain() { List<HystrixObservableCommand<T>> commands = new ArrayList<HystrixObservableCommand<T>>(2); if (cacheProvider != null) { commands.add(new CacheObservableCommand<T>(cacheProvider.getCacheProvider(), cacheProvider.getKey(), cacheHystrixCacheKey, requestProperties, template.cacheHystrixProperties())); } commands.add(new HttpResourceObservableCommand<T>(client, httpRequest, hystrixCacheKey, requestProperties, template.fallbackHandler(), template.responseValidator(), template.getClassType(), template.hystrixProperties())); return new HystrixObservableCommandChain<T>(commands); } @Override public Observable<T> toObservable() { return createHystrixCommandChain().toObservable(); } @Override public T execute() { return getObservable().toBlocking().last(); } @Override public Future<T> queue() { return getObservable().toBlocking().toFuture(); } @Override public Observable<T> observe() { ReplaySubject<T> subject = ReplaySubject.create(); getObservable().subscribe(subject); return subject; } @Override public RequestWithMetaData<T> withMetadata() { return new HttpMetaRequest<T>(this); } boolean isByteBufResponse() { return ByteBuf.class.isAssignableFrom(template.getClassType()); } Observable<T> getObservable() { if (isByteBufResponse()) { return ((Observable) toObservable()).map(refCountIncrementer); } else { return toObservable(); } } }
3,596
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/http/HttpRequestBuilder.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.http; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.reactivex.netty.channel.ContentTransformer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import rx.Observable; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.ribbon.RequestTemplate.RequestBuilder; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.http.HttpRequestTemplate.CacheProviderWithKeyTemplate; import com.netflix.ribbon.template.ParsedTemplate; import com.netflix.ribbon.template.TemplateParser; import com.netflix.ribbon.template.TemplateParsingException; public class HttpRequestBuilder<T> extends RequestBuilder<T> { private final HttpRequestTemplate<T> requestTemplate; private final Map<String, Object> vars; private final ParsedTemplate parsedUriTemplate; private Observable rawContentSource; private ContentTransformer contentTransformer; private Map<String, String> extraHeaders = new HashMap<String, String>(); private static final ContentTransformer<ByteBuf> passThroughContentTransformer = new ContentTransformer<ByteBuf>() { @Override public ByteBuf call(ByteBuf t1, ByteBufAllocator t2) { return t1; } }; HttpRequestBuilder(HttpRequestTemplate<T> requestTemplate) { this.requestTemplate = requestTemplate; this.parsedUriTemplate = requestTemplate.uriTemplate(); vars = new ConcurrentHashMap<String, Object>(); } @Override public HttpRequestBuilder<T> withRequestProperty( String key, Object value) { vars.put(key, value); return this; } public <S> HttpRequestBuilder<T> withRawContentSource(Observable<S> raw, ContentTransformer<S> transformer) { this.rawContentSource = raw; this.contentTransformer = transformer; return this; } public HttpRequestBuilder<T> withContent(Observable<ByteBuf> content) { this.rawContentSource = content; this.contentTransformer = passThroughContentTransformer; return this; } public HttpRequestBuilder<T> withHeader(String key, String value) { extraHeaders.put(key, value); return this; } @Override public RibbonRequest<T> build() { if (requestTemplate.uriTemplate() == null) { throw new IllegalArgumentException("URI template is not defined"); } if (requestTemplate.method() == null) { throw new IllegalArgumentException("HTTP method is not defined"); } try { return new HttpRequest<T>(this); } catch (TemplateParsingException e) { throw new IllegalArgumentException(e); } } HttpClientRequest<ByteBuf> createClientRequest() { String uri; try { uri = TemplateParser.toData(vars, parsedUriTemplate.getTemplate(), parsedUriTemplate.getParsed()); } catch (TemplateParsingException e) { throw new HystrixBadRequestException("Problem parsing the URI template", e); } HttpClientRequest<ByteBuf> request = HttpClientRequest.create(requestTemplate.method(), uri); for (Map.Entry<String, String> entry: requestTemplate.getHeaders().entries()) { request.withHeader(entry.getKey(), entry.getValue()); } for (Map.Entry<String, String> entry: extraHeaders.entrySet()) { request.withHeader(entry.getKey(), entry.getValue()); } if (rawContentSource != null) { request.withRawContentSource(rawContentSource, contentTransformer); } return request; } String hystrixCacheKey() throws TemplateParsingException { ParsedTemplate keyTemplate = requestTemplate.hystrixCacheKeyTemplate(); if (keyTemplate == null || (keyTemplate.getTemplate() == null || keyTemplate.getTemplate().length() == 0)) { return null; } return TemplateParser.toData(vars, requestTemplate.hystrixCacheKeyTemplate()); } Map<String, Object> requestProperties() { return vars; } CacheProviderWithKeyTemplate<T> cacheProvider() { return requestTemplate.cacheProvider(); } HttpRequestTemplate<T> template() { return requestTemplate; } }
3,597
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/hystrix/ResultCommandPair.java
package com.netflix.ribbon.hystrix; import com.netflix.hystrix.HystrixObservableCommand; /** * @author Tomasz Bak */ public class ResultCommandPair<T> { private final T result; private final HystrixObservableCommand<T> command; public ResultCommandPair(T result, HystrixObservableCommand<T> command) { this.result = result; this.command = command; } public T getResult() { return result; } public HystrixObservableCommand<T> getCommand() { return command; } }
3,598
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/hystrix/FallbackHandler.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon.hystrix; import java.util.Map; import com.netflix.hystrix.HystrixInvokableInfo; import rx.Observable; /** * * @author awang * * @param <T> Output entity type */ public interface FallbackHandler<T> { public Observable<T> getFallback(HystrixInvokableInfo<?> hystrixInfo, Map<String, Object> requestProperties); }
3,599