index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
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); } }
7,100
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; } }
7,101
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; } }
7,102
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) { } }
7,103
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; } }
7,104
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; } }
7,105
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; } }
7,106
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); } }
7,107
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); } }
7,108
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); } }
7,109
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")); } }
7,110
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); } }
7,111
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()); } }
7,112
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); } }
7,113
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); } }
7,114
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()); } }
7,115
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); } }
7,116
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; } } }
7,117
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"); } } }
7,118
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; } }
7,119
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); } }
7,120
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; } } }
7,121
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 { }
7,122
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()); } }
7,123
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); } } } }
7,124
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(); } }); } }); } }
7,125
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(); }
7,126
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); }
7,127
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); } }
7,128
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(); }
7,129
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; } }
7,130
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); } }
7,131
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; }
7,132
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(); }
7,133
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; } }
7,134
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); } }
7,135
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(); }
7,136
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(); } }
7,137
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); } }
7,138
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); }
7,139
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(); } } }
7,140
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(); } } }
7,141
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); } }
7,142
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(); }
7,143
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); } } }
7,144
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"); } } }
7,145
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); } }
7,146
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); } }
7,147
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; } }
7,148
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; } }
7,149
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) { } }
7,150
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) { } }
7,151
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); }
7,152
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()); } } }
7,153
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) { } }
7,154
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(); }
7,155
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; }
7,156
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(); }
7,157
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(); }
7,158
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(); } }
7,159
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 {}; }
7,160
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(); }
7,161
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 {}; }
7,162
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 { }
7,163
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); } }
7,164
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)); } }
7,165
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; } }
7,166
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); } }
7,167
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); } }
7,168
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); } }
7,169
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>> { }
7,170
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; } }
7,171
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; } }
7,172
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); } }); } }); } }
7,173
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()); } } }); } }); } }
7,174
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; } }
7,175
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(); } } }
7,176
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; } }
7,177
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; } }
7,178
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); }
7,179
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/hystrix/HystrixObservableCommandChain.java
package com.netflix.ribbon.hystrix; import com.netflix.hystrix.HystrixObservableCommand; import rx.Observable; import rx.functions.Func1; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * This class implements chaining mechanism for Hystrix commands. If a command in a chain fails, the next one * is run. If all commands in the chain failed, the error from the last one is reported. * To be able to identify the Hystrix command for which request was executed, an {@link ResultCommandPair} event * stream is returned by {@link #toResultCommandPairObservable()} method. * If information about Hystrix command is not important, {@link #toObservable()} method shall be used, which * is more efficient. * * @author Tomasz Bak */ public class HystrixObservableCommandChain<T> { private final List<HystrixObservableCommand<T>> hystrixCommands; public HystrixObservableCommandChain(List<HystrixObservableCommand<T>> hystrixCommands) { this.hystrixCommands = hystrixCommands; } public HystrixObservableCommandChain(HystrixObservableCommand<T>... commands) { hystrixCommands = new ArrayList<HystrixObservableCommand<T>>(commands.length); Collections.addAll(hystrixCommands, commands); } public Observable<ResultCommandPair<T>> toResultCommandPairObservable() { Observable<ResultCommandPair<T>> rootObservable = null; for (final HystrixObservableCommand<T> command : hystrixCommands) { Observable<ResultCommandPair<T>> observable = command.toObservable().map(new Func1<T, ResultCommandPair<T>>() { @Override public ResultCommandPair<T> call(T result) { return new ResultCommandPair<T>(result, command); } }); rootObservable = rootObservable == null ? observable : rootObservable.onErrorResumeNext(observable); } return rootObservable; } public Observable<T> toObservable() { Observable<T> rootObservable = null; for (final HystrixObservableCommand<T> command : hystrixCommands) { Observable<T> observable = command.toObservable(); rootObservable = rootObservable == null ? observable : rootObservable.onErrorResumeNext(observable); } return rootObservable; } public List<HystrixObservableCommand<T>> getCommands() { return Collections.unmodifiableList(hystrixCommands); } public HystrixObservableCommand getLastCommand() { return hystrixCommands.get(hystrixCommands.size() - 1); } }
7,180
0
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/hystrix/CacheObservableCommand.java
package com.netflix.ribbon.hystrix; import java.util.Map; import rx.Observable; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.ribbon.CacheProvider; /** * @author Tomasz Bak */ public class CacheObservableCommand<T> extends HystrixObservableCommand<T> { private final CacheProvider<T> cacheProvider; private final String key; private final String hystrixCacheKey; private final Map<String, Object> requestProperties; public CacheObservableCommand( CacheProvider<T> cacheProvider, String key, String hystrixCacheKey, Map<String, Object> requestProperties, Setter setter) { super(setter); this.cacheProvider = cacheProvider; this.key = key; this.hystrixCacheKey = hystrixCacheKey; this.requestProperties = requestProperties; } @Override protected String getCacheKey() { if (hystrixCacheKey == null) { return super.getCacheKey(); } else { return hystrixCacheKey; } } @Override protected Observable<T> construct() { return cacheProvider.get(key, requestProperties); } }
7,181
0
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/utils/ScheduledThreadPoolExectuorWithDynamicSize.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.utils; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import com.netflix.config.DynamicIntProperty; /** * A {@link ScheduledThreadPoolExecutor} whose core size can be dynamically changed by a given {@link DynamicIntProperty} and * registers itself with a shutdown hook to shut down. * * @author awang * * @deprecated This class is no longer necessary as part of Ribbon and should not be used by anyone */ @Deprecated public class ScheduledThreadPoolExectuorWithDynamicSize extends ScheduledThreadPoolExecutor { private final Thread shutdownThread; public ScheduledThreadPoolExectuorWithDynamicSize(final DynamicIntProperty corePoolSize, ThreadFactory threadFactory) { super(corePoolSize.get(), threadFactory); corePoolSize.addCallback(new Runnable() { public void run() { setCorePoolSize(corePoolSize.get()); } }); shutdownThread = new Thread(new Runnable() { public void run() { shutdown(); if (shutdownThread != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownThread); } catch (IllegalStateException ise) { // NOPMD } } } }); Runtime.getRuntime().addShutdownHook(shutdownThread); } }
7,182
0
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/SimpleVipAddressResolver.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.client; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.netflix.client.config.IClientConfig; import com.netflix.config.ConfigurationManager; /** * A "VipAddress" in Ribbon terminology is a logical name used for a target * server farm. This class helps interpret and resolve a "macro" and obtain a * finalized vipAddress. * <p> * Ribbon supports a comma separated set of logcial addresses for a Ribbon * Client. Typical/default implementation uses the list of servers obtained from * the first of the comma separated list and progresses down the list only when * the priorr vipAddress contains no servers. * <p> * This class assumes that the vip address string may contain marcos in the format * of ${foo}, where foo is a property in Archaius configuration, and tries to replace * these macros with actual values. * * <p> * e.g. vipAddress settings * * <code> * ${foo}.bar:${port},${foobar}:80,localhost:8080 * * The above list will be resolved by this class as * * apple.bar:80,limebar:80,localhost:8080 * * provided that the Configuration library resolves the property foo=apple,port=80 and foobar=limebar * * </code> * * @author stonse * */ public class SimpleVipAddressResolver implements VipAddressResolver { private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{(.*?)\\}"); /** * Resolve the vip address by replacing macros with actual values in configuration. * If there is no macro, the passed in string will be returned. If a macro is found but * there is no property defined in configuration, the same macro is returned as part of the * result. */ @Override public String resolve(String vipAddressMacro, IClientConfig niwsClientConfig) { if (vipAddressMacro == null || vipAddressMacro.length() == 0) { return vipAddressMacro; } return replaceMacrosFromConfig(vipAddressMacro); } private static String replaceMacrosFromConfig(String macro) { String result = macro; Matcher matcher = VAR_PATTERN.matcher(result); while (matcher.find()) { String key = matcher.group(1); String value = ConfigurationManager.getConfigInstance().getString(key); if (value != null) { result = result.replaceAll("\\$\\{" + key + "\\}", value); matcher = VAR_PATTERN.matcher(result); } } return result.trim(); } }
7,183
0
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/config/ArchaiusPropertyResolver.java
package com.netflix.client.config; import com.netflix.config.ConfigurationManager; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.event.ConfigurationEvent; import org.apache.commons.configuration.event.ConfigurationListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.stream.Collectors; public class ArchaiusPropertyResolver implements PropertyResolver { private static final Logger LOG = LoggerFactory.getLogger(ArchaiusPropertyResolver.class); public static final ArchaiusPropertyResolver INSTANCE = new ArchaiusPropertyResolver(); private final AbstractConfiguration config; private final CopyOnWriteArrayList<Runnable> actions = new CopyOnWriteArrayList<>(); private ArchaiusPropertyResolver() { this.config = ConfigurationManager.getConfigInstance(); ConfigurationManager.getConfigInstance().addConfigurationListener(new ConfigurationListener() { @Override public void configurationChanged(ConfigurationEvent event) { if (!event.isBeforeUpdate()) { actions.forEach(ArchaiusPropertyResolver::invokeAction); } } }); } private static void invokeAction(Runnable action) { try { action.run(); } catch (Exception e) { LOG.info("Failed to invoke action", e); } } @Override public <T> Optional<T> get(String key, Class<T> type) { if (Integer.class.equals(type)) { return Optional.ofNullable((T) config.getInteger(key, null)); } else if (Boolean.class.equals(type)) { return Optional.ofNullable((T) config.getBoolean(key, null)); } else if (Float.class.equals(type)) { return Optional.ofNullable((T) config.getFloat(key, null)); } else if (Long.class.equals(type)) { return Optional.ofNullable((T) config.getLong(key, null)); } else if (Double.class.equals(type)) { return Optional.ofNullable((T) config.getDouble(key, null)); } else if (TimeUnit.class.equals(type)) { return Optional.ofNullable((T) TimeUnit.valueOf(config.getString(key, null))); } else { return Optional.ofNullable(config.getStringArray(key)) .filter(ar -> ar.length > 0) .map(ar -> Arrays.stream(ar).collect(Collectors.joining(","))) .map(value -> { if (type.equals(String.class)) { return (T)value; } else { return PropertyUtils.resolveWithValueOf(type, value) .orElseThrow(() -> new IllegalArgumentException("Unable to convert value to desired type " + type)); } }); } } @Override public void forEach(String prefix, BiConsumer<String, String> consumer) { Optional.ofNullable(config.subset(prefix)) .ifPresent(subconfig -> { subconfig.getKeys().forEachRemaining(key -> { String value = config.getString(prefix + "." + key); consumer.accept(key, value); }); }); } @Override public void onChange(Runnable action) { actions.add(action); } public int getActionCount() { return actions.size(); } }
7,184
0
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/config/ArchaiusClientConfigFactory.java
package com.netflix.client.config; public class ArchaiusClientConfigFactory implements ClientConfigFactory { @Override public IClientConfig newConfig() { return new DefaultClientConfigImpl(); } }
7,185
0
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/config/DefaultClientConfigImpl.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.client.config; import java.util.concurrent.TimeUnit; /** * Default client configuration that loads properties from Archaius's ConfigurationManager. * <p> * The easiest way to configure client and load balancer is through loading properties into Archaius that conform to the specific format: <pre>{@code <clientName>.<nameSpace>.<propertyName>=<value> }</pre> <p> You can define properties in a file on classpath or as system properties. If former, ConfigurationManager.loadPropertiesFromResources() API should be called to load the file. <p> By default, "ribbon" should be the nameSpace. <p> If there is no property specified for a named client, {@code com.netflix.client.ClientFactory} will still create the client and load balancer with default values for all necessary properties. The default values are specified in this class as constants. <p> If a property is missing the clientName, it is interpreted as a property that applies to all clients. For example <pre>{@code ribbon.ReadTimeout=1000 }</pre> This will establish the default ReadTimeout property for all clients. <p> You can also programmatically set properties by constructing instance of DefaultClientConfigImpl. Follow these steps: <ul> <li> Get an instance by calling {@link #getClientConfigWithDefaultValues(String)} to load default values, and any properties that are already defined with Configuration in Archaius <li> Set all desired properties by calling {@link #setProperty(IClientConfigKey, Object)} API. <li> Pass this instance together with client name to {@code com.netflix.client.ClientFactory} API. </ul> <p><p> If it is desired to have properties defined in a different name space, for example, "foo" <pre>{@code myclient.foo.ReadTimeout=1000 }</pre> You should use {@link #getClientConfigWithDefaultValues(String, String)} - in the first step above. * * @author Sudhir Tonse * @author awang * */ public class DefaultClientConfigImpl extends AbstractDefaultClientConfigImpl { public static final String DEFAULT_PROPERTY_NAME_SPACE = CommonClientConfigKey.DEFAULT_NAME_SPACE; private String propertyNameSpace = DEFAULT_PROPERTY_NAME_SPACE; @Deprecated public Boolean getDefaultPrioritizeVipAddressBasedServers() { return DEFAULT_PRIORITIZE_VIP_ADDRESS_BASED_SERVERS; } @Deprecated public String getDefaultNfloadbalancerPingClassname() { return DEFAULT_NFLOADBALANCER_PING_CLASSNAME; } @Deprecated public String getDefaultNfloadbalancerRuleClassname() { return DEFAULT_NFLOADBALANCER_RULE_CLASSNAME; } @Deprecated public String getDefaultNfloadbalancerClassname() { return DEFAULT_NFLOADBALANCER_CLASSNAME; } @Deprecated public boolean getDefaultUseIpAddressForServer() { return DEFAULT_USEIPADDRESS_FOR_SERVER; } @Deprecated public String getDefaultClientClassname() { return DEFAULT_CLIENT_CLASSNAME; } @Deprecated public String getDefaultVipaddressResolverClassname() { return DEFAULT_VIPADDRESS_RESOLVER_CLASSNAME; } @Deprecated public String getDefaultPrimeConnectionsUri() { return DEFAULT_PRIME_CONNECTIONS_URI; } @Deprecated public int getDefaultMaxTotalTimeToPrimeConnections() { return DEFAULT_MAX_TOTAL_TIME_TO_PRIME_CONNECTIONS; } @Deprecated public int getDefaultMaxRetriesPerServerPrimeConnection() { return DEFAULT_MAX_RETRIES_PER_SERVER_PRIME_CONNECTION; } @Deprecated public Boolean getDefaultEnablePrimeConnections() { return DEFAULT_ENABLE_PRIME_CONNECTIONS; } @Deprecated public int getDefaultMaxRequestsAllowedPerWindow() { return DEFAULT_MAX_REQUESTS_ALLOWED_PER_WINDOW; } @Deprecated public int getDefaultRequestThrottlingWindowInMillis() { return DEFAULT_REQUEST_THROTTLING_WINDOW_IN_MILLIS; } @Deprecated public Boolean getDefaultEnableRequestThrottling() { return DEFAULT_ENABLE_REQUEST_THROTTLING; } @Deprecated public Boolean getDefaultEnableGzipContentEncodingFilter() { return DEFAULT_ENABLE_GZIP_CONTENT_ENCODING_FILTER; } @Deprecated public Boolean getDefaultConnectionPoolCleanerTaskEnabled() { return DEFAULT_CONNECTION_POOL_CLEANER_TASK_ENABLED; } @Deprecated public Boolean getDefaultFollowRedirects() { return DEFAULT_FOLLOW_REDIRECTS; } @Deprecated public float getDefaultPercentageNiwsEventLogged() { return DEFAULT_PERCENTAGE_NIWS_EVENT_LOGGED; } @Deprecated public int getDefaultMaxAutoRetriesNextServer() { return DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER; } @Deprecated public int getDefaultMaxAutoRetries() { return DEFAULT_MAX_AUTO_RETRIES; } @Deprecated public int getDefaultReadTimeout() { return DEFAULT_READ_TIMEOUT; } @Deprecated public int getDefaultConnectionManagerTimeout() { return DEFAULT_CONNECTION_MANAGER_TIMEOUT; } @Deprecated public int getDefaultConnectTimeout() { return DEFAULT_CONNECT_TIMEOUT; } @Deprecated public int getDefaultMaxHttpConnectionsPerHost() { return DEFAULT_MAX_HTTP_CONNECTIONS_PER_HOST; } @Deprecated public int getDefaultMaxTotalHttpConnections() { return DEFAULT_MAX_TOTAL_HTTP_CONNECTIONS; } @Deprecated public int getDefaultMaxConnectionsPerHost() { return DEFAULT_MAX_CONNECTIONS_PER_HOST; } @Deprecated public int getDefaultMaxTotalConnections() { return DEFAULT_MAX_TOTAL_CONNECTIONS; } @Deprecated public float getDefaultMinPrimeConnectionsRatio() { return DEFAULT_MIN_PRIME_CONNECTIONS_RATIO; } @Deprecated public String getDefaultPrimeConnectionsClass() { return DEFAULT_PRIME_CONNECTIONS_CLASS; } @Deprecated public String getDefaultSeverListClass() { return DEFAULT_SEVER_LIST_CLASS; } @Deprecated public int getDefaultConnectionIdleTimertaskRepeatInMsecs() { return DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS; } @Deprecated public int getDefaultConnectionidleTimeInMsecs() { return DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS; } @Deprecated public int getDefaultPoolMaxThreads() { return DEFAULT_POOL_MAX_THREADS; } @Deprecated public int getDefaultPoolMinThreads() { return DEFAULT_POOL_MIN_THREADS; } @Deprecated public long getDefaultPoolKeepAliveTime() { return DEFAULT_POOL_KEEP_ALIVE_TIME; } @Deprecated public TimeUnit getDefaultPoolKeepAliveTimeUnits() { return DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS; } @Deprecated public Boolean getDefaultEnableZoneAffinity() { return DEFAULT_ENABLE_ZONE_AFFINITY; } @Deprecated public Boolean getDefaultEnableZoneExclusivity() { return DEFAULT_ENABLE_ZONE_EXCLUSIVITY; } @Deprecated public int getDefaultPort() { return DEFAULT_PORT; } @Deprecated public Boolean getDefaultEnableLoadbalancer() { return DEFAULT_ENABLE_LOADBALANCER; } @Deprecated public Boolean getDefaultOkToRetryOnAllOperations() { return DEFAULT_OK_TO_RETRY_ON_ALL_OPERATIONS; } @Deprecated public Boolean getDefaultIsClientAuthRequired(){ return DEFAULT_IS_CLIENT_AUTH_REQUIRED; } @Deprecated public Boolean getDefaultEnableConnectionPool() { return DEFAULT_ENABLE_CONNECTION_POOL; } /** * Create instance with no properties in default name space {@link #DEFAULT_PROPERTY_NAME_SPACE} */ public DefaultClientConfigImpl() { super(ArchaiusPropertyResolver.INSTANCE); } /** * Create instance with no properties in the specified name space */ public DefaultClientConfigImpl(String nameSpace) { this(); this.propertyNameSpace = nameSpace; } public void loadDefaultValues() { setDefault(CommonClientConfigKey.MaxHttpConnectionsPerHost, getDefaultMaxHttpConnectionsPerHost()); setDefault(CommonClientConfigKey.MaxTotalHttpConnections, getDefaultMaxTotalHttpConnections()); setDefault(CommonClientConfigKey.EnableConnectionPool, getDefaultEnableConnectionPool()); setDefault(CommonClientConfigKey.MaxConnectionsPerHost, getDefaultMaxConnectionsPerHost()); setDefault(CommonClientConfigKey.MaxTotalConnections, getDefaultMaxTotalConnections()); setDefault(CommonClientConfigKey.ConnectTimeout, getDefaultConnectTimeout()); setDefault(CommonClientConfigKey.ConnectionManagerTimeout, getDefaultConnectionManagerTimeout()); setDefault(CommonClientConfigKey.ReadTimeout, getDefaultReadTimeout()); setDefault(CommonClientConfigKey.MaxAutoRetries, getDefaultMaxAutoRetries()); setDefault(CommonClientConfigKey.MaxAutoRetriesNextServer, getDefaultMaxAutoRetriesNextServer()); setDefault(CommonClientConfigKey.OkToRetryOnAllOperations, getDefaultOkToRetryOnAllOperations()); setDefault(CommonClientConfigKey.FollowRedirects, getDefaultFollowRedirects()); setDefault(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, getDefaultConnectionPoolCleanerTaskEnabled()); setDefault(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, getDefaultConnectionidleTimeInMsecs()); setDefault(CommonClientConfigKey.ConnectionCleanerRepeatInterval, getDefaultConnectionIdleTimertaskRepeatInMsecs()); setDefault(CommonClientConfigKey.EnableGZIPContentEncodingFilter, getDefaultEnableGzipContentEncodingFilter()); setDefault(CommonClientConfigKey.ProxyHost, null); setDefault(CommonClientConfigKey.ProxyPort, null); setDefault(CommonClientConfigKey.Port, getDefaultPort()); setDefault(CommonClientConfigKey.EnablePrimeConnections, getDefaultEnablePrimeConnections()); setDefault(CommonClientConfigKey.MaxRetriesPerServerPrimeConnection, getDefaultMaxRetriesPerServerPrimeConnection()); setDefault(CommonClientConfigKey.MaxTotalTimeToPrimeConnections, getDefaultMaxTotalTimeToPrimeConnections()); setDefault(CommonClientConfigKey.PrimeConnectionsURI, getDefaultPrimeConnectionsUri()); setDefault(CommonClientConfigKey.PoolMinThreads, getDefaultPoolMinThreads()); setDefault(CommonClientConfigKey.PoolMaxThreads, getDefaultPoolMaxThreads()); setDefault(CommonClientConfigKey.PoolKeepAliveTime, (int)getDefaultPoolKeepAliveTime()); setDefault(CommonClientConfigKey.PoolKeepAliveTimeUnits, getDefaultPoolKeepAliveTimeUnits().toString()); setDefault(CommonClientConfigKey.EnableZoneAffinity, getDefaultEnableZoneAffinity()); setDefault(CommonClientConfigKey.EnableZoneExclusivity, getDefaultEnableZoneExclusivity()); setDefault(CommonClientConfigKey.ClientClassName, getDefaultClientClassname()); setDefault(CommonClientConfigKey.NFLoadBalancerClassName, getDefaultNfloadbalancerClassname()); setDefault(CommonClientConfigKey.NFLoadBalancerRuleClassName, getDefaultNfloadbalancerRuleClassname()); setDefault(CommonClientConfigKey.NFLoadBalancerPingClassName, getDefaultNfloadbalancerPingClassname()); setDefault(CommonClientConfigKey.PrioritizeVipAddressBasedServers, getDefaultPrioritizeVipAddressBasedServers()); setDefault(CommonClientConfigKey.MinPrimeConnectionsRatio, getDefaultMinPrimeConnectionsRatio()); setDefault(CommonClientConfigKey.PrimeConnectionsClassName, getDefaultPrimeConnectionsClass()); setDefault(CommonClientConfigKey.NIWSServerListClassName, getDefaultSeverListClass()); setDefault(CommonClientConfigKey.VipAddressResolverClassName, getDefaultVipaddressResolverClassname()); setDefault(CommonClientConfigKey.IsClientAuthRequired, getDefaultIsClientAuthRequired()); setDefault(CommonClientConfigKey.UseIPAddrForServer, getDefaultUseIpAddressForServer()); setDefault(CommonClientConfigKey.ListOfServers, ""); } @Deprecated protected void setPropertyInternal(IClientConfigKey propName, Object value) { set(propName, value); } // Helper methods which first check if a "default" (with rest client name) // property exists. If so, that value is used, else the default value // passed as argument is used to put into the properties member variable @Deprecated protected void putDefaultIntegerProperty(IClientConfigKey propName, Integer defaultValue) { this.set(propName, defaultValue); } @Deprecated protected void putDefaultLongProperty(IClientConfigKey propName, Long defaultValue) { this.set(propName, defaultValue); } @Deprecated protected void putDefaultFloatProperty(IClientConfigKey propName, Float defaultValue) { this.set(propName, defaultValue); } @Deprecated protected void putDefaultTimeUnitProperty(IClientConfigKey propName, TimeUnit defaultValue) { this.set(propName, defaultValue); } @Deprecated protected void putDefaultStringProperty(IClientConfigKey propName, String defaultValue) { this.set(propName, defaultValue); } @Deprecated protected void putDefaultBooleanProperty(IClientConfigKey propName, Boolean defaultValue) { this.set(propName, defaultValue); } @Deprecated String getDefaultPropName(String propName) { return getNameSpace() + "." + propName; } public String getDefaultPropName(IClientConfigKey propName) { return getDefaultPropName(propName.key()); } public String getInstancePropName(String restClientName, IClientConfigKey configKey) { return getInstancePropName(restClientName, configKey.key()); } public String getInstancePropName(String restClientName, String key) { if (getNameSpace() == null) { throw new NullPointerException("getNameSpace() may not be null"); } return restClientName + "." + getNameSpace() + "." + key; } public DefaultClientConfigImpl withProperty(IClientConfigKey key, Object value) { setProperty(key, value); return this; } public static DefaultClientConfigImpl getEmptyConfig() { return new DefaultClientConfigImpl(); } public static DefaultClientConfigImpl getClientConfigWithDefaultValues(String clientName) { return getClientConfigWithDefaultValues(clientName, DEFAULT_PROPERTY_NAME_SPACE); } public static DefaultClientConfigImpl getClientConfigWithDefaultValues() { return getClientConfigWithDefaultValues("default", DEFAULT_PROPERTY_NAME_SPACE); } public static DefaultClientConfigImpl getClientConfigWithDefaultValues(String clientName, String nameSpace) { DefaultClientConfigImpl config = new DefaultClientConfigImpl(nameSpace); config.loadProperties(clientName); return config; } }
7,186
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/ResponseTimeWeightedRuleTest.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.client.http; import java.net.URI; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.client.http.HttpRequest; import com.netflix.config.ConfigurationManager; import com.netflix.loadbalancer.AbstractLoadBalancer; import com.netflix.loadbalancer.WeightedResponseTimeRule; public class ResponseTimeWeightedRuleTest { @Test public void testServerWeights(){ try{ ConfigurationManager.loadPropertiesFromResources("sample-client.properties"); ConfigurationManager.getConfigInstance().setProperty( "sample-client.ribbon.NFLoadBalancerClassName", "com.netflix.loadbalancer.DynamicServerListLoadBalancer"); ConfigurationManager.getConfigInstance().setProperty( "sample-client.ribbon.NFLoadBalancerRuleClassName", "com.netflix.loadbalancer.WeightedResponseTimeRule"); // shorter weight adjusting interval ConfigurationManager.getConfigInstance().setProperty( "sample-client.ribbon." + WeightedResponseTimeRule.WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY, "5000"); ConfigurationManager.getConfigInstance().setProperty( "sample-client.ribbon.InitializeNFLoadBalancer", "true"); RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client"); HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); for (int i = 0; i < 20; i++) { client.executeWithLoadBalancer(request); } System.out.println(((AbstractLoadBalancer) client.getLoadBalancer()).getLoadBalancerStats()); // wait for the weights to be adjusted Thread.sleep(5000); for (int i = 0; i < 50; i++) { client.executeWithLoadBalancer(request); } System.out.println(((AbstractLoadBalancer) client.getLoadBalancer()).getLoadBalancerStats()); } catch (Exception e){ e.printStackTrace(); } } }
7,187
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/GetPostTest.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.client.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.util.Random; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.client.http.HttpRequest.Verb; import com.sun.jersey.api.container.httpserver.HttpServerFactory; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.net.httpserver.HttpServer; public class GetPostTest { private static HttpServer server = null; private static String SERVICE_URI; private static RestClient client; @BeforeClass public static void init() throws Exception { PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.http", "com.netflix.niws.client"); int port = (new Random()).nextInt(1000) + 4000; SERVICE_URI = "http://localhost:" + port + "/"; try{ server = HttpServerFactory.create(SERVICE_URI, resourceConfig); server.start(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } client = (RestClient) ClientFactory.getNamedClient("GetPostTest"); } @AfterClass public static void shutDown() { server.stop(0); } @Test public void testGet() throws Exception { URI getUri = new URI(SERVICE_URI + "test/getObject"); MultivaluedMapImpl params = new MultivaluedMapImpl(); params.add("name", "test"); HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build(); HttpResponse response = client.execute(request); assertEquals(200, response.getStatus()); assertTrue(response.getEntity(TestObject.class).name.equals("test")); } @Test public void testPost() throws Exception { URI getUri = new URI(SERVICE_URI + "test/setObject"); TestObject obj = new TestObject(); obj.name = "fromClient"; HttpRequest request = HttpRequest.newBuilder().verb(Verb.POST).uri(getUri).entity(obj).build(); HttpResponse response = client.execute(request); assertEquals(200, response.getStatus()); assertTrue(response.getEntity(TestObject.class).name.equals("fromClient")); } @Test public void testChunkedEncoding() throws Exception { String obj = "chunked encoded content"; URI postUri = new URI(SERVICE_URI + "test/postStream"); InputStream input = new ByteArrayInputStream(obj.getBytes("UTF-8")); HttpRequest request = HttpRequest.newBuilder().verb(Verb.POST).uri(postUri).entity(input).build(); HttpResponse response = client.execute(request); assertEquals(200, response.getStatus()); assertTrue(response.getEntity(String.class).equals(obj)); } }
7,188
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/SecureRestClientKeystoreTest.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.client.http; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileOutputStream; import java.security.KeyStore; import java.security.cert.Certificate; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.config.ConfigurationManager; import com.sun.jersey.core.util.Base64; /** * Test keystore info is configurable/retrievable * * @author jzarfoss * */ public class SecureRestClientKeystoreTest { @Test public void testGetKeystoreWithClientAuth() throws Exception{ // jks format byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1); byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1); File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore"); File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore"); FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore); try { keystoreFileOut.write(dummyKeystore); } finally { keystoreFileOut.close(); } FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore); try { truststoreFileOut.write(dummyTruststore); } finally { truststoreFileOut.close(); } AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = this.getClass().getName() + ".test1"; String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, "changeit"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, tempTruststore.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, "changeit"); RestClient client = (RestClient) ClientFactory.getNamedClient(name); KeyStore keyStore = client.getKeyStore(); Certificate cert = keyStore.getCertificate("ribbon_key"); assertNotNull(cert); } @Test public void testGetKeystoreWithNoClientAuth() throws Exception{ // jks format byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1); byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1); File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore"); File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore"); FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore); try { keystoreFileOut.write(dummyKeystore); } finally { keystoreFileOut.close(); } FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore); try { truststoreFileOut.write(dummyTruststore); } finally { truststoreFileOut.close(); } AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = this.getClass().getName() + ".test2"; String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, "changeit"); RestClient client = (RestClient) ClientFactory.getNamedClient(name); KeyStore keyStore = client.getKeyStore(); Certificate cert = keyStore.getCertificate("ribbon_key"); assertNotNull(cert); } }
7,189
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RetryTest.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.client.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.net.URI; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import com.google.common.collect.Lists; import com.netflix.client.ClientException; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpRequest.Verb; import com.netflix.client.http.HttpResponse; import com.netflix.client.testutil.MockHttpServer; import com.netflix.config.ConfigurationManager; import com.netflix.http4.MonitoredConnectionManager; import com.netflix.http4.NFHttpClient; import com.netflix.http4.NFHttpClientFactory; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.DummyPing; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerStats; public class RetryTest { @ClassRule public static MockHttpServer server = new MockHttpServer() ; private RestClient client; private BaseLoadBalancer lb; private NFHttpClient httpClient; private MonitoredConnectionManager connectionPoolManager; private static Server localServer; @BeforeClass public static void init() throws Exception { // PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.client.http"); localServer = new Server("localhost", server.getServerPort()); } @Before public void beforeTest() { ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.NFLoadBalancerClassName", BaseLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.client.NFLoadBalancerPingClassName", DummyPing.class.getName()); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.ReadTimeout", "1000"); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.ConnectTimeout, "500"); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.OkToRetryOnAllOperations, "true"); client = (RestClient) ClientFactory.getNamedClient("RetryTest"); lb = (BaseLoadBalancer) client.getLoadBalancer(); lb.setServersList(Lists.newArrayList(localServer)); httpClient = NFHttpClientFactory.getNamedNFHttpClient("RetryTest"); connectionPoolManager = (MonitoredConnectionManager) httpClient.getConnectionManager(); client.setMaxAutoRetries(0); client.setMaxAutoRetriesNextServer(0); client.setOkToRetryOnAllOperations(false); lb.setServersList(Lists.newArrayList(localServer)); // reset the server index lb.setRule(new AvailabilityFilteringRule()); lb.getLoadBalancerStats().getSingleServerStat(localServer).clearSuccessiveConnectionFailureCount(); } @Test public void testThrottled() throws Exception { URI localUrl = new URI("/status?code=503"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build(); try { client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 0)); fail("Exception expected"); } catch (ClientException e) { assertNotNull(e); } assertEquals(1, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount()); } @Test public void testThrottledWithRetrySameServer() throws Exception { URI localUrl = new URI("/status?code=503"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build(); try { client.executeWithLoadBalancer(request, DefaultClientConfigImpl .getEmptyConfig() .set(CommonClientConfigKey.MaxAutoRetries, 1) .set(CommonClientConfigKey.MaxAutoRetriesNextServer, 0)); fail("Exception expected"); } catch (ClientException e) { // NOPMD } assertEquals(2, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount()); } @Test public void testThrottledWithRetryNextServer() throws Exception { int connectionCount = connectionPoolManager.getConnectionsInPool(); URI localUrl = new URI("/status?code=503"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build(); try { client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); fail("Exception expected"); } catch (ClientException e) { // NOPMD } assertEquals(3, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount()); System.out.println("Initial connections count " + connectionCount); System.out.println("Final connections count " + connectionPoolManager.getConnectionsInPool()); // should be no connection leak assertTrue(connectionPoolManager.getConnectionsInPool() <= connectionCount + 1); } @Test public void testReadTimeout() throws Exception { URI localUrl = new URI("/noresponse"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build(); try { client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); fail("Exception expected"); } catch (ClientException e) { // NOPMD } assertEquals(3, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount()); } @Test public void testReadTimeoutWithRetriesNextServe() throws Exception { URI localUrl = new URI("/noresponse"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build(); try { client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); fail("Exception expected"); } catch (ClientException e) { // NOPMD } assertEquals(3, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount()); } @Test public void postReadTimeout() throws Exception { URI localUrl = new URI("/noresponse"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).build(); try { client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); fail("Exception expected"); } catch (ClientException e) { // NOPMD } ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(localServer); assertEquals(1, stats.getSuccessiveConnectionFailureCount()); } @Test public void testRetriesOnPost() throws Exception { URI localUrl = new URI("/noresponse"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).setRetriable(true).build(); try { client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); fail("Exception expected"); } catch (ClientException e) { // NOPMD } ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(localServer); assertEquals(3, stats.getSuccessiveConnectionFailureCount()); } @Test public void testRetriesOnPostWithConnectException() throws Exception { URI localUrl = new URI("/status?code=503"); lb.setServersList(Lists.newArrayList(localServer)); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).setRetriable(true).build(); try { HttpResponse response = client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); fail("Exception expected"); } catch (ClientException e) { // NOPMD } ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(localServer); assertEquals(3, stats.getSuccessiveConnectionFailureCount()); } @Test public void testSuccessfulRetries() throws Exception { lb.setServersList(Lists.newArrayList(new Server("localhost:12987"), new Server("localhost:12987"), localServer)); URI localUrl = new URI("/ok"); HttpRequest request = HttpRequest.newBuilder().uri(localUrl).queryParams("name", "ribbon").build(); try { HttpResponse response = client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2)); assertEquals(200, response.getStatus()); } catch (ClientException e) { fail("Unexpected exception"); } ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(new Server("localhost:12987")); assertEquals(1, stats.getSuccessiveConnectionFailureCount()); } }
7,190
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/TestObject.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.client.http; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class TestObject { public String name; }
7,191
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RestClientTest.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.client.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.ClassRule; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.client.testutil.MockHttpServer; import com.netflix.config.ConfigurationManager; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.Server; public class RestClientTest { @ClassRule public static MockHttpServer server = new MockHttpServer(); @ClassRule public static MockHttpServer secureServer = new MockHttpServer().secure(); @Test public void testExecuteWithoutLB() throws Exception { RestClient client = (RestClient) ClientFactory.getNamedClient("google"); HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build(); HttpResponse response = client.executeWithLoadBalancer(request); assertStatusIsOk(response.getStatus()); response = client.execute(request); assertStatusIsOk(response.getStatus()); } @Test public void testExecuteWithLB() throws Exception { ConfigurationManager.getConfigInstance().setProperty("allservices.ribbon." + CommonClientConfigKey.ReadTimeout, "10000"); ConfigurationManager.getConfigInstance().setProperty("allservices.ribbon." + CommonClientConfigKey.FollowRedirects, "true"); RestClient client = (RestClient) ClientFactory.getNamedClient("allservices"); BaseLoadBalancer lb = new BaseLoadBalancer(); Server[] servers = new Server[]{new Server("localhost", server.getServerPort())}; lb.addServers(Arrays.asList(servers)); client.setLoadBalancer(lb); Set<URI> expected = new HashSet<URI>(); expected.add(new URI(server.getServerPath("/"))); Set<URI> result = new HashSet<URI>(); HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); for (int i = 0; i < 5; i++) { HttpResponse response = client.executeWithLoadBalancer(request); assertStatusIsOk(response.getStatus()); assertTrue(response.isSuccess()); String content = response.getEntity(String.class); response.close(); assertFalse(content.isEmpty()); result.add(response.getRequestedURI()); } assertEquals(expected, result); request = HttpRequest.newBuilder().uri(server.getServerURI()).build(); HttpResponse response = client.executeWithLoadBalancer(request); assertEquals(200, response.getStatus()); } @Test public void testVipAsURI() throws Exception { ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.DeploymentContextBasedVipAddresses", server.getServerPath("/")); ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.InitializeNFLoadBalancer", "false"); RestClient client = (RestClient) ClientFactory.getNamedClient("test1"); assertNull(client.getLoadBalancer()); HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); HttpResponse response = client.executeWithLoadBalancer(request); assertStatusIsOk(response.getStatus()); assertEquals(server.getServerPath("/"), response.getRequestedURI().toString()); } @Test public void testSecureClient() throws Exception { ConfigurationManager.getConfigInstance().setProperty("test2.ribbon.IsSecure", "true"); RestClient client = (RestClient) ClientFactory.getNamedClient("test2"); HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build(); HttpResponse response = client.executeWithLoadBalancer(request); assertStatusIsOk(response.getStatus()); } @Test public void testSecureClient2() throws Exception { ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.IsSecure, "true"); ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStore, secureServer.getTrustStore().getAbsolutePath()); ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD); RestClient client = (RestClient) ClientFactory.getNamedClient("test3"); BaseLoadBalancer lb = new BaseLoadBalancer(); Server[] servers = new Server[]{new Server("localhost", secureServer.getServerPort())}; lb.addServers(Arrays.asList(servers)); client.setLoadBalancer(lb); HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); HttpResponse response = client.executeWithLoadBalancer(request); assertStatusIsOk(response.getStatus()); assertEquals(secureServer.getServerPath("/"), response.getRequestedURI().toString()); } @Test public void testDelete() throws Exception { RestClient client = (RestClient) ClientFactory.getNamedClient("google"); HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).verb(HttpRequest.Verb.DELETE).build(); HttpResponse response = client.execute(request); assertStatusIsOk(response.getStatus()); request = HttpRequest.newBuilder().uri(server.getServerURI()).verb(HttpRequest.Verb.DELETE).entity("").build(); response = client.execute(request); assertStatusIsOk(response.getStatus()); } private void assertStatusIsOk(int status) { assertTrue(status == 200 || status == 302); } }
7,192
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/FollowRedirectTest.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.client.http; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URI; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.netflix.client.ClientFactory; 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.http.HttpRequest; import com.netflix.client.http.HttpResponse; public class FollowRedirectTest { private MockWebServer redirectingServer; private MockWebServer redirectedServer; @Before public void setup() throws IOException { redirectedServer = new MockWebServer(); redirectedServer.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "text/plain") .setBody("OK")); redirectingServer = new MockWebServer(); redirectedServer.play(); redirectingServer.enqueue(new MockResponse() .setResponseCode(302) .setHeader("Location", "http://localhost:" + redirectedServer.getPort())); redirectingServer.play(); } @After public void shutdown() { try { redirectedServer.shutdown(); } catch (IOException e) { e.printStackTrace(); } try { redirectingServer.shutdown(); } catch (IOException e) { e.printStackTrace(); } } @Test public void testRedirectNotFollowed() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues("myclient"); config.set(CommonClientConfigKey.FollowRedirects, Boolean.FALSE); ClientFactory.registerClientFromProperties("myclient", config); RestClient client = (RestClient) ClientFactory.getNamedClient("myclient"); HttpRequest request = HttpRequest.newBuilder().uri(new URI("http://localhost:" + redirectingServer.getPort())).build(); HttpResponse response = client.executeWithLoadBalancer(request); assertEquals(302, response.getStatus()); } @Test public void testRedirectFollowed() throws Exception { IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues("myclient2") .set(IClientConfigKey.Keys.FollowRedirects, Boolean.TRUE); ClientFactory.registerClientFromProperties("myclient2", config); com.netflix.niws.client.http.RestClient client = (com.netflix.niws.client.http.RestClient) ClientFactory.getNamedClient("myclient2"); HttpRequest request = HttpRequest.newBuilder().uri(new URI("http://localhost:" + redirectingServer.getPort())).build(); HttpResponse response = client.execute(request); assertEquals(200, response.getStatus()); } }
7,193
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/SecureAcceptAllGetTest.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.client.http; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.client.testutil.SimpleSSLTestServer; import com.netflix.config.ConfigurationManager; import com.sun.jersey.core.util.Base64; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.*; import org.junit.rules.TestName; import javax.net.ssl.SSLPeerUnverifiedException; import java.io.File; import java.io.FileOutputStream; import java.net.URI; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * * Test that the AcceptAllSocketFactory works against a dumbed down TLS server, except when it shouldn't... * * @author jzarfoss * */ public class SecureAcceptAllGetTest { private static String TEST_SERVICE_URI; private static File TEST_FILE_KS; private static File TEST_FILE_TS; private static SimpleSSLTestServer TEST_SERVER; @Rule public TestName testName = new TestName(); @BeforeClass public static void init() throws Exception { // jks format byte[] sampleTruststore1 = Base64.decode(SecureGetTest.TEST_TS1); byte[] sampleKeystore1 = Base64.decode(SecureGetTest.TEST_KS1); TEST_FILE_KS = File.createTempFile("SecureAcceptAllGetTest", ".keystore"); TEST_FILE_TS = File.createTempFile("SecureAcceptAllGetTest", ".truststore"); FileOutputStream keystoreFileOut = new FileOutputStream(TEST_FILE_KS); try { keystoreFileOut.write(sampleKeystore1); } finally { keystoreFileOut.close(); } FileOutputStream truststoreFileOut = new FileOutputStream(TEST_FILE_TS); try { truststoreFileOut.write(sampleTruststore1); } finally { truststoreFileOut.close(); } try { TEST_SERVER = new SimpleSSLTestServer(TEST_FILE_TS, SecureGetTest.PASSWORD, TEST_FILE_KS, SecureGetTest.PASSWORD, false); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } // setup server 1, will use first keystore/truststore with client auth TEST_SERVICE_URI = "https://127.0.0.1:" + TEST_SERVER.getPort() + "/"; } @AfterClass public static void shutDown(){ try{ TEST_SERVER.close(); }catch(Exception e){ e.printStackTrace(); } } @Test public void testPositiveAcceptAllSSLSocketFactory() throws Exception{ // test connection succeeds connecting to a random SSL endpoint with allow all SSL factory AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = "GetPostSecureTest." + testName.getMethodName(); String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.CustomSSLSocketFactoryClassName, "com.netflix.http4.ssl.AcceptAllSocketFactory"); RestClient rc = (RestClient) ClientFactory.getNamedClient(name); TEST_SERVER.accept(); URI getUri = new URI(TEST_SERVICE_URI + "test/"); HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build(); HttpResponse response = rc.execute(request); assertEquals(200, response.getStatus()); } @Test public void testNegativeAcceptAllSSLSocketFactoryCannotWorkWithTrustStore() throws Exception{ // test config exception happens before we even try to connect to anything AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = "GetPostSecureTest." + testName.getMethodName(); String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.CustomSSLSocketFactoryClassName, "com.netflix.http4.ssl.AcceptAllSocketFactory"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, TEST_FILE_TS.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD); boolean foundCause = false; try { ClientFactory.getNamedClient(name); } catch(Throwable t){ while (t != null && ! foundCause){ if (t instanceof IllegalArgumentException && t.getMessage().startsWith("Invalid value for property:CustomSSLSocketFactoryClassName")){ foundCause = true; break; } t = t.getCause(); } } assertTrue(foundCause); } @Test public void testNegativeAcceptAllSSLSocketFactory() throws Exception{ // test exception is thrown connecting to a random SSL endpoint without explicitly setting factory to allow all String name = "GetPostSecureTest." + testName.getMethodName(); // don't set any interesting properties -- really we're just setting the defaults RestClient rc = (RestClient) ClientFactory.getNamedClient(name); TEST_SERVER.accept(); URI getUri = new URI(TEST_SERVICE_URI + "test/"); HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build(); boolean foundCause = false; try { rc.execute(request); } catch(Throwable t){ while (t != null && ! foundCause){ if (t instanceof SSLPeerUnverifiedException && t.getMessage().startsWith("peer not authenticated")){ foundCause = true; break; } t = t.getCause(); } } assertTrue(foundCause); } }
7,194
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/TestResource.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.client.http; import java.io.InputStream; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.IOUtils; @Produces({"application/xml"}) @Path("/test") public class TestResource { @Path("/getObject") @GET public Response getObject(@QueryParam ("name") String name) { TestObject obj = new TestObject(); obj.name = name; return Response.ok(obj).build(); } @Path("/getJsonObject") @Produces("application/json") @GET public Response getJsonObject(@QueryParam ("name") String name) throws Exception { TestObject obj = new TestObject(); obj.name = name; ObjectMapper mapper = new ObjectMapper(); String value = mapper.writeValueAsString(obj); return Response.ok(value).build(); } @Path("/setObject") @POST @Consumes(MediaType.APPLICATION_XML) public Response setObject(TestObject obj) { return Response.ok(obj).build(); } @Path("/setJsonObject") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response setJsonObject(String obj) throws Exception { System.out.println("Get json string " + obj); return Response.ok(obj).build(); } @POST @Path("/postStream") @Consumes( { MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_XML}) public Response handlePost(final InputStream in, @HeaderParam("Transfer-Encoding") String transferEncoding) { try { byte[] bytes = IOUtils.toByteArray(in); String entity = new String(bytes, "UTF-8"); return Response.ok(entity).build(); } catch (Exception e) { return Response.serverError().build(); } } @GET @Path("/get503") public Response get503() { return Response.status(503).build(); } @GET @Path("/get500") public Response get500() { return Response.status(500).build(); } @GET @Path("/getReadtimeout") public Response getReadtimeout() { try { Thread.sleep(10000); } catch (Exception e) { // NOPMD } return Response.ok().build(); } @POST @Path("/postReadtimeout") public Response postReadtimeout() { try { Thread.sleep(10000); } catch (Exception e) { // NOPMD } return Response.ok().build(); } }
7,195
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/SecureGetTest.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.client.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileOutputStream; import java.net.URI; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.client.testutil.SimpleSSLTestServer; import com.netflix.config.ConfigurationManager; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.core.util.Base64; import com.sun.jersey.core.util.MultivaluedMapImpl; /** * * Test TLS configurations work against a very dumbed down test server. * * @author jzarfoss * */ public class SecureGetTest { // custom minted test keystores/truststores for Ribbon testing // PLEASE DO NOT USE FOR ANYTHING OTHER THAN TESTING (the private keys are sitting right here in a String!!) // but if you need keystore to test with, help yourself, they're good until 2113! // we have a pair of independently valid keystore/truststore combinations // thus allowing us to perform both positive and negative testing, // the negative testing being that set 1 and set 2 cannot talk to each other // base64 encoded // Keystore type: JKS // Keystore provider: SUN // // Your keystore contains 1 entry // // Alias name: ribbon_root // Creation date: Sep 6, 2013 // Entry type: trustedCertEntry // // Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot1 // Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot1 // Serial number: 1 // Valid from: Fri Sep 06 10:25:22 PDT 2013 until: Sun Aug 13 10:25:22 PDT 2113 // Certificate fingerprints: // MD5: BD:08:2A:F3:3B:26:C0:D4:44:B9:6D:EE:D2:45:31:C0 // SHA1: 64:95:7E:C6:0C:D7:81:56:28:0C:93:60:85:AB:9D:E2:60:33:70:43 // Signature algorithm name: SHA1withRSA // Version: 3 // // Extensions: // // #1: ObjectId: 2.5.29.19 Criticality=false // BasicConstraints:[ // CA:true // PathLen:2147483647 // ] public static final String TEST_TS1 = "/u3+7QAAAAIAAAABAAAAAgALcmliYm9uX3Jvb3QAAAFA9E6KkQAFWC41MDkAAAIyMIICLjCCAZeg" + "AwIBAgIBATANBgkqhkiG9w0BAQUFADBTMRgwFgYDVQQDDA9SaWJib25UZXN0Um9vdDExCzAJBgNV" + "BAsMAklUMRAwDgYDVQQKDAdOZXRmbGl4MQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwIBcNMTMw" + "OTA2MTcyNTIyWhgPMjExMzA4MTMxNzI1MjJaMFMxGDAWBgNVBAMMD1JpYmJvblRlc3RSb290MTEL" + "MAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgxCzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCB" + "nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAg8riOgT2Y39SQlZE+MWnOiKjREZzQ3ecvPf40oF8" + "9YPNGpBhJzIKdA0TR1vQ70p3Fl2+Y5txs1H2/iguOdFMBrSdv1H8qJG1UufaeYO++HBm3Mi2L02F" + "6fcTEEyXQMebKCWf04mxvLy5M6B5yMqZ9rHEZD+qsF4rXspx70bd0tUCAwEAAaMQMA4wDAYDVR0T" + "BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBzTEn9AZniODYSRa+N7IvZu127rh+Sc6XWth68TBRj" + "hThDFARnGxxe2d3EFXB4xH7qcvLl3HQ3U6lIycyLabdm06D3/jzu68mkMToE5sHJmrYNHHTVl0aj" + "0gKFBQjLRJRlgJ3myUbbfrM+/a5g6S90TsVGTxXwFn5bDvdErsn8F8Hd41plMkW5ywsn6yFZMaFr" + "MxnX"; // Keystore type: JKS // Keystore provider: SUN // // Your keystore contains 1 entry // // Alias name: ribbon_root // Creation date: Sep 6, 2013 // Entry type: trustedCertEntry // // Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2 // Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2 // Serial number: 1 // Valid from: Fri Sep 06 10:26:22 PDT 2013 until: Sun Aug 13 10:26:22 PDT 2113 // Certificate fingerprints: // MD5: 44:64:E3:25:4F:D2:2C:8D:4D:B0:53:19:59:BD:B3:20 // SHA1: 26:2F:41:6D:03:C7:D0:8E:4F:AF:0E:4F:29:E3:08:53:B7:3C:DB:EE // Signature algorithm name: SHA1withRSA // Version: 3 // // Extensions: // // #1: ObjectId: 2.5.29.19 Criticality=false // BasicConstraints:[ // CA:true // PathLen:2147483647 // ] public static final String TEST_TS2 = "/u3+7QAAAAIAAAABAAAAAgALcmliYm9uX3Jvb3QAAAFA9E92vgAFWC41MDkAAAIyMIICLjCCAZeg" + "AwIBAgIBATANBgkqhkiG9w0BAQUFADBTMRgwFgYDVQQDDA9SaWJib25UZXN0Um9vdDIxCzAJBgNV" + "BAsMAklUMRAwDgYDVQQKDAdOZXRmbGl4MQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwIBcNMTMw" + "OTA2MTcyNjIyWhgPMjExMzA4MTMxNzI2MjJaMFMxGDAWBgNVBAMMD1JpYmJvblRlc3RSb290MjEL" + "MAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgxCzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCB" + "nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAnEwAfuHYKRJviVB3RyV3+/mp4qjWZZd/q+fE2Z0k" + "o2N2rrC8fAw53KXwGOE5fED6wXd3B2zyoSFHVsWOeL+TUoohn+eHSfwH7xK+0oWC8IvUoXWehOft" + "grYtv9Jt5qNY5SmspBmyxFiaiAWQJYuf12Ycu4Gqg+P7mieMHgu6Do0CAwEAAaMQMA4wDAYDVR0T" + "BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBNA0ask9eTYYhYA3bbmQZInxkBV74Gq/xorLlVygjn" + "OgyGYp4/L274qwlPMqnQRmVbezkug2YlUK8xbrjwCUvHq2XW38e2RjK5q3EXVkGJxgCBuHug/eIf" + "wD+/IEIE8aVkTW2j1QrrdkXDhRO5OsjvIVdy5/V4U0hVDnSo865ud9VQ/hZmOQuZItHViSoGSe2j" + "bbZk"; // Keystore type: JKS // Keystore provider: SUN // // Your keystore contains 1 entry // // Alias name: ribbon_key // Creation date: Sep 6, 2013 // Entry type: PrivateKeyEntry // Certificate chain length: 1 // Certificate[1]: // Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestEndEntity1 // Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot1 // Serial number: 64 // Valid from: Fri Sep 06 10:25:22 PDT 2013 until: Sun Aug 13 10:25:22 PDT 2113 // Certificate fingerprints: // MD5: 79:C5:F3:B2:B8:4C:F2:3F:2E:C7:67:FC:E7:04:BF:90 // SHA1: B1:D0:4E:A6:D8:84:BF:8B:01:46:B6:EA:97:5B:A0:4E:13:8B:A9:DE // Signature algorithm name: SHA1withRSA // Version: 3 public static final String TEST_KS1 = "/u3+7QAAAAIAAAABAAAAAQAKcmliYm9uX2tleQAAAUD0Toq4AAACuzCCArcwDgYKKwYBBAEqAhEB" + "AQUABIICo9fLN8zeXLcyx50+6B6gdXiUslZKY0SgLwL8kKNlQFiccD3Oc1yWjMnVC2QOdLsFzcVk" + "ROhgMH/nHfFeXFlvY5IYMXqhbEC37LjE52RtX5KHv4FLYxxZCHduAwO8UTPa603XzrJ0VTMJ6Hso" + "9+Ql76cGxPtIPcYm8IfqIY22as3NlKO4eMbiur9GLvuC57eql8vROaxGy8y657gc6kZMUyQOC+HG" + "a5M3DTFpjl4V6HHbXHhMNEk9eXHnrZwYVOJmOgdgIrNNHOyD4kE+k21C7rUHhLAwK84wKL/tW4k9" + "xnhOJK/L1RmycRIFWwXVi3u/3vi49bzdZsRLn73MdQkTe5p8oNZzG9sxg76u67ua6+99TMZYE1ay" + "5JCYgbr85KbRsoX9Hd5XBcSNzROKJl0To2tAF8eTTMRlhEy7JZyTF2M9877juNaregVwE3Tp+a/J" + "ACeNMyrxOQItNDam7a5dgBohpM8oJdEFqqj/S9BU7H5sR0XYo8TyIe1BV9zR5ZC/23fj5l5zkrri" + "TCMgMbvt95JUGOT0gSzxBMmhV+ZLxpmVz3M5P2pXX0DXGTKfuHSiBWrh1GAQL4BOVpuKtyXlH1/9" + "55/xY25W0fpLzMiQJV7jf6W69LU0FAFWFH9uuwf/sFph0S1QQXcQSfpYmWPMi1gx/IgIbvT1xSuI" + "6vajgFqv6ctiVbFAJ6zmcnGd6e33+Ao9pmjs5JPZP3rtAYd6+PxtlwUbGLZuqIVK4o68LEISDfvm" + "nGlk4/1+S5CILKVqTC6Ja8ojwUjjsNSJbZwHue3pOkmJQUNtuK6kDOYXgiMRLURbrYLyen0azWw8" + "C5/nPs5J4pN+irD/hhD6cupCnUJmzMw30u8+LOCN6GaM5fdCTQ2uQKF7quYuD+gR3lLNOqq7KAAA" + "AAEABVguNTA5AAACJTCCAiEwggGKoAMCAQICAWQwDQYJKoZIhvcNAQEFBQAwUzEYMBYGA1UEAwwP" + "UmliYm9uVGVzdFJvb3QxMQswCQYDVQQLDAJJVDEQMA4GA1UECgwHTmV0ZmxpeDELMAkGA1UECAwC" + "Q0ExCzAJBgNVBAYTAlVTMCAXDTEzMDkwNjE3MjUyMloYDzIxMTMwODEzMTcyNTIyWjBYMR0wGwYD" + "VQQDDBRSaWJib25UZXN0RW5kRW50aXR5MTELMAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgx" + "CzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAydqk" + "AJuUcSF8dpUbNJWl+G1usgHtEFEbOMm54N/ZqGC7iSYs6EXfeoEyiHrMw/hdCKACERq2vuiuqan8" + "h6z65/DXIiHUyykGb/Z4NK1I0aCQLZG4Ek3sERilILWyy2NRpjUrvqDPr/mQgymXqpuYhSD81jHx" + "F84AOpTrnGsY7/sCAwEAATANBgkqhkiG9w0BAQUFAAOBgQAjvtRKNhb1R6XIuWaOxJ0XDLine464" + "Ie7LDfkE/KB43oE4MswjRh7nR9q6C73oa6TlIXmW6ysyKPp0vAyWHlq/zZhL3gNQ6faHuYHqas5s" + "nJQgvQpHAQh4VXRyZt1K8ZdsHg3Qbd4APTL0aRVQkxDt+Dxd6AsoRMKmO/c5CRwUFIV/CK7k5VSh" + "Sl5PRtH3PVj2vp84"; // Keystore type: JKS // Keystore provider: SUN // // Your keystore contains 1 entry // // Alias name: ribbon_key // Creation date: Sep 6, 2013 // Entry type: PrivateKeyEntry // Certificate chain length: 1 // Certificate[1]: // Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestEndEntity2 // Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2 // Serial number: 64 // Valid from: Fri Sep 06 10:26:22 PDT 2013 until: Sun Aug 13 10:26:22 PDT 2113 // Certificate fingerprints: // MD5: C3:AF:6A:DB:18:ED:70:22:83:73:9A:A5:DB:58:6D:04 // SHA1: B7:D4:F0:87:A8:4E:49:0A:91:B1:7B:62:28:CA:A2:4A:0E:AE:40:CC // Signature algorithm name: SHA1withRSA // Version: 3 // // // public static final String TEST_KS2 = "/u3+7QAAAAIAAAABAAAAAQAKcmliYm9uX2tleQAAAUD0T3bNAAACuzCCArcwDgYKKwYBBAEqAhEB" + "AQUABIICoysDP4inwmxxKZkS8EYMW3DCJCD1AmpwFHxJIzo2v9fMysg+vjKxsrvVyKG23ZcHcznI" + "ftmrEpriCCUZp+NNAf0EJWVAIzGenwrsd0+rI5I96gBOh9slJUzgucn7164R3XKNKk+VWcwGJRh+" + "IuHxVrwFN025pfhlBJXNGJg4ZlzB7ZwcQPYblBzhLbhS3vJ1Vc46pEYWpnjxmHaDSetaQIcueAp8" + "HnTUkFMXJ6t51N0u9QMPhBH7p7N8tNjaa5noSdxhSl/2Znj6r04NwQU1qX2n4rSWEnYaW1qOVkgx" + "YrQzxI2kSHZfQDM2T918UikboQvAS1aX4h5P3gVCDKLr3EOO6UYO0ZgLHUr/DZrhVKd1KAhnzaJ8" + "BABxot2ES7Zu5EzY9goiaYDA2/bkURmt0zDdKpeORb7r59XBZUm/8D80naaNnE45W/gBA9bCiDu3" + "R99xie447c7ZX9Jio25yil3ncv+npBO1ozc5QIgQnbEfxbbwii3//shvPT6oxYPrcwWBXnaJNC5w" + "2HDpCTXJZNucyjnNVVxC7p1ANNnvvZhgC0+GpEqmf/BW+fb9Qu+AXe0/h4Vnoe/Zs92vPDehpaKy" + "oe+jBlUNiW2bpR88DSqxVcIu1DemlgzPa1Unzod0FdrOr/272bJnB2zAo4OBaBSv3KNf/rsMKjsU" + "X2Po77+S+PKoQkqd8KJFpmLEb0vxig9JsrTDJXLf4ebeSA1W7+mBotimMrp646PA3NciMSbS4csh" + "A7o/dBYhHlEosVgThm1JknIKhemf+FZsOzR3bJDT1oXJ/GhYpfzlCLyVFBeVP0KRnhih4xO0MEO7" + "Q21DBaTTqAvUo7Iv3/F3mGMOanLcLgoRoq3moQ7FhfCDRtRAPA1qT2+pxPG5wqlGeYc6McOvogAA" + "AAEABVguNTA5AAACJTCCAiEwggGKoAMCAQICAWQwDQYJKoZIhvcNAQEFBQAwUzEYMBYGA1UEAwwP" + "UmliYm9uVGVzdFJvb3QyMQswCQYDVQQLDAJJVDEQMA4GA1UECgwHTmV0ZmxpeDELMAkGA1UECAwC" + "Q0ExCzAJBgNVBAYTAlVTMCAXDTEzMDkwNjE3MjYyMloYDzIxMTMwODEzMTcyNjIyWjBYMR0wGwYD" + "VQQDDBRSaWJib25UZXN0RW5kRW50aXR5MjELMAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgx" + "CzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtOvK" + "fBMC/oMo4xf4eYGN7hTNn+IywaSaVYndqECIfuznoIqRKSbeCKPSGs4CN1D+u3E2UoXcsDmTguHU" + "fokDA7sLUu8wD5ndAXfCkP3gXlFtUpNz/jPaXDsMFntTn2BdLKccxRxNwtwC0zzwIdtx9pw/Ru0g" + "NXIQnPi50aql5WcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQCYWM2ZdBjG3jCvMw/RkebMLkEDRxVM" + "XU63Ygo+iCZUk8V8d0/S48j8Nk/hhVGHljsHqE/dByEF77X6uHaDGtt3Xwe+AYPofoJukh89jKnT" + "jEDtLF+y5AVfz6b2z3TnJcuigMr4ZtBFv18R00KLnVAznl/waXG8ix44IL5ss6nRZBJE4jr+ZMG9" + "9I4P1YhySxo3Qd3g"; private static String SERVICE_URI1; private static String SERVICE_URI2; private static SimpleSSLTestServer testServer1; private static SimpleSSLTestServer testServer2; private static File FILE_TS1; private static File FILE_KS1; private static File FILE_TS2; private static File FILE_KS2; public static final String PASSWORD = "changeit"; @BeforeClass public static void init() throws Exception { // setup server 1, will use first keystore/truststore with client auth // jks format byte[] sampleTruststore1 = Base64.decode(TEST_TS1); byte[] sampleKeystore1 = Base64.decode(TEST_KS1); FILE_KS1 = File.createTempFile("SecureGetTest1", ".keystore"); FILE_TS1 = File.createTempFile("SecureGetTest1", ".truststore"); FileOutputStream keystoreFileOut = new FileOutputStream(FILE_KS1); try { keystoreFileOut.write(sampleKeystore1); } finally { keystoreFileOut.close(); } FileOutputStream truststoreFileOut = new FileOutputStream(FILE_TS1); try { truststoreFileOut.write(sampleTruststore1); } finally { truststoreFileOut.close(); } try{ testServer1 = new SimpleSSLTestServer(FILE_TS1, PASSWORD, FILE_KS1, PASSWORD, true); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } SERVICE_URI1 = "https://127.0.0.1:" + testServer1.getPort() + "/"; // setup server 2, will use second keystore truststore without client auth // jks format byte[] sampleTruststore2 = Base64.decode(TEST_TS2); byte[] sampleKeystore2 = Base64.decode(TEST_KS2); FILE_KS2 = File.createTempFile("SecureGetTest2", ".keystore"); FILE_TS2 = File.createTempFile("SecureGetTest2", ".truststore"); keystoreFileOut = new FileOutputStream(FILE_KS2); try { keystoreFileOut.write(sampleKeystore2); } finally { keystoreFileOut.close(); } truststoreFileOut = new FileOutputStream(FILE_TS2); try { truststoreFileOut.write(sampleTruststore2); } finally { truststoreFileOut.close(); } try{ testServer2 = new SimpleSSLTestServer(FILE_TS2, PASSWORD, FILE_KS2, PASSWORD, false); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } SERVICE_URI2 = "https://127.0.0.1:" + testServer2.getPort() + "/"; } @AfterClass public static void shutDown(){ try{ testServer1.close(); }catch(Exception e){ e.printStackTrace(); } try{ testServer2.close(); }catch(Exception e){ e.printStackTrace(); } } @Test public void testSunnyDay() throws Exception { AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = "GetPostSecureTest" + ".testSunnyDay"; String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer1.getPort())); cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD); RestClient rc = (RestClient) ClientFactory.getNamedClient(name); testServer1.accept(); URI getUri = new URI(SERVICE_URI1 + "test/"); HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build(); HttpResponse response = rc.execute(request); assertEquals(200, response.getStatus()); } @Test public void testSunnyDayNoClientAuth() throws Exception{ AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = "GetPostSecureTest" + ".testSunnyDayNoClientAuth"; String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort())); cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS2.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD); RestClient rc = (RestClient) ClientFactory.getNamedClient(name); testServer2.accept(); URI getUri = new URI(SERVICE_URI2 + "test/"); HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build(); HttpResponse response = rc.execute(request); assertEquals(200, response.getStatus()); } @Test public void testFailsWithHostNameValidationOn() throws Exception { AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = "GetPostSecureTest" + ".testFailsWithHostNameValidationOn"; String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort())); cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "true"); // <-- cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath()); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD); RestClient rc = (RestClient) ClientFactory.getNamedClient(name); testServer1.accept(); URI getUri = new URI(SERVICE_URI1 + "test/"); MultivaluedMapImpl params = new MultivaluedMapImpl(); params.add("name", "test"); HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build(); try{ rc.execute(request); fail("expecting ssl hostname validation error"); }catch(ClientHandlerException che){ assertTrue(che.getMessage().indexOf("hostname in certificate didn't match") > -1); } } @Test public void testClientRejectsWrongServer() throws Exception{ AbstractConfiguration cm = ConfigurationManager.getConfigInstance(); String name = "GetPostSecureTest" + ".testClientRejectsWrongServer"; String configPrefix = name + "." + "ribbon"; cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort())); cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false"); cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath()); // <-- cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD); RestClient rc = (RestClient) ClientFactory.getNamedClient(name); testServer2.accept(); URI getUri = new URI(SERVICE_URI2 + "test/"); HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build(); try{ rc.execute(request); fail("expecting ssl hostname validation error"); }catch(ClientHandlerException che){ assertTrue(che.getMessage().indexOf("peer not authenticated") > -1); } } }
7,196
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/PrimeConnectionsTest.java
package com.netflix.niws.client.http; import static org.junit.Assert.*; import java.util.Arrays; import java.util.List; import java.util.Random; import org.apache.commons.configuration.Configuration; import org.junit.*; import com.netflix.client.ClientFactory; import com.netflix.client.PrimeConnections.PrimeConnectionEndStats; //import com.netflix.client.PrimeConnections.PrimeConnectionEndStats; import com.netflix.client.config.IClientConfig; import com.netflix.config.ConfigurationManager; import com.netflix.loadbalancer.AbstractServerList; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; import com.sun.jersey.api.container.httpserver.HttpServerFactory; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.net.httpserver.HttpServer; public class PrimeConnectionsTest { private static String SERVICE_URI; private static int port = (new Random()).nextInt(1000) + 4000; private static HttpServer server = null; private static final int SMALL_FIXED_SERVER_LIST_SIZE = 10; private static final int LARGE_FIXED_SERVER_LIST_SIZE = 200; public static class LargeFixedServerList extends FixedServerList { public LargeFixedServerList() { super(200); } } public static class SmallFixedServerList extends FixedServerList { public SmallFixedServerList() { super(10); } } public static class FixedServerList extends AbstractServerList<Server> { private Server testServer = new Server("localhost", port); private List<Server> testServers; public FixedServerList(int repeatCount) { Server list[] = new Server[repeatCount]; for (int ii = 0; ii < list.length; ii++) { list[ii] = testServer; } testServers = Arrays.asList(list); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } @Override public List<Server> getInitialListOfServers() { return testServers; } @Override public List<Server> getUpdatedListOfServers() { return testServers; } } @BeforeClass public static void setup(){ PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.client.http"); SERVICE_URI = "http://localhost:" + port + "/"; try{ server = HttpServerFactory.create(SERVICE_URI, resourceConfig); server.start(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testPrimeConnectionsSmallPool() throws Exception { Configuration config = ConfigurationManager.getConfigInstance(); config.setProperty("PrimeConnectionsTest1.ribbon.NFLoadBalancerClassName", com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName()); config.setProperty("PrimeConnectionsTest1.ribbon.NIWSServerListClassName", SmallFixedServerList.class.getName()); config.setProperty("PrimeConnectionsTest1.ribbon.EnablePrimeConnections", "true"); DynamicServerListLoadBalancer<Server> lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("PrimeConnectionsTest1"); PrimeConnectionEndStats stats = lb.getPrimeConnections().getEndStats(); assertEquals(stats.success, SMALL_FIXED_SERVER_LIST_SIZE); } @Test public void testPrimeConnectionsLargePool() throws Exception { Configuration config = ConfigurationManager.getConfigInstance(); config.setProperty("PrimeConnectionsTest2.ribbon.NFLoadBalancerClassName", com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName()); config.setProperty("PrimeConnectionsTest2.ribbon.NIWSServerListClassName", LargeFixedServerList.class.getName()); config.setProperty("PrimeConnectionsTest2.ribbon.EnablePrimeConnections", "true"); DynamicServerListLoadBalancer<Server> lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("PrimeConnectionsTest2"); PrimeConnectionEndStats stats = lb.getPrimeConnections().getEndStats(); assertEquals(stats.success, LARGE_FIXED_SERVER_LIST_SIZE); } @AfterClass public static void shutDown() { server.stop(0); } }
7,197
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/http4/NFHttpClientTest.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.http4; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.util.EntityUtils; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Test; import com.netflix.client.testutil.MockHttpServer; public class NFHttpClientTest { @ClassRule public static MockHttpServer server = new MockHttpServer(); @Test public void testDefaultClient() throws Exception { NFHttpClient client = NFHttpClientFactory.getDefaultClient(); HttpGet get = new HttpGet(server.getServerURI()); // uri // this is not the overridable method HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); String contentStr = EntityUtils.toString(entity); assertTrue(contentStr.length() > 0); } @Test public void testNFHttpClient() throws Exception { NFHttpClient client = NFHttpClientFactory.getNFHttpClient("localhost", server.getServerPort()); ThreadSafeClientConnManager cm = (ThreadSafeClientConnManager) client.getConnectionManager(); cm.setDefaultMaxPerRoute(10); HttpGet get = new HttpGet(server.getServerURI()); ResponseHandler<Integer> respHandler = new ResponseHandler<Integer>(){ public Integer handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); String contentStr = EntityUtils.toString(entity); return contentStr.length(); } }; long contentLen = client.execute(get, respHandler); assertTrue(contentLen > 0); } @Ignore public void testMultiThreadedClient() throws Exception { NFHttpClient client = (NFHttpClient) NFHttpClientFactory .getNFHttpClient("hc.apache.org", 80); ThreadSafeClientConnManager cm = (ThreadSafeClientConnManager) client.getConnectionManager(); cm.setDefaultMaxPerRoute(10); HttpHost target = new HttpHost("hc.apache.org", 80); // create an array of URIs to perform GETs on String[] urisToGet = { "/", "/httpclient-3.x/status.html", "/httpclient-3.x/methods/", "http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/" }; // create a thread for each URI GetThread[] threads = new GetThread[urisToGet.length]; for (int i = 0; i < threads.length; i++) { HttpGet get = new HttpGet(urisToGet[i]); threads[i] = new GetThread(client, target, get, i + 1); } // start the threads for (int j = 0; j < threads.length; j++) { threads[j].start(); } } /** * A thread that performs a GET. */ static class GetThread extends Thread { private HttpClient httpClient; private HttpHost target; private HttpGet request; private int id; public GetThread(HttpClient httpClient, HttpHost target, HttpGet request, int id) { this.httpClient = httpClient; this.target = target; this.request = request; this.id = id; } /** * Executes the GetMethod and prints some satus information. */ public void run() { try { System.out.println(id + " - about to get something from " + request.getURI()); // execute the method HttpResponse resp = httpClient.execute(target, request); System.out.println(id + " - get executed"); // get the response body as an array of bytes byte[] bytes = EntityUtils.toByteArray(resp.getEntity()); System.out.println(id + " - " + bytes.length + " bytes read"); } catch (Exception e) { System.out.println(id + " - error: " + e); } finally { System.out.println(id + " - connection released"); } } } }
7,198
0
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix
Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/http4/NamedConnectionPoolTest.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.http4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.util.EntityUtils; import org.junit.ClassRule; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.http.HttpRequest; import com.netflix.client.testutil.MockHttpServer; import com.netflix.config.ConfigurationManager; import com.netflix.niws.client.http.RestClient; public class NamedConnectionPoolTest { @ClassRule public static MockHttpServer server = new MockHttpServer(); @Test public void testConnectionPoolCounters() throws Exception { // LogManager.getRootLogger().setLevel((Level)Level.DEBUG); NFHttpClient client = NFHttpClientFactory.getNamedNFHttpClient("google-NamedConnectionPoolTest"); assertTrue(client.getConnectionManager() instanceof MonitoredConnectionManager); MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) client.getConnectionManager(); connectionPoolManager.setDefaultMaxPerRoute(100); connectionPoolManager.setMaxTotal(200); assertTrue(connectionPoolManager.getConnectionPool() instanceof NamedConnectionPool); NamedConnectionPool connectionPool = (NamedConnectionPool) connectionPoolManager.getConnectionPool(); System.out.println("Entries created: " + connectionPool.getCreatedEntryCount()); System.out.println("Requests count: " + connectionPool.getRequestsCount()); System.out.println("Free entries: " + connectionPool.getFreeEntryCount()); System.out.println("Deleted :" + connectionPool.getDeleteCount()); System.out.println("Released: " + connectionPool.getReleaseCount()); for (int i = 0; i < 10; i++) { HttpUriRequest request = new HttpGet(server.getServerPath("/")); HttpResponse response = client.execute(request); EntityUtils.consume(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); assertTrue(statusCode == 200 || statusCode == 302); Thread.sleep(500); } System.out.println("Entries created: " + connectionPool.getCreatedEntryCount()); System.out.println("Requests count: " + connectionPool.getRequestsCount()); System.out.println("Free entries: " + connectionPool.getFreeEntryCount()); System.out.println("Deleted :" + connectionPool.getDeleteCount()); System.out.println("Released: " + connectionPool.getReleaseCount()); assertTrue(connectionPool.getCreatedEntryCount() >= 1); assertTrue(connectionPool.getRequestsCount() >= 10); assertTrue(connectionPool.getFreeEntryCount() >= 9); assertEquals(0, connectionPool.getDeleteCount()); assertEquals(connectionPool.getReleaseCount(), connectionPool.getRequestsCount()); assertEquals(connectionPool.getRequestsCount(), connectionPool.getCreatedEntryCount() + connectionPool.getFreeEntryCount()); ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxTotalHttpConnections.key(), "50"); ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxHttpConnectionsPerHost.key(), "10"); assertEquals(50, connectionPoolManager.getMaxTotal()); assertEquals(10, connectionPoolManager.getDefaultMaxPerRoute()); } @Test public void testConnectionPoolCleaner() throws Exception { // LogManager.getRootLogger().setLevel((Level)Level.DEBUG); ConfigurationManager.getConfigInstance().setProperty("ConnectionPoolCleanerTest.ribbon." + CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, "100"); ConfigurationManager.getConfigInstance().setProperty("ConnectionPoolCleanerTest.ribbon." + CommonClientConfigKey.ConnectionCleanerRepeatInterval, "500"); RestClient client = (RestClient) ClientFactory.getNamedClient("ConnectionPoolCleanerTest"); NFHttpClient httpclient = NFHttpClientFactory.getNamedNFHttpClient("ConnectionPoolCleanerTest"); assertNotNull(httpclient); com.netflix.client.http.HttpResponse response = null; try { response = client.execute(HttpRequest.newBuilder().uri(server.getServerPath("/")).build()); } finally { if (response != null) { response.close(); } } MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) httpclient.getConnectionManager(); Thread.sleep(2000); assertEquals(0, connectionPoolManager.getConnectionsInPool()); client.shutdown(); } }
7,199