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/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration/collapser/BasicCollapserPropertiesTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.configuration.collapser;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.MAX_REQUESTS_IN_BATCH;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.TIMER_DELAY_IN_MILLISECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil
*/
public abstract class BasicCollapserPropertiesTest extends BasicHystrixTest {
private UserService userService;
protected abstract UserService createUserService();
@Before
public void setUp() throws Exception {
userService = createUserService();
}
@Test
public void testCollapser() throws ExecutionException, InterruptedException {
User u1 = userService.getUser("1");
User u2 = userService.getUser("2");
User u3 = userService.getUser("3");
User u4 = userService.getUser("4");
assertEquals("name: 1", u1.getName());
assertEquals("name: 2", u2.getName());
assertEquals("name: 3", u3.getName());
assertEquals("name: 4", u4.getName());
assertEquals(4, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("getUsers", command.getCommandKey().name());
// confirm that it was a COLLAPSED command execution
assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
// and that it was successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
public static class UserService {
@HystrixCollapser(
batchMethod = "getUsers",
collapserKey = "GetUserCollapser", collapserProperties = {
@HystrixProperty(name = TIMER_DELAY_IN_MILLISECONDS, value = "200"),
@HystrixProperty(name = MAX_REQUESTS_IN_BATCH, value = "1"),
})
public User getUser(String id) {
return null;
}
@HystrixCommand
public List<User> getUsers(List<String> ids) {
List<User> users = new ArrayList<User>();
for (String id : ids) {
users.add(new User(id, "name: " + id));
}
return users;
}
}
}
| 4,400 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration/command/BasicCommandPropertiesTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.configuration.command;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.CIRCUIT_BREAKER_FORCE_CLOSED;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.CIRCUIT_BREAKER_FORCE_OPEN;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.EXECUTION_TIMEOUT_ENABLED;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.FALLBACK_ENABLED;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.METRICS_HEALTH_SNAPSHOT_INTERVAL_IN_MILLISECONDS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.METRICS_ROLLING_PERCENTILE_BUCKET_SIZE;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.METRICS_ROLLING_PERCENTILE_ENABLED;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.METRICS_ROLLING_PERCENTILE_NUM_BUCKETS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.METRICS_ROLLING_PERCENTILE_TIME_IN_MILLISECONDS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.METRICS_ROLLING_STATS_NUM_BUCKETS;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.REQUEST_CACHE_ENABLED;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.REQUEST_LOG_ENABLED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil
*/
public abstract class BasicCommandPropertiesTest extends BasicHystrixTest {
private UserService userService;
protected abstract UserService createUserService();
@Before
public void setUp() throws Exception {
userService = createUserService();
}
@Test
public void testGetUser() throws NoSuchFieldException, IllegalAccessException {
User u1 = userService.getUser("1", "name: ");
assertEquals("name: 1", u1.getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("GetUserCommand", command.getCommandKey().name());
assertEquals("UserGroupKey", command.getCommandGroup().name());
assertEquals("Test", command.getThreadPoolKey().name());
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
// assert properties
assertEquals(110, command.getProperties().executionTimeoutInMilliseconds().get().intValue());
assertEquals(false, command.getProperties().executionIsolationThreadInterruptOnTimeout().get());
HystrixThreadPoolProperties properties = getThreadPoolProperties(command);
assertEquals(30, (int) properties.coreSize().get());
assertEquals(35, (int) properties.maximumSize().get());
assertEquals(true, properties.getAllowMaximumSizeToDivergeFromCoreSize().get());
assertEquals(101, (int) properties.maxQueueSize().get());
assertEquals(2, (int) properties.keepAliveTimeMinutes().get());
assertEquals(15, (int) properties.queueSizeRejectionThreshold().get());
assertEquals(1440, (int) properties.metricsRollingStatisticalWindowInMilliseconds().get());
assertEquals(12, (int) properties.metricsRollingStatisticalWindowBuckets().get());
}
@Test
public void testGetUserDefaultPropertiesValues() {
User u1 = userService.getUserDefProperties("1", "name: ");
assertEquals("name: 1", u1.getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("getUserDefProperties", command.getCommandKey().name());
assertEquals("UserService", command.getCommandGroup().name());
assertEquals("UserService", command.getThreadPoolKey().name());
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testGetUserDefGroupKeyWithSpecificThreadPoolKey() {
User u1 = userService.getUserDefGroupKeyWithSpecificThreadPoolKey("1", "name: ");
assertEquals("name: 1", u1.getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("getUserDefGroupKeyWithSpecificThreadPoolKey", command.getCommandKey().name());
assertEquals("UserService", command.getCommandGroup().name());
assertEquals("CustomThreadPool", command.getThreadPoolKey().name());
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testHystrixCommandProperties() {
User u1 = userService.getUsingAllCommandProperties("1", "name: ");
assertEquals("name: 1", u1.getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
// assert properties
assertEquals(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE, command.getProperties().executionIsolationStrategy().get());
assertEquals(500, command.getProperties().executionTimeoutInMilliseconds().get().intValue());
assertEquals(true, command.getProperties().executionTimeoutEnabled().get().booleanValue());
assertEquals(false, command.getProperties().executionIsolationThreadInterruptOnTimeout().get().booleanValue());
assertEquals(10, command.getProperties().executionIsolationSemaphoreMaxConcurrentRequests().get().intValue());
assertEquals(15, command.getProperties().fallbackIsolationSemaphoreMaxConcurrentRequests().get().intValue());
assertEquals(false, command.getProperties().fallbackEnabled().get().booleanValue());
assertEquals(false, command.getProperties().circuitBreakerEnabled().get().booleanValue());
assertEquals(30, command.getProperties().circuitBreakerRequestVolumeThreshold().get().intValue());
assertEquals(250, command.getProperties().circuitBreakerSleepWindowInMilliseconds().get().intValue());
assertEquals(60, command.getProperties().circuitBreakerErrorThresholdPercentage().get().intValue());
assertEquals(false, command.getProperties().circuitBreakerForceOpen().get().booleanValue());
assertEquals(true, command.getProperties().circuitBreakerForceClosed().get().booleanValue());
assertEquals(false, command.getProperties().metricsRollingPercentileEnabled().get().booleanValue());
assertEquals(400, command.getProperties().metricsRollingPercentileWindowInMilliseconds().get().intValue());
assertEquals(5, command.getProperties().metricsRollingPercentileWindowBuckets().get().intValue());
assertEquals(6, command.getProperties().metricsRollingPercentileBucketSize().get().intValue());
assertEquals(10, command.getProperties().metricsRollingStatisticalWindowBuckets().get().intValue());
assertEquals(500, command.getProperties().metricsRollingStatisticalWindowInMilliseconds().get().intValue());
assertEquals(312, command.getProperties().metricsHealthSnapshotIntervalInMilliseconds().get().intValue());
assertEquals(false, command.getProperties().requestCacheEnabled().get().booleanValue());
assertEquals(true, command.getProperties().requestLogEnabled().get().booleanValue());
}
public static class UserService {
@HystrixCommand(commandKey = "GetUserCommand", groupKey = "UserGroupKey", threadPoolKey = "Test",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "110"),
@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "false")
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"),
@HystrixProperty(name = "maximumSize", value = "35"),
@HystrixProperty(name = "allowMaximumSizeToDivergeFromCoreSize", value = "true"),
@HystrixProperty(name = "maxQueueSize", value = "101"),
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1440")
})
public User getUser(String id, String name) {
return new User(id, name + id); // it should be network call
}
@HystrixCommand
public User getUserDefProperties(String id, String name) {
return new User(id, name + id); // it should be network call
}
@HystrixCommand(threadPoolKey = "CustomThreadPool")
public User getUserDefGroupKeyWithSpecificThreadPoolKey(String id, String name) {
return new User(id, name + id); // it should be network call
}
@HystrixCommand(
commandProperties = {
@HystrixProperty(name = EXECUTION_ISOLATION_STRATEGY, value = "SEMAPHORE"),
@HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "500"),
@HystrixProperty(name = EXECUTION_TIMEOUT_ENABLED, value = "true"),
@HystrixProperty(name = EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT, value = "false"),
@HystrixProperty(name = EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "10"),
@HystrixProperty(name = FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "15"),
@HystrixProperty(name = FALLBACK_ENABLED, value = "false"),
@HystrixProperty(name = CIRCUIT_BREAKER_ENABLED, value = "false"),
@HystrixProperty(name = CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "30"),
@HystrixProperty(name = CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "250"),
@HystrixProperty(name = CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "60"),
@HystrixProperty(name = CIRCUIT_BREAKER_FORCE_OPEN, value = "false"),
@HystrixProperty(name = CIRCUIT_BREAKER_FORCE_CLOSED, value = "true"),
@HystrixProperty(name = METRICS_ROLLING_PERCENTILE_ENABLED, value = "false"),
@HystrixProperty(name = METRICS_ROLLING_PERCENTILE_TIME_IN_MILLISECONDS, value = "400"),
@HystrixProperty(name = METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, value = "500"),
@HystrixProperty(name = METRICS_ROLLING_STATS_NUM_BUCKETS, value = "10"),
@HystrixProperty(name = METRICS_ROLLING_PERCENTILE_NUM_BUCKETS, value = "5"),
@HystrixProperty(name = METRICS_ROLLING_PERCENTILE_BUCKET_SIZE, value = "6"),
@HystrixProperty(name = METRICS_HEALTH_SNAPSHOT_INTERVAL_IN_MILLISECONDS, value = "312"),
@HystrixProperty(name = REQUEST_CACHE_ENABLED, value = "false"),
@HystrixProperty(name = REQUEST_LOG_ENABLED, value = "true")
}
)
public User getUsingAllCommandProperties(String id, String name) {
return new User(id, name + id); // it should be network call
}
}
}
| 4,401 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration/command/BasicCommandDefaultPropertiesTest.java | package com.netflix.hystrix.contrib.javanica.test.common.configuration.command;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS;
import static org.junit.Assert.assertEquals;
/**
* Created by dmgcodevil.
*/
public abstract class BasicCommandDefaultPropertiesTest extends BasicHystrixTest {
private Service service;
protected abstract Service createService();
@Before
public void setUp() throws Exception {
service = createService();
}
@Test
public void testCommandInheritsDefaultGroupKey() {
service.commandInheritsDefaultProperties();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("DefaultGroupKey", command.getCommandGroup().name());
}
@Test
public void testCommandOverridesDefaultGroupKey() {
service.commandOverridesGroupKey();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("SpecificGroupKey", command.getCommandGroup().name());
}
@Test
public void testCommandInheritsDefaultThreadPoolKey() {
service.commandInheritsDefaultProperties();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("DefaultThreadPoolKey", command.getThreadPoolKey().name());
}
@Test
public void testCommandOverridesDefaultThreadPoolKey() {
service.commandOverridesThreadPoolKey();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("SpecificThreadPoolKey", command.getThreadPoolKey().name());
}
@Test
public void testCommandInheritsDefaultCommandProperties() {
service.commandInheritsDefaultProperties();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals(456, command.getProperties().executionTimeoutInMilliseconds().get().intValue());
}
@Test
public void testCommandOverridesDefaultCommandProperties() {
service.commandOverridesDefaultCommandProperties();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals(654, command.getProperties().executionTimeoutInMilliseconds().get().intValue());
}
@Test
public void testCommandInheritsThreadPollProperties() {
service.commandInheritsDefaultProperties();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
HystrixThreadPoolProperties properties = getThreadPoolProperties(command);
assertEquals(123, properties.maxQueueSize().get().intValue());
}
@Test
public void testCommandOverridesDefaultThreadPollProperties() {
service.commandOverridesDefaultThreadPoolProperties();
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
HystrixThreadPoolProperties properties = getThreadPoolProperties(command);
assertEquals(321, properties.maxQueueSize().get().intValue());
}
@DefaultProperties(groupKey = "DefaultGroupKey", threadPoolKey = "DefaultThreadPoolKey",
commandProperties = {
@HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "456")
},
threadPoolProperties = {
@HystrixProperty(name = "maxQueueSize", value = "123")
}
)
public static class Service {
@HystrixCommand
public Object commandInheritsDefaultProperties() {
return null;
}
@HystrixCommand(groupKey = "SpecificGroupKey")
public Object commandOverridesGroupKey() {
return null;
}
@HystrixCommand(threadPoolKey = "SpecificThreadPoolKey")
public Object commandOverridesThreadPoolKey() {
return null;
}
@HystrixCommand(commandProperties = {
@HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "654")
})
public Object commandOverridesDefaultCommandProperties() {
return null;
}
@HystrixCommand(threadPoolProperties = {
@HystrixProperty(name = "maxQueueSize", value = "321")
})
public Object commandOverridesDefaultThreadPoolProperties() {
return null;
}
}
}
| 4,402 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/cache/BasicCacheTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.cache;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.netflix.hystrix.contrib.javanica.exception.HystrixCachingException;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.Profile;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getLastExecutedCommand;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil
*/
public abstract class BasicCacheTest extends BasicHystrixTest {
private UserService userService;
@Before
public void setUp() throws Exception {
userService = createUserService();
}
protected abstract UserService createUserService();
/**
* Get-Set-Get with Request Cache Invalidation Test.
* <p/>
* given:
* command to get user by id, see {@link UserService#getUserById(String)}
* command to update user, see {@link UserService#update(com.netflix.hystrix.contrib.javanica.test.common.domain.User)}
* <p/>
* when:
* 1. call {@link UserService#getUserById(String)}
* 2. call {@link UserService#getUserById(String)}
* 3. call {@link UserService#update(com.netflix.hystrix.contrib.javanica.test.common.domain.User)}
* 4. call {@link UserService#getUserById(String)}
* <p/>
* then:
* at the first time "getUserById" command shouldn't retrieve value from cache
* at the second time "getUserById" command should retrieve value from cache
* "update" method should update an user and flush cache related to "getUserById" command
* after "update" method execution "getUserById" command shouldn't retrieve value from cache
*/
@Test
public void testGetSetGetUserCache_givenTwoCommands() {
User user = userService.getUserById("1");
HystrixInvokableInfo<?> getUserByIdCommand = getLastExecutedCommand();
// this is the first time we've executed this command with
// the value of "1" so it should not be from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
assertEquals("1", user.getId());
assertEquals("name", user.getName()); // initial name value
user = userService.getUserById("1");
assertEquals("1", user.getId());
getUserByIdCommand = getLastExecutedCommand();
// this is the second time we've executed this command with
// the same value so it should return from cache
assertTrue(getUserByIdCommand.isResponseFromCache());
assertEquals("name", user.getName()); // same name
// create new user with same id but with new name
user = new User("1", "new_name");
userService.update(user); // update the user
user = userService.getUserById("1");
getUserByIdCommand = getLastExecutedCommand();
// this is the first time we've executed this command after "update"
// method was invoked and a cache for "getUserById" command was flushed
// so the response should not be from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
assertEquals("1", user.getId());
assertEquals("new_name", user.getName());
// start a new request context
resetContext();
user = userService.getUserById("1");
getUserByIdCommand = getLastExecutedCommand();
assertEquals("1", user.getId());
// this is a new request context so this
// should not come from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
}
@Test
public void testGetSetGetUserCache_givenGetUserByEmailAndUpdateProfile() {
User user = userService.getUserByEmail("email");
HystrixInvokableInfo<?> getUserByIdCommand = getLastExecutedCommand();
// this is the first time we've executed this command with
// the value of "1" so it should not be from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
assertEquals("1", user.getId());
assertEquals("name", user.getName());
assertEquals("email", user.getProfile().getEmail()); // initial email value
user = userService.getUserByEmail("email");
assertEquals("1", user.getId());
getUserByIdCommand = getLastExecutedCommand();
// this is the second time we've executed this command with
// the same value so it should return from cache
assertTrue(getUserByIdCommand.isResponseFromCache());
assertEquals("email", user.getProfile().getEmail()); // same email
// create new user with same id but with new email
Profile profile = new Profile();
profile.setEmail("new_email");
user.setProfile(profile);
userService.updateProfile(user); // update the user profile
user = userService.getUserByEmail("new_email");
getUserByIdCommand = getLastExecutedCommand();
// this is the first time we've executed this command after "updateProfile"
// method was invoked and a cache for "getUserByEmail" command was flushed
// so the response should not be from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
assertEquals("1", user.getId());
assertEquals("name", user.getName());
assertEquals("new_email", user.getProfile().getEmail());
// start a new request context
resetContext();
user = userService.getUserByEmail("new_email");
getUserByIdCommand = getLastExecutedCommand();
assertEquals("1", user.getId());
// this is a new request context so this
// should not come from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
}
@Test
public void testGetSetGetUserCache_givenOneCommandAndOneMethodAnnotatedWithCacheRemove() {
// given
User user = userService.getUserById("1");
HystrixInvokableInfo<?> getUserByIdCommand = getLastExecutedCommand();
// this is the first time we've executed this command with
// the value of "1" so it should not be from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
assertEquals("1", user.getId());
assertEquals("name", user.getName()); // initial name value
user = userService.getUserById("1");
assertEquals("1", user.getId());
getUserByIdCommand = getLastExecutedCommand();
// this is the second time we've executed this command with
// the same value so it should return from cache
assertTrue(getUserByIdCommand.isResponseFromCache());
assertEquals("name", user.getName()); // same name
// when
userService.updateName("1", "new_name"); // update the user name
// then
user = userService.getUserById("1");
getUserByIdCommand = getLastExecutedCommand();
// this is the first time we've executed this command after "update"
// method was invoked and a cache for "getUserById" command was flushed
// so the response should not be from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
assertEquals("1", user.getId());
assertEquals("new_name", user.getName());
// start a new request context
resetContext();
user = userService.getUserById("1");
getUserByIdCommand = getLastExecutedCommand();
assertEquals("1", user.getId());
// this is a new request context so this
// should not come from cache
assertFalse(getUserByIdCommand.isResponseFromCache());
}
@Test(expected = HystrixCachingException.class)
public void testGetUser_givenWrongCacheKeyMethodReturnType_shouldThrowException() {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
User user = userService.getUserByName("name");
} finally {
context.shutdown();
}
}
@Test(expected = HystrixCachingException.class)
public void testGetUserByName_givenNonexistentCacheKeyMethod_shouldThrowException() {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
User user = userService.getUser();
} finally {
context.shutdown();
}
}
public static class UserService {
private Map<String, User> storage = new ConcurrentHashMap<String, User>();
@PostConstruct
public void init() {
User user = new User("1", "name");
Profile profile = new Profile();
profile.setEmail("email");
user.setProfile(profile);
storage.put("1", user);
}
@CacheResult
@HystrixCommand
public User getUserById(@CacheKey String id) {
return storage.get(id);
}
@CacheResult(cacheKeyMethod = "getUserByNameCacheKey")
@HystrixCommand
public User getUserByName(String name) {
return null;
}
private Long getUserByNameCacheKey() {
return 0L;
}
@CacheResult(cacheKeyMethod = "nonexistent")
@HystrixCommand
public User getUser() {
return null;
}
@CacheResult(cacheKeyMethod = "getUserByEmailCacheKey")
@HystrixCommand
public User getUserByEmail(final String email) {
return Iterables.tryFind(storage.values(), new Predicate<User>() {
@Override
public boolean apply(User input) {
return input.getProfile().getEmail().equalsIgnoreCase(email);
}
}).orNull();
}
private String getUserByEmailCacheKey(String email) {
return email;
}
@CacheRemove(commandKey = "getUserById")
@HystrixCommand
public void update(@CacheKey("id") User user) {
storage.put(user.getId(), user);
}
@CacheRemove(commandKey = "getUserByEmail")
@HystrixCommand
public void updateProfile(@CacheKey("profile.email") User user) {
storage.get(user.getId()).setProfile(user.getProfile());
}
@CacheRemove(commandKey = "getUserById")
public void updateName(@CacheKey String id, String name) {
storage.get(id).setName(name);
}
}
}
| 4,403 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/fallback/BasicCommandFallbackTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.fallback;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.Domain;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import org.apache.commons.lang3.Validate;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public abstract class BasicCommandFallbackTest extends BasicHystrixTest {
private UserService userService;
protected abstract UserService createUserService();
@Before
public void setUp() throws Exception {
userService = createUserService();
}
@Test
public void testGetUserAsyncWithFallback() throws ExecutionException, InterruptedException {
Future<User> f1 = userService.getUserAsync(" ", "name: ");
assertEquals("def", f1.get().getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("getUserAsync", command.getCommandKey().name());
// confirm that 'getUserAsync' command has failed
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that fallback waw successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetUserSyncWithFallback() {
User u1 = userService.getUserSync(" ", "name: ");
assertEquals("def", u1.getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("getUserSync", command.getCommandKey().name());
// confirm that command has failed
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that fallback was successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
/**
* * **************************** *
* * * TEST FALLBACK COMMANDS * *
* * **************************** *
*/
@Test
public void testGetUserAsyncWithFallbackCommand() throws ExecutionException, InterruptedException {
Future<User> f1 = userService.getUserAsyncFallbackCommand(" ", "name: ");
assertEquals("def", f1.get().getName());
assertEquals(3, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> getUserAsyncFallbackCommand = getHystrixCommandByKey(
"getUserAsyncFallbackCommand");
com.netflix.hystrix.HystrixInvokableInfo firstFallbackCommand = getHystrixCommandByKey("firstFallbackCommand");
com.netflix.hystrix.HystrixInvokableInfo secondFallbackCommand = getHystrixCommandByKey("secondFallbackCommand");
assertEquals("getUserAsyncFallbackCommand", getUserAsyncFallbackCommand.getCommandKey().name());
// confirm that command has failed
assertTrue(getUserAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// confirm that first fallback has failed
assertTrue(firstFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that second fallback was successful
assertTrue(secondFallbackCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetUserAsyncFallbackAsyncCommand() throws ExecutionException, InterruptedException {
Future<User> f1 = userService.getUserAsyncFallbackAsyncCommand(" ", "name: ");
assertEquals("def", f1.get().getName());
assertEquals(4, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> getUserAsyncFallbackAsyncCommand = getHystrixCommandByKey(
"getUserAsyncFallbackAsyncCommand");
com.netflix.hystrix.HystrixInvokableInfo firstAsyncFallbackCommand = getHystrixCommandByKey("firstAsyncFallbackCommand");
com.netflix.hystrix.HystrixInvokableInfo secondAsyncFallbackCommand = getHystrixCommandByKey("secondAsyncFallbackCommand");
com.netflix.hystrix.HystrixInvokableInfo thirdAsyncFallbackCommand = getHystrixCommandByKey("thirdAsyncFallbackCommand");
assertEquals("getUserAsyncFallbackAsyncCommand", getUserAsyncFallbackAsyncCommand.getCommandKey().name());
// confirm that command has failed
assertTrue(getUserAsyncFallbackAsyncCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// confirm that first fallback has failed
assertTrue(firstAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that second fallback was successful
assertTrue(secondAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(thirdAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(thirdAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetUserSyncWithFallbackCommand() {
User u1 = userService.getUserSyncFallbackCommand(" ", "name: ");
assertEquals("def", u1.getName());
assertEquals(3, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> getUserSyncFallbackCommand = getHystrixCommandByKey(
"getUserSyncFallbackCommand");
com.netflix.hystrix.HystrixInvokableInfo firstFallbackCommand = getHystrixCommandByKey("firstFallbackCommand");
com.netflix.hystrix.HystrixInvokableInfo secondFallbackCommand = getHystrixCommandByKey("secondFallbackCommand");
assertEquals("getUserSyncFallbackCommand", getUserSyncFallbackCommand.getCommandKey().name());
// confirm that command has failed
assertTrue(getUserSyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// confirm that first fallback has failed
assertTrue(firstFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that second fallback was successful
assertTrue(secondFallbackCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testAsyncCommandWithAsyncFallbackCommand() throws ExecutionException, InterruptedException {
Future<User> userFuture = userService.asyncCommandWithAsyncFallbackCommand("", "");
User user = userFuture.get();
assertEquals("def", user.getId());
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> asyncCommandWithAsyncFallbackCommand = getHystrixCommandByKey("asyncCommandWithAsyncFallbackCommand");
com.netflix.hystrix.HystrixInvokableInfo asyncFallbackCommand = getHystrixCommandByKey("asyncFallbackCommand");
// confirm that command has failed
assertTrue(asyncCommandWithAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(asyncCommandWithAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// and that second fallback was successful
assertTrue(asyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test(expected = FallbackDefinitionException.class)
public void testAsyncCommandWithAsyncFallback() {
userService.asyncCommandWithAsyncFallback("", "");
}
@Test(expected = FallbackDefinitionException.class)
public void testCommandWithWrongFallbackReturnType() {
userService.commandWithWrongFallbackReturnType("", "");
}
@Test(expected = FallbackDefinitionException.class)
public void testAsyncCommandWithWrongFallbackReturnType() {
userService.asyncCommandWithWrongFallbackReturnType("", "");
}
@Test(expected = FallbackDefinitionException.class)
public void testCommandWithWrongFallbackParams() {
userService.commandWithWrongFallbackParams("1", "2");
}
@Test(expected = FallbackDefinitionException.class)
public void testCommandWithFallbackReturnSuperType() {
userService.commandWithFallbackReturnSuperType("", "");
}
@Test
public void testCommandWithFallbackReturnSubType() {
User user = (User) userService.commandWithFallbackReturnSubType("", "");
assertEquals("def", user.getName());
}
@Test
public void testCommandWithFallbackWithAdditionalParameter() {
User user = userService.commandWithFallbackWithAdditionalParameter("", "");
assertEquals("def", user.getName());
}
@Test(expected = HystrixBadRequestException.class)
public void testCommandThrowsHystrixBadRequestExceptionWithNoCause() {
try {
userService.commandThrowsHystrixBadRequestExceptionWithNoCause(null, null);
} finally {
HystrixInvokableInfo<?> asyncCommandWithAsyncFallbackCommand = getHystrixCommandByKey("commandThrowsHystrixBadRequestExceptionWithNoCause");
assertFalse(asyncCommandWithAsyncFallbackCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
}
@Test
public void testFallbackMissing(){
try {
userService.getUserWithoutFallback(null, null);
} catch (Exception e) {}
HystrixInvokableInfo<?> command = getHystrixCommandByKey("getUserWithoutFallback");
assertTrue("expected event: FALLBACK_MISSING", command.getExecutionEvents().contains(HystrixEventType.FALLBACK_MISSING));
}
public static class UserService {
@HystrixCommand
public User getUserWithoutFallback(final String id, final String name) {
validate(id, name);
return new User(id, name);
}
@HystrixCommand(fallbackMethod = "fallback")
public Future<User> getUserAsync(final String id, final String name) {
validate(id, name); // validate logic can be inside and outside of AsyncResult#invoke method
return new AsyncResult<User>() {
@Override
public User invoke() {
// validate(id, name); possible put validation logic here, in case of any exception a fallback method will be invoked
return new User(id, name + id); // it should be network call
}
};
}
@HystrixCommand(fallbackMethod = "fallback")
public User getUserSync(String id, String name) {
validate(id, name);
return new User(id, name + id); // it should be network call
}
private User fallback(String id, String name) {
return new User("def", "def");
}
@HystrixCommand(fallbackMethod = "firstFallbackCommand")
public Future<User> getUserAsyncFallbackCommand(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
validate(id, name);
return new User(id, name + id); // it should be network call
}
};
}
@HystrixCommand(fallbackMethod = "firstFallbackCommand")
public User getUserSyncFallbackCommand(String id, String name) {
validate(id, name);
return new User(id, name + id); // it should be network call
}
// FALLBACK COMMANDS METHODS:
// This fallback methods will be processed as hystrix commands
@HystrixCommand(fallbackMethod = "secondFallbackCommand")
private User firstFallbackCommand(String id, String name) {
validate(id, name);
return new User(id, name + id); // it should be network call
}
@HystrixCommand(fallbackMethod = "staticFallback")
private User secondFallbackCommand(String id, String name) {
validate(id, name);
return new User(id, name + id); // it should be network call
}
@HystrixCommand(fallbackMethod = "firstAsyncFallbackCommand")
public Future<User> getUserAsyncFallbackAsyncCommand(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
throw new RuntimeException("getUserAsyncFallbackAsyncCommand failed");
}
};
}
@HystrixCommand(fallbackMethod = "secondAsyncFallbackCommand")
private Future<User> firstAsyncFallbackCommand(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
throw new RuntimeException("firstAsyncFallbackCommand failed");
}
};
}
@HystrixCommand(fallbackMethod = "thirdAsyncFallbackCommand")
private Future<User> secondAsyncFallbackCommand(final String id, final String name, final Throwable e) {
return new AsyncResult<User>() {
@Override
public User invoke() {
if ("firstAsyncFallbackCommand failed".equals(e.getMessage())) {
throw new RuntimeException("secondAsyncFallbackCommand failed");
}
return new User(id, name + id);
}
};
}
@HystrixCommand(fallbackMethod = "fallbackWithAdditionalParam")
private Future<User> thirdAsyncFallbackCommand(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
throw new RuntimeException("thirdAsyncFallbackCommand failed");
}
};
}
private User fallbackWithAdditionalParam(final String id, final String name, final Throwable e) {
if (!"thirdAsyncFallbackCommand failed".equals(e.getMessage())) {
throw new RuntimeException("fallbackWithAdditionalParam failed");
}
return new User("def", "def");
}
@HystrixCommand(fallbackMethod = "asyncFallbackCommand", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100000")
})
public Future<User> asyncCommandWithAsyncFallbackCommand(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
validate(id, name);
return new User(id, name + id); // it should be network call
}
};
}
@HystrixCommand(fallbackMethod = "asyncFallback", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100000")
})
public Future<User> asyncCommandWithAsyncFallback(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
validate(id, name);
return new User(id, name + id); // it should be network call
}
};
}
public Future<User> asyncFallback(final String id, final String name) {
return Observable.just(new User("def", "def")).toBlocking().toFuture();
}
@HystrixCommand
public Future<User> asyncFallbackCommand(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
return new User("def", "def"); // it should be network call
}
};
}
@HystrixCommand(fallbackMethod = "fallbackWithAdditionalParameter")
public User commandWithFallbackWithAdditionalParameter(final String id, final String name) {
validate(id, name);
return new User(id, name + id);
}
public User fallbackWithAdditionalParameter(final String id, final String name, Throwable e) {
if (e == null) {
throw new RuntimeException("exception should be not null");
}
return new User("def", "def");
}
@HystrixCommand(fallbackMethod = "fallbackWithStringReturnType")
public User commandWithWrongFallbackReturnType(final String id, final String name) {
validate(id, name);
return new User(id, name);
}
@HystrixCommand(fallbackMethod = "fallbackWithStringReturnType")
public Future<User> asyncCommandWithWrongFallbackReturnType(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
return new User("def", "def"); // it should be network call
}
};
}
@HystrixCommand(fallbackMethod = "fallbackWithoutParameters")
public User commandWithWrongFallbackParams(final String id, final String name) {
return new User(id, name);
}
@HystrixCommand(fallbackMethod = "fallbackReturnSubTypeOfDomain")
public Domain commandWithFallbackReturnSubType(final String id, final String name) {
validate(id, name);
return new User(id, name);
}
@HystrixCommand(fallbackMethod = "fallbackReturnSuperTypeOfDomain")
public User commandWithFallbackReturnSuperType(final String id, final String name) {
validate(id, name);
return new User(id, name);
}
@HystrixCommand(fallbackMethod = "staticFallback")
public User commandThrowsHystrixBadRequestExceptionWithNoCause(final String id, final String name){
throw new HystrixBadRequestException("invalid arguments");
}
private User fallbackReturnSubTypeOfDomain(final String id, final String name) {
return new User("def", "def");
}
private Domain fallbackReturnSuperTypeOfDomain(final String id, final String name) {
return new User("def", "def");
}
private String fallbackWithStringReturnType(final String id, final String name) {
return null;
}
private User fallbackWithoutParameters() {
return null;
}
private User staticFallback(String id, String name) {
return new User("def", "def");
}
private void validate(String id, String name) {
Validate.notBlank(id);
Validate.notBlank(name);
}
}
}
| 4,404 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/fallback/BasicDefaultFallbackTest.java | package com.netflix.hystrix.contrib.javanica.test.common.fallback;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil.
*/
public abstract class BasicDefaultFallbackTest extends BasicHystrixTest {
private ServiceWithDefaultFallback serviceWithDefaultFallback;
private ServiceWithDefaultCommandFallback serviceWithDefaultCommandFallback;
protected abstract ServiceWithDefaultFallback createServiceWithDefaultFallback();
protected abstract ServiceWithDefaultCommandFallback serviceWithDefaultCommandFallback();
@Before
public void setUp() throws Exception {
serviceWithDefaultFallback = createServiceWithDefaultFallback();
serviceWithDefaultCommandFallback = serviceWithDefaultCommandFallback();
}
@Test
public void testClassScopeDefaultFallback() {
String res = serviceWithDefaultFallback.requestString("");
assertEquals(ServiceWithDefaultFallback.DEFAULT_RESPONSE, res);
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("requestString", command.getCommandKey().name());
// confirm that 'requestString' command has failed
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that default fallback waw successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testSpecificCommandFallbackOverridesDefault() {
Integer res = serviceWithDefaultFallback.commandWithSpecificFallback("");
assertEquals(Integer.valueOf(res), res);
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("commandWithSpecificFallback", command.getCommandKey().name());
// confirm that 'commandWithSpecificFallback' command has failed
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that default fallback waw successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testCommandScopeDefaultFallback() {
Long res = serviceWithDefaultFallback.commandWithDefaultFallback(1L);
assertEquals(Long.valueOf(0L), res);
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("commandWithDefaultFallback", command.getCommandKey().name());
// confirm that 'requestString' command has failed
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that default fallback waw successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testClassScopeCommandDefaultFallback() {
String res = serviceWithDefaultCommandFallback.requestString("");
assertEquals(ServiceWithDefaultFallback.DEFAULT_RESPONSE, res);
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> requestStringCommand = getHystrixCommandByKey("requestString");
com.netflix.hystrix.HystrixInvokableInfo fallback = getHystrixCommandByKey("classDefaultFallback");
assertEquals("requestString", requestStringCommand.getCommandKey().name());
// confirm that command has failed
assertTrue(requestStringCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(requestStringCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// confirm that fallback was successful
assertTrue(fallback.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testCommandScopeCommandDefaultFallback() {
Long res = serviceWithDefaultCommandFallback.commandWithDefaultFallback(1L);
assertEquals(Long.valueOf(0L), res);
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> requestStringCommand = getHystrixCommandByKey("commandWithDefaultFallback");
com.netflix.hystrix.HystrixInvokableInfo fallback = getHystrixCommandByKey("defaultCommandFallback");
assertEquals("commandWithDefaultFallback", requestStringCommand.getCommandKey().name());
// confirm that command has failed
assertTrue(requestStringCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(requestStringCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// confirm that fallback was successful
assertTrue(fallback.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
// case when class level default fallback
@DefaultProperties(defaultFallback = "classDefaultFallback")
public static class ServiceWithDefaultFallback {
static final String DEFAULT_RESPONSE = "class_def";
@HystrixCommand
public String requestString(String str) {
throw new RuntimeException();
}
public String classDefaultFallback() {
return DEFAULT_RESPONSE;
}
@HystrixCommand(defaultFallback = "defaultCommandFallback")
Long commandWithDefaultFallback(long l){
throw new RuntimeException();
}
Long defaultCommandFallback(){
return 0L;
}
@HystrixCommand(fallbackMethod = "specificFallback")
Integer commandWithSpecificFallback(String str) {
throw new RuntimeException();
}
Integer specificFallback(String str) {
return 0;
}
}
// class level default fallback is annotated with @HystrixCommand and should be executed as Hystrix command
@DefaultProperties(defaultFallback = "classDefaultFallback")
public static class ServiceWithDefaultCommandFallback {
static final String DEFAULT_RESPONSE = "class_def";
@HystrixCommand
public String requestString(String str) {
throw new RuntimeException();
}
@HystrixCommand
public String classDefaultFallback() {
return DEFAULT_RESPONSE;
}
@HystrixCommand(defaultFallback = "defaultCommandFallback")
Long commandWithDefaultFallback(long l){
throw new RuntimeException();
}
@HystrixCommand(fallbackMethod = "defaultCommandFallback")
Long defaultCommandFallback(){
return 0L;
}
}
}
| 4,405 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/fallback/BasicGenericFallbackTest.java | package com.netflix.hystrix.contrib.javanica.test.common.fallback;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import rx.Completable;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil.
*/
@RunWith(JUnitParamsRunner.class)
public abstract class BasicGenericFallbackTest extends BasicHystrixTest {
@ClassRule
public static final SpringClassRule SCR = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
protected abstract <T> T createProxy(Class<T> t);
public Object[] methodGenericDefinitionSuccess() {
return new Object[]{
new Object[]{MethodGenericDefinitionSuccessCase0.class},
new Object[]{MethodGenericDefinitionSuccessCase1.class},
new Object[]{MethodGenericDefinitionSuccessCase2.class},
new Object[]{MethodGenericDefinitionSuccessCase3.class},
new Object[]{MethodGenericDefinitionSuccessCase4.class},
new Object[]{MethodGenericDefinitionSuccessCase5.class},
new Object[]{MethodGenericDefinitionSuccessCase6.class},
new Object[]{MethodGenericDefinitionSuccessCase7.class},
};
}
public Object[] methodGenericDefinitionFailure() {
return new Object[]{
new Object[]{MethodGenericDefinitionFailureCase0.class},
new Object[]{MethodGenericDefinitionFailureCase1.class},
new Object[]{MethodGenericDefinitionFailureCase2.class},
new Object[]{MethodGenericDefinitionFailureCase3.class},
new Object[]{MethodGenericDefinitionFailureCase4.class},
new Object[]{MethodGenericDefinitionFailureCase5.class},
new Object[]{MethodGenericDefinitionFailureCase6.class},
new Object[]{MethodGenericDefinitionFailureCase7.class},
new Object[]{MethodGenericDefinitionFailureCase8.class},
new Object[]{MethodGenericDefinitionFailureCase9.class},
new Object[]{MethodGenericDefinitionFailureCase10.class},
new Object[]{MethodGenericDefinitionFailureCase11.class},
};
}
public Object[] classGenericDefinitionSuccess() {
return new Object[]{
new Object[]{ClassGenericDefinitionSuccessCase0.class},
new Object[]{ClassGenericDefinitionSuccessCase1.class},
};
}
public Object[] classGenericDefinitionFailure() {
return new Object[]{
new Object[]{ClassGenericDefinitionFailureCase0.class},
new Object[]{ClassGenericDefinitionFailureCase1.class},
};
}
@Test
@Parameters(method = "methodGenericDefinitionSuccess")
public void testMethodGenericDefinitionSuccess(Class<?> type) {
testXKindGenericDefinitionSuccess(type);
}
@Test(expected = FallbackDefinitionException.class)
@Parameters(method = "methodGenericDefinitionFailure")
public void testMethodGenericDefinitionFailure(Class<?> type) {
Object p = createProxy(type);
executeCommand(p);
}
@Test
@Parameters(method = "classGenericDefinitionSuccess")
public void testClassGenericDefinitionSuccess(Class<?> type) {
testXKindGenericDefinitionSuccess(type);
}
@Test(expected = FallbackDefinitionException.class)
@Parameters(method = "classGenericDefinitionFailure")
public void testClassGenericDefinitionFailure(Class<?> type) {
Object p = createProxy(type);
executeCommand(p);
}
private void testXKindGenericDefinitionSuccess(Class<?> type) {
Object p = createProxy(type);
try {
executeCommand(p);
HystrixInvokableInfo<?> command = getHystrixCommandByKey("command");
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
} catch (FallbackDefinitionException e) {
throw new AssertionError(MessageFormatter.format("Case class '{}' has failed. Reason:\n{}", type.getCanonicalName(), e).getMessage());
}
}
/* ====================================================================== */
/* ===================== GENERIC METHOD DEFINITIONS ===================== */
/* =========================== SUCCESS CASES ============================ */
public static class MethodGenericDefinitionSuccessCase0 {
@HystrixCommand(fallbackMethod = "fallback")
public <T> T command() { throw new IllegalStateException(); }
private <T> T fallback() { return null; }
}
public static class MethodGenericDefinitionSuccessCase1 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable> T command() { throw new IllegalStateException(); }
private <T extends Serializable> T fallback() { return null; }
}
public static class MethodGenericDefinitionSuccessCase2 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable, T1 extends T> T1 command() { throw new IllegalStateException(); }
private <T extends Serializable, T1 extends T> T1 fallback() { return null; }
}
public static class MethodGenericDefinitionSuccessCase3 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable, T1 extends T> GenericEntity<? extends T1> command() { throw new IllegalStateException(); }
private <T extends Serializable, T1 extends T> GenericEntity<? extends T1> fallback() { return null; }
}
public static class MethodGenericDefinitionSuccessCase4 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable & Comparable, T1 extends T> GenericEntity<? extends T1> command() { throw new IllegalStateException(); }
private <T extends Serializable & Comparable, T1 extends T> GenericEntity<? extends T1> fallback() { return null; }
}
public static class MethodGenericDefinitionSuccessCase5 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable & Comparable, T1 extends GenericEntity<T>> GenericEntity<T1> command() { throw new IllegalStateException(); }
private <T extends Serializable & Comparable, T1 extends GenericEntity<T>> GenericEntity<T1> fallback() { return null; }
}
public static class MethodGenericDefinitionSuccessCase6 {
@HystrixCommand(fallbackMethod = "fallback")
public <T> GenericEntity<T> command() { throw new IllegalStateException(); }
private <T> GenericEntity<T> fallback() { return new GenericEntity<T>(); }
}
public static class MethodGenericDefinitionSuccessCase7 {
@HystrixCommand(fallbackMethod = "fallback")
public GenericEntity<? super Serializable> command() { throw new IllegalStateException(); }
private GenericEntity<? super Serializable> fallback() { return null; }
}
/* ====================================================================== */
/* ===================== GENERIC METHOD DEFINITIONS ===================== */
/* =========================== FAILURE CASES ============================ */
public static class MethodGenericDefinitionFailureCase0 {
@HystrixCommand(fallbackMethod = "fallback")
public <T> T command() { throw new IllegalStateException(); }
private String fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase1 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable> T command() { throw new IllegalStateException(); }
private <T> T fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase2 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable> T command() { throw new IllegalStateException(); }
private <T extends Comparable> T fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase3 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable, T1 extends T> GenericEntity<? extends T1> command() { throw new IllegalStateException(); }
private <T extends Serializable, T1 extends T> GenericEntity<T1> fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase4 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable & Comparable, T1 extends T> GenericEntity<? extends T1> command() { throw new IllegalStateException(); }
private <T extends Serializable, T1 extends T> GenericEntity<? extends T1> fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase5 {
@HystrixCommand(fallbackMethod = "fallback")
public <T extends Serializable & Comparable, T1 extends GenericEntity<T>> GenericEntity<T1> command() { throw new IllegalStateException(); }
private <T extends Serializable & Comparable, T1 extends GenericEntity<String>> GenericEntity<T1> fallback() { return null;}
}
public static class MethodGenericDefinitionFailureCase6 {
@HystrixCommand(fallbackMethod = "fallback")
public <T> GenericEntity<T> command() { throw new IllegalStateException(); }
private GenericEntity<String> fallback() { return new GenericEntity<String>(); }
}
public static class MethodGenericDefinitionFailureCase7 {
@HystrixCommand(fallbackMethod = "fallback")
public <T> Set<T> command() { throw new IllegalStateException(); }
private <T> List<T> fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase8 {
@HystrixCommand(fallbackMethod = "fallback")
public <T> GenericEntity<Set<T>> command() { throw new IllegalStateException(); }
private <T> GenericEntity<List<T>> fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase9 {
@HystrixCommand(fallbackMethod = "fallback")
public <T> GenericEntity<List<Set<T>>> command() { throw new IllegalStateException(); }
private <T> GenericEntity<List<List<T>>> fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase10 {
@HystrixCommand(fallbackMethod = "fallback")
public GenericEntity<? super Serializable> command() { throw new IllegalStateException(); }
private GenericEntity<? super Comparable> fallback() { return null; }
}
public static class MethodGenericDefinitionFailureCase11 {
@HystrixCommand(fallbackMethod = "fallback")
public Completable command() { throw new IllegalStateException(); }
private void fallback() { return; }
}
/* ====================================================================== */
/* ===================== GENERIC CLASS DEFINITIONS =====+================ */
/* =========================== SUCCESS CASES ============================ */
public static class ClassGenericDefinitionSuccessCase0<T> {
@HystrixCommand(fallbackMethod = "fallback")
public GenericEntity<T> command() { throw new IllegalStateException(); }
private GenericEntity<T> fallback() { return new GenericEntity<T>(); }
}
public static class ClassGenericDefinitionSuccessCase1<T extends Serializable> {
@HystrixCommand(fallbackMethod = "fallback")
public GenericEntity<T> command() { throw new IllegalStateException(); }
private GenericEntity<T> fallback() { return new GenericEntity<T>(); }
}
/* ====================================================================== */
/* ===================== GENERIC CLASS DEFINITIONS =====+================ */
/* =========================== FAILURE CASES ============================ */
public static class ClassGenericDefinitionFailureCase0<T> {
@HystrixCommand(fallbackMethod = "fallback")
public GenericEntity<T> command() { throw new IllegalStateException(); }
private <T> GenericEntity<T> fallback() { return new GenericEntity<T>(); }
}
public static class ClassGenericDefinitionFailureCase1<T extends Serializable> {
@HystrixCommand(fallbackMethod = "fallback")
public GenericEntity<T> command() { throw new IllegalStateException(); }
private <T extends Serializable> GenericEntity<T> fallback() { return new GenericEntity<T>(); }
}
public static class GenericEntity<T> {
}
private static Object executeCommand(Object proxy) {
try {
Method method = proxy.getClass().getDeclaredMethod("command");
return method.invoke(proxy);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof FallbackDefinitionException) {
throw (FallbackDefinitionException) t;
} else throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 4,406 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/collapser/BasicCollapserTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.collapser;
import com.google.common.collect.Sets;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil
*/
public abstract class BasicCollapserTest extends BasicHystrixTest {
protected abstract UserService createUserService();
private UserService userService;
@Before
public void setUp() throws Exception {
userService = createUserService();
}
@Test
public void testGetUserById() throws ExecutionException, InterruptedException {
Future<User> f1 = userService.getUserById("1");
Future<User> f2 = userService.getUserById("2");
Future<User> f3 = userService.getUserById("3");
Future<User> f4 = userService.getUserById("4");
Future<User> f5 = userService.getUserById("5");
assertEquals("name: 1", f1.get().getName());
assertEquals("name: 2", f2.get().getName());
assertEquals("name: 3", f3.get().getName());
assertEquals("name: 4", f4.get().getName());
assertEquals("name: 5", f5.get().getName());
// assert that the batch command 'getUserByIds' was in fact
// executed and that it executed only once
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
// assert the command is the one we're expecting
assertEquals("getUserByIds", command.getCommandKey().name());
// confirm that it was a COLLAPSED command execution
assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
// and that it was successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testReactive() throws Exception {
final Observable<User> u1 = userService.getUserByIdReactive("1");
final Observable<User> u2 = userService.getUserByIdReactive("2");
final Observable<User> u3 = userService.getUserByIdReactive("3");
final Observable<User> u4 = userService.getUserByIdReactive("4");
final Observable<User> u5 = userService.getUserByIdReactive("5");
final Iterable<User> users = Observable.merge(u1, u2, u3, u4, u5).toBlocking().toIterable();
Set<String> expectedIds = Sets.newHashSet("1", "2", "3", "4", "5");
for (User cUser : users) {
assertEquals(expectedIds.remove(cUser.getId()), true);
}
assertEquals(expectedIds.isEmpty(), true);
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
// assert the command is the one we're expecting
assertEquals("getUserByIds", command.getCommandKey().name());
// confirm that it was a COLLAPSED command execution
assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
// and that it was successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testGetUserByIdWithFallback() throws ExecutionException, InterruptedException {
Future<User> f1 = userService.getUserByIdWithFallback("1");
Future<User> f2 = userService.getUserByIdWithFallback("2");
Future<User> f3 = userService.getUserByIdWithFallback("3");
Future<User> f4 = userService.getUserByIdWithFallback("4");
Future<User> f5 = userService.getUserByIdWithFallback("5");
assertEquals("name: 1", f1.get().getName());
assertEquals("name: 2", f2.get().getName());
assertEquals("name: 3", f3.get().getName());
assertEquals("name: 4", f4.get().getName());
assertEquals("name: 5", f5.get().getName());
// two command should be executed: "getUserByIdWithFallback" and "getUserByIdsWithFallback"
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> getUserByIdsWithFallback = getHystrixCommandByKey("getUserByIdsWithFallback");
com.netflix.hystrix.HystrixInvokableInfo getUserByIdsFallback = getHystrixCommandByKey("getUserByIdsFallback");
// confirm that command has failed
assertTrue(getUserByIdsWithFallback.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(getUserByIdsWithFallback.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// and that fallback was successful
assertTrue(getUserByIdsFallback.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testGetUserByIdWithFallbackWithThrowableParam() throws ExecutionException, InterruptedException {
Future<User> f1 = userService.getUserByIdWithFallbackWithThrowableParam("1");
Future<User> f2 = userService.getUserByIdWithFallbackWithThrowableParam("2");
Future<User> f3 = userService.getUserByIdWithFallbackWithThrowableParam("3");
Future<User> f4 = userService.getUserByIdWithFallbackWithThrowableParam("4");
Future<User> f5 = userService.getUserByIdWithFallbackWithThrowableParam("5");
assertEquals("name: 1", f1.get().getName());
assertEquals("name: 2", f2.get().getName());
assertEquals("name: 3", f3.get().getName());
assertEquals("name: 4", f4.get().getName());
assertEquals("name: 5", f5.get().getName());
// 4 commands should be executed
assertEquals(4, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> batchCommand = getHystrixCommandByKey("getUserByIdsThrowsException");
com.netflix.hystrix.HystrixInvokableInfo fallback1 = getHystrixCommandByKey("getUserByIdsFallbackWithThrowableParam1");
com.netflix.hystrix.HystrixInvokableInfo fallback2 = getHystrixCommandByKey("getUserByIdsFallbackWithThrowableParam2");
com.netflix.hystrix.HystrixInvokableInfo fallback3 = getHystrixCommandByKey("getUserByIdsFallbackWithThrowableParam3");
// confirm that command has failed
assertTrue(batchCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(fallback1.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(fallback2.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(fallback2.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// and that last fallback3 was successful
assertTrue(fallback3.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test(expected = IllegalStateException.class)
public void testGetUserByIdWrongBatchMethodArgType() {
userService.getUserByIdWrongBatchMethodArgType("1");
}
@Test(expected = IllegalStateException.class)
public void testGetUserByIdWrongBatchMethodReturnType() {
userService.getUserByIdWrongBatchMethodArgType("1");
}
@Test(expected = IllegalStateException.class)
public void testGetUserByIdWrongCollapserMethodReturnType() {
userService.getUserByIdWrongCollapserMethodReturnType("1");
}
@Test(expected = IllegalStateException.class)
public void testGetUserByIdWrongCollapserMultipleArgs() {
userService.getUserByIdWrongCollapserMultipleArgs("1", "2");
}
@Test(expected = IllegalStateException.class)
public void testGetUserByIdWrongCollapserNoArgs() {
userService.getUserByIdWrongCollapserNoArgs();
}
public static class UserService {
public static final Logger log = LoggerFactory.getLogger(UserService.class);
public static final User DEFAULT_USER = new User("def", "def");
@HystrixCollapser(batchMethod = "getUserByIds",
collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds", value = "200")})
public Future<User> getUserById(String id) {
return null;
}
@HystrixCollapser(batchMethod = "getUserByIdsWithFallback",
collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds", value = "200")})
public Future<User> getUserByIdWithFallback(String id) {
return null;
}
@HystrixCollapser(batchMethod = "getUserByIds",
collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds", value = "200")})
public Observable<User> getUserByIdReactive(String id) {
return null;
}
@HystrixCollapser(batchMethod = "getUserByIdsThrowsException",
collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds", value = "200")})
public Future<User> getUserByIdWithFallbackWithThrowableParam(String id) {
return null;
}
@HystrixCommand(
fallbackMethod = "getUserByIdsFallbackWithThrowableParam1",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000")// for debug
})
public List<User> getUserByIdsThrowsException(List<String> ids) {
throw new RuntimeException("getUserByIdsFails failed");
}
@HystrixCommand(fallbackMethod = "getUserByIdsFallbackWithThrowableParam2")
private List<User> getUserByIdsFallbackWithThrowableParam1(List<String> ids, Throwable e) {
if (e.getMessage().equals("getUserByIdsFails failed")) {
throw new RuntimeException("getUserByIdsFallbackWithThrowableParam1 failed");
}
List<User> users = new ArrayList<User>();
for (String id : ids) {
users.add(new User(id, "name: " + id));
}
return users;
}
@HystrixCommand(fallbackMethod = "getUserByIdsFallbackWithThrowableParam3")
private List<User> getUserByIdsFallbackWithThrowableParam2(List<String> ids) {
throw new RuntimeException("getUserByIdsFallbackWithThrowableParam2 failed");
}
@HystrixCommand
private List<User> getUserByIdsFallbackWithThrowableParam3(List<String> ids, Throwable e) {
if (!e.getMessage().equals("getUserByIdsFallbackWithThrowableParam2 failed")) {
throw new RuntimeException("getUserByIdsFallbackWithThrowableParam3 failed");
}
List<User> users = new ArrayList<User>();
for (String id : ids) {
users.add(new User(id, "name: " + id));
}
return users;
}
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000")// for debug
})
public List<User> getUserByIds(List<String> ids) {
List<User> users = new ArrayList<User>();
for (String id : ids) {
users.add(new User(id, "name: " + id));
}
log.debug("executing on thread id: {}", Thread.currentThread().getId());
return users;
}
@HystrixCommand(fallbackMethod = "getUserByIdsFallback",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000")// for debug
})
public List<User> getUserByIdsWithFallback(List<String> ids) {
throw new RuntimeException("not found");
}
@HystrixCommand
private List<User> getUserByIdsFallback(List<String> ids) {
List<User> users = new ArrayList<User>();
for (String id : ids) {
users.add(new User(id, "name: " + id));
}
return users;
}
// wrong return type, expected: Future<User> or User, because batch command getUserByIds returns List<User>
@HystrixCollapser(batchMethod = "getUserByIds")
public Long getUserByIdWrongCollapserMethodReturnType(String id) {
return null;
}
@HystrixCollapser(batchMethod = "getUserByIds")
public Future<User> getUserByIdWrongCollapserMultipleArgs(String id, String name) {
return null;
}
@HystrixCollapser(batchMethod = "getUserByIds")
public Future<User> getUserByIdWrongCollapserNoArgs() {
return null;
}
@HystrixCollapser(batchMethod = "getUserByIdsWrongBatchMethodArgType")
public Future<User> getUserByIdWrongBatchMethodArgType(String id) {
return null;
}
// wrong arg type, expected: List<String>
@HystrixCommand
public List<User> getUserByIdsWrongBatchMethodArgType(List<Integer> ids) {
return null;
}
@HystrixCollapser(batchMethod = "getUserByIdsWrongBatchMethodReturnType")
public Future<User> getUserByIdWrongBatchMethodReturnType(String id) {
return null;
}
// wrong return type, expected: List<User>
@HystrixCommand
public List<Integer> getUserByIdsWrongBatchMethodReturnType(List<String> ids) {
return null;
}
}
}
| 4,407 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/observable/BasicObservableTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.observable;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.ObservableExecutionMode;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;
import rx.Completable;
import rx.Observable;
import rx.Observer;
import rx.Single;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func0;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil
*/
public abstract class BasicObservableTest extends BasicHystrixTest {
private UserService userService;
protected abstract UserService createUserService();
@Before
public void setUp() throws Exception {
userService = createUserService();
}
@Test
public void testGetUserByIdSuccess() {
// blocking
Observable<User> observable = userService.getUser("1", "name: ");
assertEquals("name: 1", observable.toBlocking().single().getName());
// non-blocking
// - this is a verbose anonymous inner-class approach and doesn't do assertions
Observable<User> fUser = userService.getUser("1", "name: ");
fUser.subscribe(new Observer<User>() {
@Override
public void onCompleted() {
// nothing needed here
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(User v) {
System.out.println("onNext: " + v);
}
});
Observable<User> fs = userService.getUser("1", "name: ");
fs.subscribe(new Action1<User>() {
@Override
public void call(User user) {
assertEquals("name: 1", user.getName());
}
});
assertEquals(3, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getUser");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testGetCompletableUser(){
userService.getCompletableUser("1", "name: ");
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getCompletableUser");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testGetCompletableUserWithRegularFallback() {
Completable completable = userService.getCompletableUserWithRegularFallback(null, "name: ");
completable.<User>toObservable().subscribe(new Action1<User>() {
@Override
public void call(User user) {
assertEquals("default_id", user.getId());
}
});
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getCompletableUserWithRegularFallback");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetCompletableUserWithRxFallback() {
Completable completable = userService.getCompletableUserWithRxFallback(null, "name: ");
completable.<User>toObservable().subscribe(new Action1<User>() {
@Override
public void call(User user) {
assertEquals("default_id", user.getId());
}
});
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getCompletableUserWithRxFallback");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetSingleUser() {
final String id = "1";
Single<User> user = userService.getSingleUser(id, "name: ");
user.subscribe(new Action1<User>() {
@Override
public void call(User user) {
assertEquals(id, user.getId());
}
});
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getSingleUser");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testGetSingleUserWithRegularFallback(){
Single<User> user = userService.getSingleUserWithRegularFallback(null, "name: ");
user.subscribe(new Action1<User>() {
@Override
public void call(User user) {
assertEquals("default_id", user.getId());
}
});
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getSingleUserWithRegularFallback");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetSingleUserWithRxFallback(){
Single<User> user = userService.getSingleUserWithRxFallback(null, "name: ");
user.subscribe(new Action1<User>() {
@Override
public void call(User user) {
assertEquals("default_id", user.getId());
}
});
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getSingleUserWithRxFallback");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetUserWithRegularFallback() {
final User exUser = new User("def", "def");
Observable<User> userObservable = userService.getUserRegularFallback(" ", "");
// blocking
assertEquals(exUser, userObservable.toBlocking().single());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getUserRegularFallback");
// confirm that command has failed
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that fallback was successful
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetUserWithRxFallback() {
final User exUser = new User("def", "def");
// blocking
assertEquals(exUser, userService.getUserRxFallback(" ", "").toBlocking().single());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("getUserRxFallback");
// confirm that command has failed
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that fallback was successful
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
@Test
public void testGetUserWithRxCommandFallback() {
final User exUser = new User("def", "def");
// blocking
Observable<User> userObservable = userService.getUserRxCommandFallback(" ", "");
assertEquals(exUser, userObservable.toBlocking().single());
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserRxCommandFallback = getHystrixCommandByKey("getUserRxCommandFallback");
com.netflix.hystrix.HystrixInvokableInfo rxCommandFallback = getHystrixCommandByKey("rxCommandFallback");
// confirm that command has failed
assertTrue(getUserRxCommandFallback.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(getUserRxCommandFallback.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// and that fallback command was successful
assertTrue(rxCommandFallback.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
public static class UserService {
private User regularFallback(String id, String name) {
return new User("def", "def");
}
private Observable<User> rxFallback(String id, String name) {
return Observable.just(new User("def", "def"));
}
@HystrixCommand(observableExecutionMode = ObservableExecutionMode.EAGER)
private Observable<User> rxCommandFallback(String id, String name, Throwable throwable) {
if (throwable instanceof GetUserException && "getUserRxCommandFallback has failed".equals(throwable.getMessage())) {
return Observable.just(new User("def", "def"));
} else {
throw new IllegalStateException();
}
}
@HystrixCommand
public Observable<User> getUser(final String id, final String name) {
validate(id, name, "getUser has failed");
return createObservable(id, name);
}
@HystrixCommand
public Completable getCompletableUser(final String id, final String name) {
validate(id, name, "getCompletableUser has failed");
return createObservable(id, name).toCompletable();
}
@HystrixCommand(fallbackMethod = "completableUserRegularFallback")
public Completable getCompletableUserWithRegularFallback(final String id, final String name) {
return getCompletableUser(id, name);
}
@HystrixCommand(fallbackMethod = "completableUserRxFallback")
public Completable getCompletableUserWithRxFallback(final String id, final String name) {
return getCompletableUser(id, name);
}
public User completableUserRegularFallback(final String id, final String name) {
return new User("default_id", "default_name");
}
public Completable completableUserRxFallback(final String id, final String name) {
return Completable.fromCallable(new Func0<User>() {
@Override
public User call() {
return new User("default_id", "default_name");
}
});
}
@HystrixCommand
public Single<User> getSingleUser(final String id, final String name) {
validate(id, name, "getSingleUser has failed");
return createObservable(id, name).toSingle();
}
@HystrixCommand(fallbackMethod = "singleUserRegularFallback")
public Single<User> getSingleUserWithRegularFallback(final String id, final String name) {
return getSingleUser(id, name);
}
@HystrixCommand(fallbackMethod = "singleUserRxFallback")
public Single<User> getSingleUserWithRxFallback(final String id, final String name) {
return getSingleUser(id, name);
}
User singleUserRegularFallback(final String id, final String name) {
return new User("default_id", "default_name");
}
Single<User> singleUserRxFallback(final String id, final String name) {
return createObservable("default_id", "default_name").toSingle();
}
@HystrixCommand(fallbackMethod = "regularFallback", observableExecutionMode = ObservableExecutionMode.LAZY)
public Observable<User> getUserRegularFallback(final String id, final String name) {
validate(id, name, "getUser has failed");
return createObservable(id, name);
}
@HystrixCommand(fallbackMethod = "rxFallback")
public Observable<User> getUserRxFallback(final String id, final String name) {
validate(id, name, "getUserRxFallback has failed");
return createObservable(id, name);
}
@HystrixCommand(fallbackMethod = "rxCommandFallback", observableExecutionMode = ObservableExecutionMode.LAZY)
public Observable<User> getUserRxCommandFallback(final String id, final String name) {
validate(id, name, "getUserRxCommandFallback has failed");
return createObservable(id, name);
}
private Observable<User> createObservable(final String id, final String name) {
return Observable.create(new Observable.OnSubscribe<User>() {
@Override
public void call(Subscriber<? super User> observer) {
try {
if (!observer.isUnsubscribed()) {
observer.onNext(new User(id, name + id));
observer.onCompleted();
}
} catch (Exception e) {
observer.onError(e);
}
}
});
}
private void validate(String id, String name, String errorMsg) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(name)) {
throw new GetUserException(errorMsg);
}
}
private static final class GetUserException extends RuntimeException {
public GetUserException(String message) {
super(message);
}
}
}
}
| 4,408 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/command/BasicCommandTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.command;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public abstract class BasicCommandTest extends BasicHystrixTest {
private UserService userService;
private AdvancedUserService advancedUserService;
private GenericService<String, Long, User> genericUserService;
@Before
public void setUp() throws Exception {
userService = createUserService();
advancedUserService = createAdvancedUserServiceService();
genericUserService = createGenericUserService();
}
@Test
public void testGetUserAsync() throws ExecutionException, InterruptedException {
Future<User> f1 = userService.getUserAsync("1", "name: ");
assertEquals("name: 1", f1.get().getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo<?> command = getCommand();
// assert the command key name is the we're expecting
assertEquals("GetUserCommand", command.getCommandKey().name());
// assert the command group key name is the we're expecting
assertEquals("UserService", command.getCommandGroup().name());
// assert the command thread pool key name is the we're expecting
assertEquals("CommandTestAsync", command.getThreadPoolKey().name());
// it was successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void testGetUserSync() {
User u1 = userService.getUserSync("1", "name: ");
assertGetUserSnycCommandExecuted(u1);
}
@Test
public void shouldWorkWithInheritedMethod() {
User u1 = advancedUserService.getUserSync("1", "name: ");
assertGetUserSnycCommandExecuted(u1);
}
@Test
public void should_work_with_parameterized_method() throws Exception {
assertEquals(Integer.valueOf(1), userService.echo(1));
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
assertTrue(getCommand().getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void should_work_with_parameterized_asyncMethod() throws Exception {
assertEquals(Integer.valueOf(1), userService.echoAsync(1).get());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
assertTrue(getCommand().getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
@Test
public void should_work_with_genericClass_fallback() {
User user = genericUserService.getByKeyForceFail("1", 2L);
assertEquals("name: 2", user.getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest()
.getAllExecutedCommands().iterator().next();
assertEquals("getByKeyForceFail", command.getCommandKey().name());
// confirm that command has failed
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and that fallback was successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
}
private void assertGetUserSnycCommandExecuted(User u1) {
assertEquals("name: 1", u1.getName());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo<?> command = getCommand();
assertEquals("getUserSync", command.getCommandKey().name());
assertEquals("UserGroup", command.getCommandGroup().name());
assertEquals("UserGroup", command.getThreadPoolKey().name());
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
}
private com.netflix.hystrix.HystrixInvokableInfo<?> getCommand() {
return HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
}
protected abstract UserService createUserService();
protected abstract AdvancedUserService createAdvancedUserServiceService();
protected abstract GenericService<String, Long, User> createGenericUserService();
public interface GenericService<K1, K2, V> {
V getByKey(K1 key1, K2 key2);
V getByKeyForceFail(K1 key, K2 key2);
V fallback(K1 key, K2 key2);
}
public static class GenericUserService implements GenericService<String, Long, User> {
@HystrixCommand(fallbackMethod = "fallback")
@Override
public User getByKey(String sKey, Long lKey) {
return new User(sKey, "name: " + lKey); // it should be network call
}
@HystrixCommand(fallbackMethod = "fallback")
@Override
public User getByKeyForceFail(String sKey, Long lKey) {
throw new RuntimeException("force fail");
}
@Override
public User fallback(String sKey, Long lKey) {
return new User(sKey, "name: " + lKey);
}
}
public static class UserService {
@HystrixCommand(commandKey = "GetUserCommand", threadPoolKey = "CommandTestAsync")
public Future<User> getUserAsync(final String id, final String name) {
return new AsyncResult<User>() {
@Override
public User invoke() {
return new User(id, name + id); // it should be network call
}
};
}
@HystrixCommand(groupKey = "UserGroup")
public User getUserSync(String id, String name) {
return new User(id, name + id); // it should be network call
}
@HystrixCommand
public <T> T echo(T value) {
return value;
}
@HystrixCommand
public <T> Future<T> echoAsync(final T value) {
return new AsyncResult<T>() {
@Override
public T invoke() {
return value;
}
};
}
}
public static class AdvancedUserService extends UserService {
}
}
| 4,409 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/error/BasicObservableErrorPropagationTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.error;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import rx.Observable;
import rx.observers.TestSubscriber;
import java.util.HashMap;
import java.util.Map;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Created by dmgcodevil
*/
public abstract class BasicObservableErrorPropagationTest extends BasicHystrixTest {
private static final String COMMAND_KEY = "getUserById";
private static final Map<String, User> USERS;
static {
USERS = new HashMap<String, User>();
USERS.put("1", new User("1", "user_1"));
USERS.put("2", new User("2", "user_2"));
USERS.put("3", new User("3", "user_3"));
}
private UserService userService;
@MockitoAnnotations.Mock
private FailoverService failoverService;
protected abstract UserService createUserService();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
userService = createUserService();
userService.setFailoverService(failoverService);
}
@Test
public void testGetUserByBadId() throws NotFoundException {
try {
TestSubscriber<User> testSubscriber = new TestSubscriber<User>();
String badId = "";
userService.getUserById(badId).subscribe(testSubscriber);
testSubscriber.assertError(BadRequestException.class);
} finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey(COMMAND_KEY);
// will not affect metrics
assertFalse(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and will not trigger fallback logic
verify(failoverService, never()).getDefUser();
}
}
@Test
public void testGetNonExistentUser() throws NotFoundException {
try {
TestSubscriber<User> testSubscriber = new TestSubscriber<User>();
userService.getUserById("4").subscribe(testSubscriber); // user with id 4 doesn't exist
testSubscriber.assertError(NotFoundException.class);
} finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey(COMMAND_KEY);
// will not affect metrics
assertFalse(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and will not trigger fallback logic
verify(failoverService, never()).getDefUser();
}
}
@Test // don't expect any exceptions because fallback must be triggered
public void testActivateUser() throws NotFoundException, ActivationException {
try {
userService.activateUser("1").toBlocking().single(); // this method always throws ActivationException
} finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo activateUserCommand = getHystrixCommandByKey("activateUser");
// will not affect metrics
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// and will not trigger fallback logic
verify(failoverService, atLeastOnce()).activate();
}
}
@Test
public void testBlockUser() throws NotFoundException, ActivationException, OperationException {
try {
TestSubscriber<Void> testSubscriber = new TestSubscriber<Void>();
userService.blockUser("1").subscribe(testSubscriber); // this method always throws ActivationException
testSubscriber.assertError(Throwable.class);
assertTrue(testSubscriber.getOnErrorEvents().size() == 1);
assertTrue(testSubscriber.getOnErrorEvents().get(0).getCause() instanceof OperationException);
} finally {
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo activateUserCommand = getHystrixCommandByKey("blockUser");
// will not affect metrics
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_FAILURE));
}
}
@Test
public void testPropagateCauseException() throws NotFoundException {
TestSubscriber<Void> testSubscriber = new TestSubscriber<Void>();
userService.deleteUser("").subscribe(testSubscriber);
testSubscriber.assertError(NotFoundException.class);
}
public static class UserService {
private FailoverService failoverService;
public void setFailoverService(FailoverService failoverService) {
this.failoverService = failoverService;
}
@HystrixCommand
public Observable<Void> deleteUser(String id) throws NotFoundException {
return Observable.error(new NotFoundException(""));
}
@HystrixCommand(
commandKey = COMMAND_KEY,
ignoreExceptions = {
BadRequestException.class,
NotFoundException.class
},
fallbackMethod = "fallback")
public Observable<User> getUserById(String id) throws NotFoundException {
validate(id);
if (!USERS.containsKey(id)) {
return Observable.error(new NotFoundException("user with id: " + id + " not found"));
}
return Observable.just(USERS.get(id));
}
@HystrixCommand(
ignoreExceptions = {BadRequestException.class, NotFoundException.class},
fallbackMethod = "activateFallback")
public Observable<Void> activateUser(String id) throws NotFoundException, ActivationException {
validate(id);
if (!USERS.containsKey(id)) {
return Observable.error(new NotFoundException("user with id: " + id + " not found"));
}
// always throw this exception
return Observable.error(new ActivationException("user cannot be activate"));
}
@HystrixCommand(
ignoreExceptions = {BadRequestException.class, NotFoundException.class},
fallbackMethod = "blockUserFallback")
public Observable<Void> blockUser(String id) throws NotFoundException, OperationException {
validate(id);
if (!USERS.containsKey(id)) {
return Observable.error(new NotFoundException("user with id: " + id + " not found"));
}
// always throw this exception
return Observable.error(new OperationException("user cannot be blocked"));
}
private Observable<User> fallback(String id) {
return failoverService.getDefUser();
}
private Observable<Void> activateFallback(String id) {
return failoverService.activate();
}
@HystrixCommand(ignoreExceptions = {RuntimeException.class})
private Observable<Void> blockUserFallback(String id) {
return Observable.error(new RuntimeOperationException("blockUserFallback has failed"));
}
private void validate(String val) throws BadRequestException {
if (val == null || val.length() == 0) {
throw new BadRequestException("parameter cannot be null ot empty");
}
}
}
private class FailoverService {
public Observable<User> getDefUser() {
return Observable.just(new User("def", "def"));
}
public Observable<Void> activate() {
return Observable.empty();
}
}
// exceptions
private static class NotFoundException extends Exception {
private NotFoundException(String message) {
super(message);
}
}
private static class BadRequestException extends RuntimeException {
private BadRequestException(String message) {
super(message);
}
}
private static class ActivationException extends Exception {
private ActivationException(String message) {
super(message);
}
}
private static class OperationException extends Throwable {
private OperationException(String message) {
super(message);
}
}
private static class RuntimeOperationException extends RuntimeException {
private RuntimeOperationException(String message) {
super(message);
}
}
}
| 4,410 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/error/BasicErrorPropagationTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.error;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import com.netflix.hystrix.exception.ExceptionNotWrappedByHystrix;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.*;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Created by dmgcodevil
*/
public abstract class BasicErrorPropagationTest extends BasicHystrixTest {
private static final String COMMAND_KEY = "getUserById";
private static final Map<String, User> USERS;
static {
USERS = new HashMap<String, User>();
USERS.put("1", new User("1", "user_1"));
USERS.put("2", new User("2", "user_2"));
USERS.put("3", new User("3", "user_3"));
}
private UserService userService;
@MockitoAnnotations.Mock
private FailoverService failoverService;
protected abstract UserService createUserService();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
userService = createUserService();
userService.setFailoverService(failoverService);
}
@Test(expected = BadRequestException.class)
public void testGetUserByBadId() throws NotFoundException {
try {
String badId = "";
userService.getUserById(badId);
} finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey(COMMAND_KEY);
// will not affect metrics
assertFalse(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and will not trigger fallback logic
verify(failoverService, never()).getDefUser();
}
}
@Test(expected = NotFoundException.class)
public void testGetNonExistentUser() throws NotFoundException {
try {
userService.getUserById("4"); // user with id 4 doesn't exist
} finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey(COMMAND_KEY);
// will not affect metrics
assertFalse(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and will not trigger fallback logic
verify(failoverService, never()).getDefUser();
}
}
@Test // don't expect any exceptions because fallback must be triggered
public void testActivateUser() throws NotFoundException, ActivationException {
try {
userService.activateUser("1"); // this method always throws ActivationException
} finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo activateUserCommand = getHystrixCommandByKey("activateUser");
// will not affect metrics
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
// and will not trigger fallback logic
verify(failoverService, atLeastOnce()).activate();
}
}
@Test(expected = RuntimeOperationException.class)
public void testBlockUser() throws NotFoundException, ActivationException, OperationException {
try {
userService.blockUser("1"); // this method always throws ActivationException
} finally {
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
com.netflix.hystrix.HystrixInvokableInfo activateUserCommand = getHystrixCommandByKey("blockUser");
// will not affect metrics
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_FAILURE));
}
}
@Test(expected = NotFoundException.class)
public void testPropagateCauseException() throws NotFoundException {
userService.deleteUser("");
}
@Test(expected = UserException.class)
public void testUserExceptionThrownFromCommand() {
userService.userFailureWithoutFallback();
}
@Test
public void testHystrixExceptionThrownFromCommand() {
try {
userService.timedOutWithoutFallback();
} catch (HystrixRuntimeException e) {
assertEquals(TimeoutException.class, e.getCause().getClass());
} catch (Throwable e) {
assertTrue("'HystrixRuntimeException' is expected exception.", false);
}
}
@Test
public void testUserExceptionThrownFromFallback() {
try {
userService.userFailureWithFallback();
} catch (UserException e) {
assertEquals(1, e.level);
} catch (Throwable e) {
assertTrue("'UserException' is expected exception.", false);
}
}
@Test
public void testUserExceptionThrownFromFallbackCommand() {
try {
userService.userFailureWithFallbackCommand();
} catch (UserException e) {
assertEquals(2, e.level);
} catch (Throwable e) {
assertTrue("'UserException' is expected exception.", false);
}
}
@Test
public void testCommandAndFallbackErrorsComposition() {
try {
userService.commandAndFallbackErrorsComposition();
} catch (HystrixFlowException e) {
assertEquals(UserException.class, e.commandException.getClass());
assertEquals(UserException.class, e.fallbackException.getClass());
UserException commandException = (UserException) e.commandException;
UserException fallbackException = (UserException) e.fallbackException;
assertEquals(0, commandException.level);
assertEquals(1, fallbackException.level);
} catch (Throwable e) {
assertTrue("'HystrixFlowException' is expected exception.", false);
}
}
@Test
public void testCommandWithFallbackThatFailsByTimeOut() {
try {
userService.commandWithFallbackThatFailsByTimeOut();
} catch (HystrixRuntimeException e) {
assertEquals(TimeoutException.class, e.getCause().getClass());
} catch (Throwable e) {
assertTrue("'HystrixRuntimeException' is expected exception.", false);
}
}
@Test
public void testCommandWithNotWrappedExceptionAndNoFallback() {
try {
userService.throwNotWrappedCheckedExceptionWithoutFallback();
fail();
} catch (NotWrappedCheckedException e) {
// pass
} catch (Throwable e) {
fail("'NotWrappedCheckedException' is expected exception.");
}finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("throwNotWrappedCheckedExceptionWithoutFallback");
// record failure in metrics
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
// and will not trigger fallback logic
verify(failoverService, never()).activate();
}
}
@Test
public void testCommandWithNotWrappedExceptionAndFallback() {
try {
userService.throwNotWrappedCheckedExceptionWithFallback();
} catch (NotWrappedCheckedException e) {
fail();
} finally {
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo getUserCommand = getHystrixCommandByKey("throwNotWrappedCheckedExceptionWithFallback");
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(getUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
verify(failoverService).activate();
}
}
public static class UserService {
private FailoverService failoverService;
public void setFailoverService(FailoverService failoverService) {
this.failoverService = failoverService;
}
@HystrixCommand
public Object deleteUser(String id) throws NotFoundException {
throw new NotFoundException("");
}
@HystrixCommand(
commandKey = COMMAND_KEY,
ignoreExceptions = {
BadRequestException.class,
NotFoundException.class
},
fallbackMethod = "fallback")
public User getUserById(String id) throws NotFoundException {
validate(id);
if (!USERS.containsKey(id)) {
throw new NotFoundException("user with id: " + id + " not found");
}
return USERS.get(id);
}
@HystrixCommand(
ignoreExceptions = {BadRequestException.class, NotFoundException.class},
fallbackMethod = "activateFallback")
public void activateUser(String id) throws NotFoundException, ActivationException {
validate(id);
if (!USERS.containsKey(id)) {
throw new NotFoundException("user with id: " + id + " not found");
}
// always throw this exception
throw new ActivationException("user cannot be activate");
}
@HystrixCommand(
ignoreExceptions = {BadRequestException.class, NotFoundException.class},
fallbackMethod = "blockUserFallback")
public void blockUser(String id) throws NotFoundException, OperationException {
validate(id);
if (!USERS.containsKey(id)) {
throw new NotFoundException("user with id: " + id + " not found");
}
// always throw this exception
throw new OperationException("user cannot be blocked");
}
private User fallback(String id) {
return failoverService.getDefUser();
}
private void activateFallback(String id) {
failoverService.activate();
}
@HystrixCommand(ignoreExceptions = {RuntimeException.class})
private void blockUserFallback(String id) {
throw new RuntimeOperationException("blockUserFallback has failed");
}
private void validate(String val) throws BadRequestException {
if (val == null || val.length() == 0) {
throw new BadRequestException("parameter cannot be null ot empty");
}
}
@HystrixCommand
void throwNotWrappedCheckedExceptionWithoutFallback() throws NotWrappedCheckedException {
throw new NotWrappedCheckedException();
}
@HystrixCommand(fallbackMethod = "voidFallback")
void throwNotWrappedCheckedExceptionWithFallback() throws NotWrappedCheckedException {
throw new NotWrappedCheckedException();
}
private void voidFallback(){
failoverService.activate();
}
/*********************************************************************************/
@HystrixCommand
String userFailureWithoutFallback() throws UserException {
throw new UserException();
}
@HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1")})
String timedOutWithoutFallback() {
return "";
}
/*********************************************************************************/
@HystrixCommand(fallbackMethod = "userFailureWithFallback_f_0")
String userFailureWithFallback() {
throw new UserException();
}
String userFailureWithFallback_f_0() {
throw new UserException(1);
}
/*********************************************************************************/
@HystrixCommand(fallbackMethod = "userFailureWithFallbackCommand_f_0")
String userFailureWithFallbackCommand() {
throw new UserException(0);
}
@HystrixCommand(fallbackMethod = "userFailureWithFallbackCommand_f_1")
String userFailureWithFallbackCommand_f_0() {
throw new UserException(1);
}
@HystrixCommand
String userFailureWithFallbackCommand_f_1() {
throw new UserException(2);
}
/*********************************************************************************/
@HystrixCommand(fallbackMethod = "commandAndFallbackErrorsComposition_f_0")
String commandAndFallbackErrorsComposition() {
throw new UserException();
}
String commandAndFallbackErrorsComposition_f_0(Throwable commandError) {
throw new HystrixFlowException(commandError, new UserException(1));
}
/*********************************************************************************/
@HystrixCommand(fallbackMethod = "commandWithFallbackThatFailsByTimeOut_f_0")
String commandWithFallbackThatFailsByTimeOut() {
throw new UserException(0);
}
@HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1")})
String commandWithFallbackThatFailsByTimeOut_f_0() {
return "";
}
}
private class FailoverService {
public User getDefUser() {
return new User("def", "def");
}
public void activate() {
}
}
// exceptions
private static class NotFoundException extends Exception {
private NotFoundException(String message) {
super(message);
}
}
private static class BadRequestException extends RuntimeException {
private BadRequestException(String message) {
super(message);
}
}
private static class ActivationException extends Exception {
private ActivationException(String message) {
super(message);
}
}
private static class OperationException extends Throwable {
private OperationException(String message) {
super(message);
}
}
private static class RuntimeOperationException extends RuntimeException {
private RuntimeOperationException(String message) {
super(message);
}
}
private static class NotWrappedCheckedException extends Exception implements ExceptionNotWrappedByHystrix {
}
static class UserException extends RuntimeException {
final int level;
public UserException() {
this(0);
}
public UserException(int level) {
this.level = level;
}
}
static class HystrixFlowException extends RuntimeException {
final Throwable commandException;
final Throwable fallbackException;
public HystrixFlowException(Throwable commandException, Throwable fallbackException) {
this.commandException = commandException;
this.fallbackException = fallbackException;
}
}
}
| 4,411 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/error/BasicDefaultRaiseHystrixExceptionsTest.java | package com.netflix.hystrix.contrib.javanica.test.common.error;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.netflix.hystrix.Hystrix;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import rx.Observable;
import rx.observers.TestSubscriber;
/**
* Created by Mike Cowan
*/
public abstract class BasicDefaultRaiseHystrixExceptionsTest {
private Service service;
@Before
public void setUp() throws Exception {
service = createService();
}
protected abstract Service createService();
@Test(expected = BadRequestException.class)
public void testDefaultIgnoreException() {
service.commandInheritsDefaultIgnoreExceptions();
}
@Test(expected = SpecificException.class)
public void testCommandOverridesDefaultIgnoreExceptions() {
service.commandOverridesDefaultIgnoreExceptions(SpecificException.class);
}
@Test(expected = HystrixRuntimeException.class)
public void testCommandOverridesDefaultIgnoreExceptions_nonIgnoreExceptionShouldBePropagated() {
// method throws BadRequestException that isn't ignored
service.commandOverridesDefaultIgnoreExceptions(BadRequestException.class);
}
@Ignore // https://github.com/Netflix/Hystrix/issues/993#issuecomment-229542203
@Test(expected = BadRequestException.class)
public void testFallbackCommandInheritsDefaultIgnoreException() {
service.commandWithFallbackInheritsDefaultIgnoreExceptions();
}
@Ignore // https://github.com/Netflix/Hystrix/issues/993#issuecomment-229542203
@Test(expected = SpecificException.class)
public void testFallbackCommandOverridesDefaultIgnoreExceptions() {
service.commandWithFallbackOverridesDefaultIgnoreExceptions(SpecificException.class);
}
@Test(expected = HystrixRuntimeException.class)
public void testFallbackCommandOverridesDefaultIgnoreExceptions_nonIgnoreExceptionShouldBePropagated() {
service.commandWithFallbackOverridesDefaultIgnoreExceptions(BadRequestException.class);
}
@Test(expected = HystrixRuntimeException.class)
public void testRaiseHystrixRuntimeException() {
service.commandShouldRaiseHystrixRuntimeException();
}
@Test
public void testObservableRaiseHystrixRuntimeException() {
TestSubscriber<Void> testSubscriber = new TestSubscriber<Void>();
service.observableCommandShouldRaiseHystrixRuntimeException().subscribe(testSubscriber);
testSubscriber.assertError(HystrixRuntimeException.class);
}
@DefaultProperties(ignoreExceptions = BadRequestException.class, raiseHystrixExceptions = {HystrixException.RUNTIME_EXCEPTION})
public static class Service {
@HystrixCommand
public Object commandShouldRaiseHystrixRuntimeException() throws SpecificException {
throw new SpecificException("from 'commandShouldRaiseHystrixRuntimeException'");
}
@HystrixCommand
public Observable<Void> observableCommandShouldRaiseHystrixRuntimeException() throws SpecificException {
return Observable.error(new SpecificException("from 'observableCommandShouldRaiseHystrixRuntimeException'"));
}
@HystrixCommand
public Object commandInheritsDefaultIgnoreExceptions() throws BadRequestException {
// this exception will be ignored (wrapped in HystrixBadRequestException) because specified in default ignore exceptions
throw new BadRequestException("from 'commandInheritsIgnoreExceptionsFromDefault'");
}
@HystrixCommand(ignoreExceptions = SpecificException.class)
public Object commandOverridesDefaultIgnoreExceptions(Class<? extends Throwable> errorType) throws BadRequestException, SpecificException {
if(errorType.equals(BadRequestException.class)){
// isn't ignored because command doesn't specify this exception type in 'ignoreExceptions'
throw new BadRequestException("from 'commandOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
// something went wrong, this error is ignored because specified in the command's ignoreExceptions
throw new SpecificException("from 'commandOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
@HystrixCommand(fallbackMethod = "fallbackInheritsDefaultIgnoreExceptions")
public Object commandWithFallbackInheritsDefaultIgnoreExceptions() throws SpecificException {
// isn't ignored, need to trigger fallback
throw new SpecificException("from 'commandWithFallbackInheritsDefaultIgnoreExceptions'");
}
@HystrixCommand
private Object fallbackInheritsDefaultIgnoreExceptions() throws BadRequestException {
// should be ignored because specified in global ignore exception, fallback command inherits default ignore exceptions
throw new BadRequestException("from 'fallbackInheritsDefaultIgnoreExceptions'");
}
@HystrixCommand(fallbackMethod = "fallbackOverridesDefaultIgnoreExceptions")
public Object commandWithFallbackOverridesDefaultIgnoreExceptions(Class<? extends Throwable> errorType) {
// isn't ignored, need to trigger fallback
throw new SpecificException();
}
@HystrixCommand(ignoreExceptions = SpecificException.class)
private Object fallbackOverridesDefaultIgnoreExceptions(Class<? extends Throwable> errorType) {
if(errorType.equals(BadRequestException.class)){
// isn't ignored because fallback doesn't specify this exception type in 'ignoreExceptions'
throw new BadRequestException("from 'fallbackOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
// something went wrong, this error is ignored because specified in the fallback's ignoreExceptions
throw new SpecificException("from 'commandOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
}
public static final class BadRequestException extends RuntimeException {
public BadRequestException() {
}
public BadRequestException(String message) {
super(message);
}
}
public static final class SpecificException extends RuntimeException {
public SpecificException() {
}
public SpecificException(String message) {
super(message);
}
}
}
| 4,412 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/error/BasicDefaultIgnoreExceptionsTest.java | package com.netflix.hystrix.contrib.javanica.test.common.error;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test for {@link DefaultProperties#ignoreExceptions()} feature.
*
* <p>
* Created by dmgcodevil.
*/
public abstract class BasicDefaultIgnoreExceptionsTest {
private Service service;
@Before
public void setUp() throws Exception {
service = createService();
}
protected abstract Service createService();
@Test(expected = BadRequestException.class)
public void testDefaultIgnoreException() {
service.commandInheritsDefaultIgnoreExceptions();
}
@Test(expected = SpecificException.class)
public void testCommandOverridesDefaultIgnoreExceptions() {
service.commandOverridesDefaultIgnoreExceptions(SpecificException.class);
}
@Test(expected = BadRequestException.class)
public void testCommandOverridesDefaultIgnoreExceptions_nonIgnoreExceptionShouldBePropagated() {
// method throws BadRequestException that isn't ignored
service.commandOverridesDefaultIgnoreExceptions(BadRequestException.class);
}
@Ignore // https://github.com/Netflix/Hystrix/issues/993#issuecomment-229542203
@Test(expected = BadRequestException.class)
public void testFallbackCommandInheritsDefaultIgnoreException() {
service.commandWithFallbackInheritsDefaultIgnoreExceptions();
}
@Ignore // https://github.com/Netflix/Hystrix/issues/993#issuecomment-229542203
@Test(expected = SpecificException.class)
public void testFallbackCommandOverridesDefaultIgnoreExceptions() {
service.commandWithFallbackOverridesDefaultIgnoreExceptions(SpecificException.class);
}
@Test(expected = BadRequestException.class)
public void testFallbackCommandOverridesDefaultIgnoreExceptions_nonIgnoreExceptionShouldBePropagated() {
service.commandWithFallbackOverridesDefaultIgnoreExceptions(BadRequestException.class);
}
@DefaultProperties(ignoreExceptions = BadRequestException.class)
public static class Service {
@HystrixCommand
public Object commandInheritsDefaultIgnoreExceptions() throws BadRequestException {
// this exception will be ignored (wrapped in HystrixBadRequestException) because specified in default ignore exceptions
throw new BadRequestException("from 'commandInheritsIgnoreExceptionsFromDefault'");
}
@HystrixCommand(ignoreExceptions = SpecificException.class)
public Object commandOverridesDefaultIgnoreExceptions(Class<? extends Throwable> errorType) throws BadRequestException, SpecificException {
if(errorType.equals(BadRequestException.class)){
// isn't ignored because command doesn't specify this exception type in 'ignoreExceptions'
throw new BadRequestException("from 'commandOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
// something went wrong, this error is ignored because specified in the command's ignoreExceptions
throw new SpecificException("from 'commandOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
@HystrixCommand(fallbackMethod = "fallbackInheritsDefaultIgnoreExceptions")
public Object commandWithFallbackInheritsDefaultIgnoreExceptions() throws SpecificException {
// isn't ignored, need to trigger fallback
throw new SpecificException("from 'commandWithFallbackInheritsDefaultIgnoreExceptions'");
}
@HystrixCommand
private Object fallbackInheritsDefaultIgnoreExceptions() throws BadRequestException {
// should be ignored because specified in global ignore exception, fallback command inherits default ignore exceptions
throw new BadRequestException("from 'fallbackInheritsDefaultIgnoreExceptions'");
}
@HystrixCommand(fallbackMethod = "fallbackOverridesDefaultIgnoreExceptions")
public Object commandWithFallbackOverridesDefaultIgnoreExceptions(Class<? extends Throwable> errorType) {
// isn't ignored, need to trigger fallback
throw new SpecificException();
}
@HystrixCommand(ignoreExceptions = SpecificException.class)
private Object fallbackOverridesDefaultIgnoreExceptions(Class<? extends Throwable> errorType) {
if(errorType.equals(BadRequestException.class)){
// isn't ignored because fallback doesn't specify this exception type in 'ignoreExceptions'
throw new BadRequestException("from 'fallbackOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
// something went wrong, this error is ignored because specified in the fallback's ignoreExceptions
throw new SpecificException("from 'commandOverridesDefaultIgnoreExceptions', cause: " + errorType.getSimpleName());
}
}
public static final class BadRequestException extends RuntimeException {
public BadRequestException() {
}
public BadRequestException(String message) {
super(message);
}
}
public static final class SpecificException extends RuntimeException {
public SpecificException() {
}
public SpecificException(String message) {
super(message);
}
}
}
| 4,413 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/domain/Profile.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.test.common.domain;
/**
* Created by dmgcodevil on 1/9/2015.
*/
public class Profile {
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| 4,414 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/domain/User.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.test.common.domain;
/**
* Simple domain object for tests.
*/
public class User extends Domain{
private String id;
private String name;
private Profile profile;
public User() {
}
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("id='").append(id).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(!(o instanceof User)) {
return false;
}
User user = (User) o;
if(id != null ? !id.equals(user.id) : user.id != null) {
return false;
}
if(name != null ? !name.equals(user.name) : user.name != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
| 4,415 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/domain/Domain.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.common.domain;
public class Domain {
}
| 4,416 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration/fallback/FallbackDefaultPropertiesTest.java | package com.netflix.hystrix.contrib.javanica.test.spring.configuration.fallback;
import com.netflix.hystrix.contrib.javanica.test.common.configuration.fallback.BasicFallbackDefaultPropertiesTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, FallbackDefaultPropertiesTest.Config.class})
public class FallbackDefaultPropertiesTest extends BasicFallbackDefaultPropertiesTest {
@Autowired
private Service service;
@Override
protected Service createService() {
return service;
}
@Configurable
public static class Config {
@Bean
public BasicFallbackDefaultPropertiesTest.Service service() {
return new BasicFallbackDefaultPropertiesTest.Service();
}
}
}
| 4,417 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration/collapser/CollapserPropertiesTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.configuration.collapser;
import com.netflix.hystrix.contrib.javanica.test.common.configuration.collapser.BasicCollapserPropertiesTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, CollapserPropertiesTest.CollapserPropertiesTestConfig.class})
public class CollapserPropertiesTest extends BasicCollapserPropertiesTest {
@Autowired
private UserService userService;
@Override
protected UserService createUserService() {
return userService;
}
@Configurable
public static class CollapserPropertiesTestConfig {
@Bean
public BasicCollapserPropertiesTest.UserService userService() {
return new UserService();
}
}
}
| 4,418 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration/command/CommandPropertiesTest.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.test.spring.configuration.command;
import com.netflix.hystrix.contrib.javanica.test.common.configuration.command.BasicCommandPropertiesTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, CommandPropertiesTest.CommandPropertiesTestConfig.class})
public class CommandPropertiesTest extends BasicCommandPropertiesTest {
@Autowired
private BasicCommandPropertiesTest.UserService userService;
@Override
protected UserService createUserService() {
return userService;
}
@Configurable
public static class CommandPropertiesTestConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
}
| 4,419 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/configuration/command/CommandDefaultPropertiesTest.java | package com.netflix.hystrix.contrib.javanica.test.spring.configuration.command;
import com.netflix.hystrix.contrib.javanica.test.common.configuration.command.BasicCommandDefaultPropertiesTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by dmgcodevil.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, CommandDefaultPropertiesTest.Config.class})
public class CommandDefaultPropertiesTest extends BasicCommandDefaultPropertiesTest {
@Autowired
private Service service;
@Override
protected Service createService() {
return service;
}
@Configurable
public static class Config {
@Bean
@Scope(value = "prototype")
public BasicCommandDefaultPropertiesTest.Service service() {
return new BasicCommandDefaultPropertiesTest.Service();
}
}
}
| 4,420 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/cache/CacheTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.cache;
import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCacheAspect;
import com.netflix.hystrix.contrib.javanica.test.common.cache.BasicCacheTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test to check cache implementation based on JSR-107.
*
* @author dmgcodevil
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, CacheTest.CacheTestConfig.class})
public class CacheTest extends BasicCacheTest {
@Autowired
private ApplicationContext applicationContext;
@Override
protected UserService createUserService() {
return applicationContext.getBean(UserService.class);
}
/**
* Spring configuration.
*/
@Configurable
public static class CacheTestConfig {
@Bean
@Scope(value = "prototype")
public UserService userService() {
return new UserService();
}
@Bean
public HystrixCacheAspect hystrixCacheAspect() {
return new HystrixCacheAspect();
}
}
} | 4,421 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/fallback/DefaultFallbackTest.java | package com.netflix.hystrix.contrib.javanica.test.spring.fallback;
import com.netflix.hystrix.contrib.javanica.test.common.fallback.BasicDefaultFallbackTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by dmgcodevil.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, DefaultFallbackTest.Config.class})
public class DefaultFallbackTest extends BasicDefaultFallbackTest {
@Autowired
private ServiceWithDefaultFallback serviceWithDefaultFallback;
@Autowired
private ServiceWithDefaultCommandFallback serviceWithDefaultCommandFallback;
@Override
protected ServiceWithDefaultFallback createServiceWithDefaultFallback() {
return serviceWithDefaultFallback;
}
@Override
protected ServiceWithDefaultCommandFallback serviceWithDefaultCommandFallback() {
return serviceWithDefaultCommandFallback;
}
@Configurable
public static class Config {
@Bean
public ServiceWithDefaultFallback serviceWithDefaultFallback() {
return new ServiceWithDefaultFallback();
}
@Bean
public ServiceWithDefaultCommandFallback serviceWithDefaultCommandFallback() {
return new ServiceWithDefaultCommandFallback();
}
}
}
| 4,422 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/fallback/CommandFallbackTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.fallback;
import com.netflix.hystrix.contrib.javanica.test.common.fallback.BasicCommandFallbackTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test covers "Fallback" functionality.
* <p/>
* https://github.com/Netflix/Hystrix/wiki/How-To-Use#Fallback
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, CommandFallbackTest.CommandTestConfig.class})
public class CommandFallbackTest extends BasicCommandFallbackTest {
@Autowired
private UserService userService;
@Override
protected BasicCommandFallbackTest.UserService createUserService() {
return userService;
}
@Configurable
public static class CommandTestConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
}
| 4,423 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/fallback/InheritedFallbackTest.java | package com.netflix.hystrix.contrib.javanica.test.spring.fallback;
import com.netflix.hystrix.contrib.javanica.test.common.fallback.BasicCommandFallbackTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by dmgcodevil.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, InheritedFallbackTest.CommandTestConfig.class})
public class InheritedFallbackTest extends BasicCommandFallbackTest {
@Autowired
private UserService userService;
@Override
protected BasicCommandFallbackTest.UserService createUserService() {
return userService;
}
@Configurable
public static class CommandTestConfig {
@Bean
public UserService userService() {
return new SubClass();
}
}
public static class SubClass extends BasicCommandFallbackTest.UserService {
}
} | 4,424 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/fallback/GenericFallbackTest.java | package com.netflix.hystrix.contrib.javanica.test.spring.fallback;
import com.netflix.hystrix.contrib.javanica.test.common.fallback.BasicGenericFallbackTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
/**
* Created by dmgcodevil.
*/
@ContextConfiguration(classes = {AopCglibConfig.class})
public class GenericFallbackTest extends BasicGenericFallbackTest {
@Autowired
private ApplicationContext applicationContext;
@Override
protected <T> T createProxy(Class<T> t) {
AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
return beanFactory.createBean(t);
}
}
| 4,425 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/collapser/CollapserTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.collapser;
import com.netflix.hystrix.contrib.javanica.test.common.collapser.BasicCollapserTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This test covers "Request Collapsing" functionality.
* <p/>
* https://github.com/Netflix/Hystrix/wiki/How-To-Use#Collapsing
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, CollapserTest.CollapserTestConfig.class})
public class CollapserTest extends BasicCollapserTest {
@Autowired
private BasicCollapserTest.UserService userService;
@Override
protected UserService createUserService() {
return userService;
}
/**
* Spring configuration.
*/
@Configurable
public static class CollapserTestConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
}
| 4,426 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/observable/ObservableTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.observable;
import com.netflix.hystrix.contrib.javanica.test.common.observable.BasicObservableTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test covers "Reactive Execution" functionality.
* https://github.com/Netflix/Hystrix/wiki/How-To-Use#Reactive-Execution
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, ObservableTest.ObservableTestConfig.class})
public class ObservableTest extends BasicObservableTest {
@Autowired
private UserService userService;
@Override
protected UserService createUserService() {
return userService;
}
@Configurable
public static class ObservableTestConfig {
@Bean
public BasicObservableTest.UserService userService() {
return new UserService();
}
}
}
| 4,427 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/command/CommandTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.command;
import com.netflix.hystrix.contrib.javanica.test.common.command.BasicCommandTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
/**
* This test covers "Hystrix command" functionality.
* <p/>
* https://github.com/Netflix/Hystrix/wiki/How-To-Use#Synchronous-Execution
* https://github.com/Netflix/Hystrix/wiki/How-To-Use#Asynchronous-Execution
*/
public abstract class CommandTest extends BasicCommandTest {
@Autowired private BasicCommandTest.UserService userService;
@Autowired private BasicCommandTest.AdvancedUserService advancedUserService;
@Autowired private BasicCommandTest.GenericService<String, Long, User> genericUserService;
@Override
protected BasicCommandTest.UserService createUserService() {
return userService;
}
@Override
protected BasicCommandTest.AdvancedUserService createAdvancedUserServiceService() {
return advancedUserService;
}
@Override
protected BasicCommandTest.GenericService<String, Long, User> createGenericUserService() {
return genericUserService;
}
@Configurable
public static class CommandTestConfig {
@Bean
public UserService userService() {
return new UserService();
}
@Bean
public AdvancedUserService advancedUserService() {
return new AdvancedUserService();
}
@Bean
public GenericService<String, Long, User> genericUserService() {
return new GenericUserService();
}
}
}
| 4,428 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/command | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/command/jdk/CommandJdkProxyTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.spring.command.jdk;
import com.netflix.hystrix.contrib.javanica.test.spring.command.CommandTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopJdkConfig;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopJdkConfig.class, CommandTest.CommandTestConfig.class})
public class CommandJdkProxyTest extends CommandTest {
}
| 4,429 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/command | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/command/cglib/CommandCGlibProxyTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.spring.command.cglib;
import com.netflix.hystrix.contrib.javanica.test.spring.command.CommandTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, CommandTest.CommandTestConfig.class})
public class CommandCGlibProxyTest extends CommandTest {
}
| 4,430 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/conf/SpringApplicationContext.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.test.spring.conf;
import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@Configurable
@ComponentScan("com.netflix.hystrix.contrib.javanica.test.spring")
public class SpringApplicationContext {
@Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
}
| 4,431 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/conf/AopCglibConfig.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.test.spring.conf;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
@Configurable
@Import(SpringApplicationContext.class)
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AopCglibConfig {
}
| 4,432 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/conf/AopJdkConfig.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.test.spring.conf;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
@Configurable
@Import(SpringApplicationContext.class)
@EnableAspectJAutoProxy
public class AopJdkConfig {
}
| 4,433 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/conf/AopLoadTimeWeavingConfig.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.test.spring.conf;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.Import;
@Configurable
@Import(SpringApplicationContext.class)
@EnableAspectJAutoProxy
@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
public class AopLoadTimeWeavingConfig {
}
| 4,434 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/error/ObservableErrorPropagationTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.error;
import com.netflix.hystrix.contrib.javanica.test.common.error.BasicObservableErrorPropagationTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test covers "Error Propagation" functionality.
* https://github.com/Netflix/Hystrix/wiki/How-To-Use#ErrorPropagation
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, ObservableErrorPropagationTest.ErrorPropagationTestConfig.class})
public class ObservableErrorPropagationTest extends BasicObservableErrorPropagationTest {
@Autowired
private UserService userService;
@Override
protected UserService createUserService() {
return userService;
}
@Configurable
public static class ErrorPropagationTestConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
}
| 4,435 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/error/DefaultIgnoreExceptionsTest.java | package com.netflix.hystrix.contrib.javanica.test.spring.error;
import com.netflix.hystrix.contrib.javanica.test.common.error.BasicDefaultIgnoreExceptionsTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by dmgcodevil.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, DefaultIgnoreExceptionsTest.DefaultIgnoreExceptionsTestConfig.class})
public class DefaultIgnoreExceptionsTest extends BasicDefaultIgnoreExceptionsTest {
@Autowired
private BasicDefaultIgnoreExceptionsTest.Service service;
@Override
protected BasicDefaultIgnoreExceptionsTest.Service createService() {
return service;
}
@Configurable
public static class DefaultIgnoreExceptionsTestConfig {
@Bean
public BasicDefaultIgnoreExceptionsTest.Service userService() {
return new BasicDefaultIgnoreExceptionsTest.Service();
}
}
}
| 4,436 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/error/ErrorPropagationTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.test.spring.error;
import com.netflix.hystrix.contrib.javanica.test.common.error.BasicErrorPropagationTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test covers "Error Propagation" functionality.
* https://github.com/Netflix/Hystrix/wiki/How-To-Use#ErrorPropagation
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, ErrorPropagationTest.ErrorPropagationTestConfig.class})
public class ErrorPropagationTest extends BasicErrorPropagationTest {
@Autowired
private BasicErrorPropagationTest.UserService userService;
@Override
protected UserService createUserService() {
return userService;
}
@Configurable
public static class ErrorPropagationTestConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
}
| 4,437 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/error/DefaultRaiseHystrixExceptionsTest.java | package com.netflix.hystrix.contrib.javanica.test.spring.error;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.netflix.hystrix.contrib.javanica.test.common.error.BasicDefaultRaiseHystrixExceptionsTest;
import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopCglibConfig;
/**
* Created by Mike Cowan
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AopCglibConfig.class, DefaultRaiseHystrixExceptionsTest.DefaultRaiseHystrixExceptionsTestConfig.class})
public class DefaultRaiseHystrixExceptionsTest extends BasicDefaultRaiseHystrixExceptionsTest {
@Autowired
private BasicDefaultRaiseHystrixExceptionsTest.Service service;
@Override
protected BasicDefaultRaiseHystrixExceptionsTest.Service createService() {
return service;
}
@Configurable
public static class DefaultRaiseHystrixExceptionsTestConfig {
@Bean
public BasicDefaultRaiseHystrixExceptionsTest.Service userService() {
return new BasicDefaultRaiseHystrixExceptionsTest.Service();
}
}
}
| 4,438 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/FallbackMethodValidationTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util;
import com.google.common.base.Throwables;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException;
import com.netflix.hystrix.contrib.javanica.utils.FallbackMethod;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Observable;
import java.lang.reflect.Method;
import java.util.concurrent.Future;
/**
* Created by dmgcodevil.
*/
@RunWith(DataProviderRunner.class)
public class FallbackMethodValidationTest {
@DataProvider
public static Object[][] fail() {
// @formatter:off
return new Object[][]{
// sync execution
{getMethod("commandReturnPlainTypeLong"), getMethod("fallbackReturnPlainTypeString")},
{getMethod("commandReturnPlainTypeChild"), getMethod("fallbackReturnPlainTypeParent")},
{getMethod("commandReturnGenericTypeParent"), getMethod("fallbackReturnGenericTypeChild")},
{getMethod("commandReturnGenericTypeChild"), getMethod("fallbackReturnGenericTypeParent")},
{getMethod("commandReturnGenericTypeChildParent"), getMethod("fallbackReturnGenericTypeParentChild")},
{getMethod("commandReturnGenericTypeParentChild"), getMethod("fallbackReturnGenericTypeChildParent")},
{getMethod("commandReturnGenericNestedTypeParentChildParent"), getMethod("commandReturnGenericNestedTypeParentParentParent")},
// async execution
{getMethod("commandReturnFutureParent"), getMethod("fallbackCommandReturnFutureChild")},
{getMethod("commandReturnFutureParent"), getMethod("fallbackReturnFutureParent")},
{getMethod("commandReturnFutureParent"), getMethod("fallbackReturnChild")},
{getMethod("commandReturnParent"), getMethod("fallbackReturnFutureParent")},
{getMethod("commandReturnParent"), getMethod("fallbackCommandReturnFutureParent")},
// observable execution
{getMethod("fallbackReturnObservableParent"), getMethod("fallbackReturnObservableChild")},
{getMethod("fallbackReturnObservableParent"), getMethod("fallbackCommandReturnObservableChild")},
{getMethod("fallbackReturnObservableParent"), getMethod("fallbackReturnChild")},
{getMethod("commandReturnParent"), getMethod("fallbackReturnObservableParent")},
{getMethod("commandReturnParent"), getMethod("fallbackCommandReturnObservableParent")},
{getMethod("commandReturnParent"), getMethod("fallbackReturnObservableChild")},
{getMethod("commandReturnParent"), getMethod("fallbackCommandReturnObservableChild")},
};
// @formatter:on
}
@DataProvider
public static Object[][] success() {
// @formatter:off
return new Object[][]{
// sync execution
{getMethod("commandReturnPlainTypeLong"), getMethod("fallbackReturnPlainTypeLong")},
{getMethod("commandReturnPlainTypeParent"), getMethod("fallbackReturnPlainTypeChild")},
{getMethod("commandReturnPlainTypeParent"), getMethod("fallbackReturnPlainTypeParent")},
{getMethod("commandReturnGenericTypeChild"), getMethod("fallbackReturnGenericTypeChild")},
{getMethod("commandReturnGenericNestedTypeParentChildParent"), getMethod("fallbackReturnGenericNestedTypeParentChildParent")},
// async execution
{getMethod("commandReturnFutureParent"), getMethod("fallbackCommandReturnFutureParent")},
{getMethod("commandReturnFutureParent"), getMethod("fallbackCommandReturnParent")},
{getMethod("commandReturnFutureParent"), getMethod("fallbackReturnParent")},
// observable execution
{getMethod("commandReturnObservableParent"), getMethod("fallbackReturnObservableParent")},
{getMethod("commandReturnObservableParent"), getMethod("fallbackCommandReturnObservableParent")},
{getMethod("commandReturnObservableParent"), getMethod("fallbackReturnParent")},
};
// @formatter:on
}
@Test(expected = FallbackDefinitionException.class)
@UseDataProvider("fail")
public void testValidateBadFallbackReturnType(Method commandMethod, Method fallbackMethod) {
new FallbackMethod(fallbackMethod).validateReturnType(commandMethod);
}
@UseDataProvider("success")
public void testValidateCorrectFallbackReturnType(Method commandMethod, Method fallbackMethod) {
new FallbackMethod(fallbackMethod).validateReturnType(commandMethod);
}
private static Method getMethod(String name) {
try {
return Service.class.getDeclaredMethod(name);
} catch (NoSuchMethodException e) {
throw Throwables.propagate(e);
}
}
// @formatter:off
private static class Service {
// Sync execution
public Parent commandReturnPlainTypeParent() {return null;}
public Child commandReturnPlainTypeChild() {return null;}
public Parent fallbackReturnPlainTypeParent() {return null;}
public Child fallbackReturnPlainTypeChild() {return null;}
public Long commandReturnPlainTypeLong() {return null;}
public Long fallbackReturnPlainTypeLong() {return null;}
public String fallbackReturnPlainTypeString() {return null;}
public GType<Parent> commandReturnGenericTypeParent() {return null;}
public GType<Child> commandReturnGenericTypeChild() {return null;}
public GType<Parent> fallbackReturnGenericTypeParent() {return null;}
public GType<Child> fallbackReturnGenericTypeChild() {return null;}
public GDoubleType<Parent, Child> commandReturnGenericTypeParentChild() {return null;}
public GDoubleType<Child, Parent> commandReturnGenericTypeChildParent() {return null;}
public GDoubleType<Parent, Child> fallbackReturnGenericTypeParentChild() {return null;}
public GDoubleType<Child, Parent> fallbackReturnGenericTypeChildParent() {return null;}
public GType<GType<GDoubleType<GType<GDoubleType<Parent, Child>>, Parent>>> commandReturnGenericNestedTypeParentChildParent() {return null;}
public GType<GType<GDoubleType<GType<GDoubleType<Parent, Parent>>, Parent>>> commandReturnGenericNestedTypeParentParentParent() {return null;}
public GType<GType<GDoubleType<GType<GDoubleType<Parent, Child>>, Parent>>> fallbackReturnGenericNestedTypeParentChildParent() {return null;}
// Async execution
Future<Parent> commandReturnFutureParent() {return null;}
Parent commandReturnParent() {return null;}
Parent fallbackReturnParent() {return null;}
Child fallbackReturnChild() {return null;}
Future<Parent> fallbackReturnFutureParent() {return null;}
Future<Child> fallbackReturnFutureChild() {return null;}
@HystrixCommand Parent fallbackCommandReturnParent() {return null;}
@HystrixCommand Child fallbackCommandReturnChild() {return null;}
@HystrixCommand Future<Parent> fallbackCommandReturnFutureParent() {return null;}
@HystrixCommand Future<Child> fallbackCommandReturnFutureChild() {return null;}
// Observable execution
Observable<Parent> commandReturnObservableParent() {return null;}
Observable<Parent> fallbackReturnObservableParent() {return null;}
Observable<Child> fallbackReturnObservableChild() {return null;}
@HystrixCommand Observable<Parent> fallbackCommandReturnObservableParent() {return null;}
@HystrixCommand Observable<Child> fallbackCommandReturnObservableChild() {return null;}
}
// @formatter:on
private interface GType<T> {
}
private interface GDoubleType<T1, T2> {
}
private static class Parent {
}
private static class Child extends Parent {
}
}
| 4,439 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/FallbackMethodTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.utils.MethodProvider;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.Method;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Created by dmgcodevil.
*/
@RunWith(DataProviderRunner.class)
public class FallbackMethodTest {
@Test
public void testGetExtendedFallback() throws NoSuchMethodException {
// given
Method command = Service.class.getDeclaredMethod("command", String.class, Integer.class);
// when
Method extFallback = MethodProvider.getInstance().getFallbackMethod(Service.class, command).getMethod();
// then
assertParamsTypes(extFallback, String.class, Integer.class, Throwable.class);
}
@Test
@DataProvider({"true", "false"})
public void testGetFallbackForExtendedCommand(boolean extended) throws NoSuchMethodException {
// given
Method extFallback = Service.class.getDeclaredMethod("extCommand", String.class, Integer.class, Throwable.class);
// when
Method fallback = MethodProvider.getInstance().getFallbackMethod(Service.class, extFallback, extended).getMethod();
// then
assertParamsTypes(fallback, String.class, Integer.class, Throwable.class);
}
public void testGetFallbackForExtendedCommandV2() throws NoSuchMethodException {
// given
Method extFallback = Service.class.getDeclaredMethod("extCommandV2", String.class, Integer.class, Throwable.class);
// when
Method fallback = MethodProvider.getInstance().getFallbackMethod(Service.class, extFallback, true).getMethod();
// then
assertParamsTypes(fallback, String.class, Integer.class);
}
public void testGetFallbackForExtendedCommandV2_extendedParameterFalse() throws NoSuchMethodException {
// given
Method extFallback = Service.class.getDeclaredMethod("extCommandV2", String.class, Integer.class, Throwable.class);
// when
Method fallback = MethodProvider.getInstance().getFallbackMethod(Service.class, extFallback, false).getMethod();
// then
assertNull(fallback);
}
private static void assertParamsTypes(Method method, Class<?>... expected) {
assertEquals(expected.length, method.getParameterTypes().length);
Class<?>[] actual = method.getParameterTypes();
assertArrayEquals(expected, actual);
}
private static class Common {
private String fallback(String s, Integer i) {
return null;
}
private String fallbackV2(String s, Integer i) {
return null;
}
}
private static class Service extends Common{
@HystrixCommand(fallbackMethod = "fallback")
public String command(String s, Integer i) {
return null;
}
@HystrixCommand(fallbackMethod = "fallback")
public String extCommand(String s, Integer i, Throwable throwable) {
return null;
}
@HystrixCommand(fallbackMethod = "fallbackV2")
public String extCommandV2(String s, Integer i, Throwable throwable) {
return null;
}
public String fallback(String s, Integer i, Throwable throwable) {
return null;
}
}
}
| 4,440 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/GetMethodTest.java | package com.netflix.hystrix.contrib.javanica.util;
import com.google.common.base.Optional;
import com.netflix.hystrix.contrib.javanica.utils.MethodProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by dmgcodevil.
*/
@RunWith(Parameterized.class)
public class GetMethodTest {
private String methodName;
private Class<?>[] parametersTypes;
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "foo", new Class<?>[]{ String.class } },
{ "bar", new Class<?>[]{ Integer.class } }
});
}
public GetMethodTest(String methodName, Class<?>[] parametersTypes) {
this.methodName = methodName;
this.parametersTypes = parametersTypes;
}
@Test
public void testGetMethodFoo(){
Optional<Method> method = MethodProvider.getInstance().getMethod(C.class, methodName, parametersTypes);
assertTrue(method.isPresent());
assertEquals(methodName, method.get().getName());
}
public static class A { void foo(String in) {} }
public static class B extends A { void bar(Integer in) {} }
public static class C extends B{ }
} | 4,441 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/bridge/Child.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util.bridge;
/**
* Created by dmgcodevil.
*/
public class Child extends Parent {
}
| 4,442 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/bridge/GenericInterfaceImpl.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util.bridge;
/**
* Created by dmgcodevil
*/
public class GenericInterfaceImpl implements GenericInterface<Child, Parent> {
public Child foo(SubChild c) {
return null;
}
@Override
public Child foo(Child c) {
return null;
}
public Child foo(Parent c) {
return null;
}
}
| 4,443 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/bridge/GenericInterface.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util.bridge;
/**
* Created by dmgcodevil
*/
public interface GenericInterface<P1, R extends Parent> {
R foo(P1 p1);
}
| 4,444 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/bridge/UnbridgeMethodTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util.bridge;
import com.netflix.hystrix.contrib.javanica.utils.MethodProvider;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Method;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Created by dmgcodevil
*/
public class UnbridgeMethodTest {
@Test
public void testUnbridgeFoo() throws NoSuchMethodException, IOException, ClassNotFoundException {
// given
Method bridgeMethod = getBridgeMethod(GenericInterfaceImpl.class, "foo");
assertNotNull(bridgeMethod);
// when
Method genMethod = MethodProvider.getInstance().unbride(bridgeMethod, GenericInterfaceImpl.class);
// then
assertNotNull(bridgeMethod);
assertReturnType(Child.class, genMethod);
assertParamsTypes(genMethod, Child.class);
}
private static Method getBridgeMethod(Class<?> type, String methodName) {
for (Method method : type.getDeclaredMethods()) {
if (method.isBridge() && method.getName().equals(methodName)) {
return method;
}
}
return null;
}
private static void assertReturnType(Class<?> expected, Method method) {
assertEquals(expected, method.getReturnType());
}
private static void assertParamsTypes(Method method, Class<?>... expected) {
assertEquals(expected.length, method.getParameterTypes().length);
Class<?>[] actual = method.getParameterTypes();
assertArrayEquals(expected, actual);
}
}
| 4,445 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/bridge/Parent.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util.bridge;
public class Parent {
}
| 4,446 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/util/bridge/SubChild.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.util.bridge;
/**
* Created by dmgcodevil.
*/
public class SubChild extends Child {
}
| 4,447 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/command/ExecutionTypeTest.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.command;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import rx.Observable;
import rx.internal.operators.OperatorMulticast;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableFuture;
import static com.netflix.hystrix.contrib.javanica.command.ExecutionType.ASYNCHRONOUS;
import static com.netflix.hystrix.contrib.javanica.command.ExecutionType.OBSERVABLE;
import static com.netflix.hystrix.contrib.javanica.command.ExecutionType.SYNCHRONOUS;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class ExecutionTypeTest {
@Parameterized.Parameters
public static List<Object[]> data() {
return asList(new Object[][]{
{returnType(Integer.class), shouldHaveExecutionType(SYNCHRONOUS)},
{returnType(List.class), shouldHaveExecutionType(SYNCHRONOUS)},
{returnType(Object.class), shouldHaveExecutionType(SYNCHRONOUS)},
{returnType(Class.class), shouldHaveExecutionType(SYNCHRONOUS)},
{returnType(Future.class), shouldHaveExecutionType(ASYNCHRONOUS)},
{returnType(AsyncResult.class), shouldHaveExecutionType(ASYNCHRONOUS)},
{returnType(RunnableFuture.class), shouldHaveExecutionType(ASYNCHRONOUS)},
{returnType(Observable.class), shouldHaveExecutionType(OBSERVABLE)},
{returnType(OperatorMulticast.class), shouldHaveExecutionType(OBSERVABLE)},
});
}
@Test
public void should_return_correct_execution_type() throws Exception {
assertEquals("Unexpected execution type for method return type: " + methodReturnType, expectedType, ExecutionType.getExecutionType(methodReturnType));
}
private static ExecutionType shouldHaveExecutionType(final ExecutionType type) {
return type;
}
private static Class<?> returnType(final Class<?> aClass) {
return aClass;
}
private final Class<?> methodReturnType;
private final ExecutionType expectedType;
public ExecutionTypeTest(final Class<?> methodReturnType, final ExecutionType expectedType) {
this.methodReturnType = methodReturnType;
this.expectedType = expectedType;
}
}
| 4,448 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/configuration/collapser/CollapserPropertiesTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.configuration.collapser;
import com.netflix.hystrix.contrib.javanica.test.common.configuration.collapser.BasicCollapserPropertiesTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class CollapserPropertiesTest extends BasicCollapserPropertiesTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
}
| 4,449 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/configuration | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/configuration/command/CommandPropertiesTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.configuration.command;
import com.netflix.hystrix.contrib.javanica.test.common.configuration.command.BasicCommandPropertiesTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class CommandPropertiesTest extends BasicCommandPropertiesTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
}
| 4,450 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/cache/CacheTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.cache;
import com.netflix.hystrix.contrib.javanica.test.common.cache.BasicCacheTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class CacheTest extends BasicCacheTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
UserService userService = new UserService();
userService.init();
return userService;
}
}
| 4,451 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/fallback/CommandFallbackTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.fallback;
import com.netflix.hystrix.contrib.javanica.test.common.fallback.BasicCommandFallbackTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class CommandFallbackTest extends BasicCommandFallbackTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
}
| 4,452 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/collapser/CollapserTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.collapser;
import com.netflix.hystrix.contrib.javanica.test.common.collapser.BasicCollapserTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class CollapserTest extends BasicCollapserTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
}
| 4,453 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/observable/ObservableTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.observable;
import com.netflix.hystrix.contrib.javanica.test.common.observable.BasicObservableTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class ObservableTest extends BasicObservableTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
}
| 4,454 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/command/CommandTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.command;
import com.netflix.hystrix.contrib.javanica.test.common.command.BasicCommandTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import org.junit.BeforeClass;
public class CommandTest extends BasicCommandTest {
@BeforeClass
public static void setUpEnv(){
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
@Override
protected AdvancedUserService createAdvancedUserServiceService() {
return new AdvancedUserService();
}
@Override
protected GenericService<String, Long, User> createGenericUserService() {
return new GenericUserService();
}
}
| 4,455 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/error/ObservableErrorPropagationTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.error;
import com.netflix.hystrix.contrib.javanica.test.common.error.BasicErrorPropagationTest;
import com.netflix.hystrix.contrib.javanica.test.common.error.BasicObservableErrorPropagationTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class ObservableErrorPropagationTest extends BasicObservableErrorPropagationTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
}
| 4,456 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/ajcTest/java/com/netflix/hystrix/contrib/javanica/test/aspectj/error/ErrorPropagationTest.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.test.aspectj.error;
import com.netflix.hystrix.contrib.javanica.test.common.error.BasicErrorPropagationTest;
import org.junit.BeforeClass;
/**
* Created by dmgcodevil
*/
public class ErrorPropagationTest extends BasicErrorPropagationTest {
@BeforeClass
public static void setUpEnv() {
System.setProperty("weavingMode", "compile");
}
@Override
protected UserService createUserService() {
return new UserService();
}
}
| 4,457 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/HystrixRequestCacheManager.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
/**
* Cache manager to work with {@link HystrixRequestCache}.
*
* @author dmgcodevil
*/
public final class HystrixRequestCacheManager {
private static final HystrixRequestCacheManager INSTANCE = new HystrixRequestCacheManager();
private HystrixRequestCacheManager() {
}
public static HystrixRequestCacheManager getInstance() {
return INSTANCE;
}
/**
* Clears the cache for a given cacheKey context.
*
* @param context the runtime information about an intercepted method invocation for a method
* annotated with {@link CacheRemove} annotation
*/
public void clearCache(CacheInvocationContext<CacheRemove> context) {
HystrixCacheKeyGenerator defaultCacheKeyGenerator = HystrixCacheKeyGenerator.getInstance();
String cacheName = context.getCacheAnnotation().commandKey();
HystrixGeneratedCacheKey hystrixGeneratedCacheKey =
defaultCacheKeyGenerator.generateCacheKey(context);
String key = hystrixGeneratedCacheKey.getCacheKey();
HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey(cacheName),
HystrixConcurrencyStrategyDefault.getInstance()).clear(key);
}
}
| 4,458 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/CacheInvocationContext.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.netflix.hystrix.contrib.javanica.command.ExecutionType;
import com.netflix.hystrix.contrib.javanica.command.MethodExecutionAction;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
/**
* Runtime information about an intercepted method invocation for a method
* annotated with {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult},
* {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove} annotations.
*
* @author dmgcodevil
*/
public class CacheInvocationContext<A extends Annotation> {
private final Method method;
private final Object target;
private final MethodExecutionAction cacheKeyMethod;
private final ExecutionType executionType = ExecutionType.SYNCHRONOUS;
private final A cacheAnnotation;
private List<CacheInvocationParameter> parameters = Collections.emptyList();
private List<CacheInvocationParameter> keyParameters = Collections.emptyList();
/**
* Constructor to create CacheInvocationContext based on passed parameters.
*
* @param cacheAnnotation the caching annotation, like {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult}
* @param cacheKeyMethod the method to generate cache key
* @param target the current instance of intercepted method
* @param method the method annotated with on of caching annotations
* @param args the method arguments
*/
public CacheInvocationContext(A cacheAnnotation, MethodExecutionAction cacheKeyMethod, Object target, Method method, Object... args) {
this.method = method;
this.target = target;
this.cacheKeyMethod = cacheKeyMethod;
this.cacheAnnotation = cacheAnnotation;
Class<?>[] parametersTypes = method.getParameterTypes();
int parameterCount = parametersTypes.length;
if (parameterCount > 0) {
Annotation[][] parametersAnnotations = method.getParameterAnnotations();
ImmutableList.Builder<CacheInvocationParameter> parametersBuilder = ImmutableList.builder();
for (int pos = 0; pos < parameterCount; pos++) {
Class<?> paramType = parametersTypes[pos];
Object val = args[pos];
parametersBuilder.add(new CacheInvocationParameter(paramType, val, parametersAnnotations[pos], pos));
}
parameters = parametersBuilder.build();
// get key parameters
Iterable<CacheInvocationParameter> filtered = Iterables.filter(parameters, new Predicate<CacheInvocationParameter>() {
@Override
public boolean apply(CacheInvocationParameter input) {
return input.hasCacheKeyAnnotation();
}
});
if (filtered.iterator().hasNext()) {
keyParameters = ImmutableList.<CacheInvocationParameter>builder().addAll(filtered).build();
} else {
keyParameters = parameters;
}
}
}
/**
* Gets intercepted method that annotated with caching annotation.
*
* @return method
*/
public Method getMethod() {
return method;
}
/**
* Gets current instance that can be used to invoke {@link #cacheKeyMethod} or for another needs.
*
* @return current instance
*/
public Object getTarget() {
return target;
}
public A getCacheAnnotation() {
return cacheAnnotation;
}
/**
* Gets all method parameters.
*
* @return immutable list of {@link CacheInvocationParameter} objects
*/
public List<CacheInvocationParameter> getAllParameters() {
return parameters;
}
/**
* Returns a clone of the array of all method parameters annotated with
* {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey} annotation to be used by the
* {@link HystrixCacheKeyGenerator} in creating a {@link HystrixGeneratedCacheKey}. The returned array
* may be the same as or a subset of the array returned by {@link #getAllParameters()}.
* <p/>
* Parameters in this array are selected by the following rules:
* <ul>
* <li>If no parameters are annotated with {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey}
* then all parameters are included</li>
* <li>If one or more {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey} annotations exist only those parameters
* with the {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey} annotation are included</li>
* </ul>
*
* @return immutable list of {@link CacheInvocationParameter} objects
*/
public List<CacheInvocationParameter> getKeyParameters() {
return keyParameters;
}
/**
* Checks whether any method argument annotated with {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey} annotation.
*
* @return true if at least one method argument with {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey} annotation
*/
public boolean hasKeyParameters() {
return !keyParameters.isEmpty();
}
/**
* Gets method name to be used to get a key for request caching.
*
* @return method name
*/
public String getCacheKeyMethodName() {
return cacheKeyMethod != null ? cacheKeyMethod.getMethod().getName() : null;
}
/**
* Gets action that invokes cache key method, the result of execution is used as cache key.
*
* @return cache key method execution action, see {@link MethodExecutionAction}.
*/
public MethodExecutionAction getCacheKeyMethod() {
return cacheKeyMethod;
}
/**
* Gets execution type of cache key action.
*
* @return execution type
*/
public ExecutionType getExecutionType() {
return executionType;
}
}
| 4,459 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/HystrixGeneratedCacheKey.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache;
/**
* Specific interface to adopt {@link HystrixGeneratedCacheKey} for Hystrix environment.
*
* @author dmgcodevil
*/
public interface HystrixGeneratedCacheKey {
/**
* Key to be used for request caching.
* <p/>
* By default this returns null which means "do not cache".
* <p/>
* To enable caching override this method and return a string key uniquely representing the state of a command instance.
* <p/>
* If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache.
*
* @return cacheKey
*/
String getCacheKey();
}
| 4,460 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/DefaultHystrixGeneratedCacheKey.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.cache;
import com.google.common.base.Objects;
/**
* Default implementation of {@link HystrixGeneratedCacheKey}.
*
* @author dmgcodevil
*/
public class DefaultHystrixGeneratedCacheKey implements HystrixGeneratedCacheKey {
/**
* Means "do not cache".
*/
public static final DefaultHystrixGeneratedCacheKey EMPTY = new DefaultHystrixGeneratedCacheKey(null);
private String cacheKey;
public DefaultHystrixGeneratedCacheKey(String cacheKey) {
this.cacheKey = cacheKey;
}
@Override
public String getCacheKey() {
return cacheKey;
}
@Override
public int hashCode() {
return Objects.hashCode(cacheKey);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
DefaultHystrixGeneratedCacheKey that = (DefaultHystrixGeneratedCacheKey) o;
return Objects.equal(this.cacheKey, that.cacheKey);
}
}
| 4,461 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/HystrixCacheKeyGenerator.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.command.MethodExecutionAction;
import com.netflix.hystrix.contrib.javanica.exception.HystrixCacheKeyGenerationException;
import org.apache.commons.lang3.StringUtils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
/**
* Generates a {@link HystrixGeneratedCacheKey} based on
* a {@link CacheInvocationContext}.
* <p/>
* Implementation is thread-safe.
*
* @author dmgcodevil
*/
public class HystrixCacheKeyGenerator {
private static final HystrixCacheKeyGenerator INSTANCE = new HystrixCacheKeyGenerator();
public static HystrixCacheKeyGenerator getInstance() {
return INSTANCE;
}
public HystrixGeneratedCacheKey generateCacheKey(CacheInvocationContext<? extends Annotation> cacheInvocationContext) throws HystrixCacheKeyGenerationException {
MethodExecutionAction cacheKeyMethod = cacheInvocationContext.getCacheKeyMethod();
if (cacheKeyMethod != null) {
try {
return new DefaultHystrixGeneratedCacheKey((String) cacheKeyMethod.execute(cacheInvocationContext.getExecutionType()));
} catch (Throwable throwable) {
throw new HystrixCacheKeyGenerationException(throwable);
}
} else {
if (cacheInvocationContext.hasKeyParameters()) {
StringBuilder cacheKeyBuilder = new StringBuilder();
for (CacheInvocationParameter parameter : cacheInvocationContext.getKeyParameters()) {
CacheKey cacheKey = parameter.getCacheKeyAnnotation();
if (cacheKey != null && StringUtils.isNotBlank(cacheKey.value())) {
appendPropertyValue(cacheKeyBuilder, Arrays.asList(StringUtils.split(cacheKey.value(), ".")), parameter.getValue());
} else {
cacheKeyBuilder.append(parameter.getValue());
}
}
return new DefaultHystrixGeneratedCacheKey(cacheKeyBuilder.toString());
} else {
return DefaultHystrixGeneratedCacheKey.EMPTY;
}
}
}
private Object appendPropertyValue(StringBuilder cacheKeyBuilder, List<String> names, Object obj) throws HystrixCacheKeyGenerationException {
for (String name : names) {
if (obj != null) {
obj = getPropertyValue(name, obj);
}
}
if (obj != null) {
cacheKeyBuilder.append(obj);
}
return obj;
}
private Object getPropertyValue(String name, Object obj) throws HystrixCacheKeyGenerationException {
try {
return new PropertyDescriptor(name, obj.getClass())
.getReadMethod().invoke(obj);
} catch (IllegalAccessException e) {
throw new HystrixCacheKeyGenerationException(e);
} catch (IntrospectionException e) {
throw new HystrixCacheKeyGenerationException(e);
} catch (InvocationTargetException e) {
throw new HystrixCacheKeyGenerationException(e);
}
}
}
| 4,462 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/CacheInvocationContextFactory.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import com.netflix.hystrix.contrib.javanica.command.MethodExecutionAction;
import com.netflix.hystrix.contrib.javanica.exception.HystrixCachingException;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Method;
import static com.netflix.hystrix.contrib.javanica.utils.AopUtils.getDeclaredMethod;
/**
* Factory to create certain {@link CacheInvocationContext}.
*
* @author dmgcodevil
*/
public class CacheInvocationContextFactory {
/**
* Create {@link CacheInvocationContext} parametrized with {@link CacheResult} annotation.
*
* @param metaHolder the meta holder, see {@link com.netflix.hystrix.contrib.javanica.command.MetaHolder}
* @return initialized and configured {@link CacheInvocationContext}
*/
public static CacheInvocationContext<CacheResult> createCacheResultInvocationContext(MetaHolder metaHolder) {
Method method = metaHolder.getMethod();
if (method.isAnnotationPresent(CacheResult.class)) {
CacheResult cacheResult = method.getAnnotation(CacheResult.class);
MethodExecutionAction cacheKeyMethod = createCacheKeyAction(cacheResult.cacheKeyMethod(), metaHolder);
return new CacheInvocationContext<CacheResult>(cacheResult, cacheKeyMethod, metaHolder.getObj(), method, metaHolder.getArgs());
}
return null;
}
/**
* Create {@link CacheInvocationContext} parametrized with {@link CacheRemove} annotation.
*
* @param metaHolder the meta holder, see {@link com.netflix.hystrix.contrib.javanica.command.MetaHolder}
* @return initialized and configured {@link CacheInvocationContext}
*/
public static CacheInvocationContext<CacheRemove> createCacheRemoveInvocationContext(MetaHolder metaHolder) {
Method method = metaHolder.getMethod();
if (method.isAnnotationPresent(CacheRemove.class)) {
CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
MethodExecutionAction cacheKeyMethod = createCacheKeyAction(cacheRemove.cacheKeyMethod(), metaHolder);
return new CacheInvocationContext<CacheRemove>(cacheRemove, cacheKeyMethod, metaHolder.getObj(), method, metaHolder.getArgs());
}
return null;
}
private static MethodExecutionAction createCacheKeyAction(String method, MetaHolder metaHolder) {
MethodExecutionAction cacheKeyAction = null;
if (StringUtils.isNotBlank(method)) {
Method cacheKeyMethod = getDeclaredMethod(metaHolder.getObj().getClass(), method,
metaHolder.getMethod().getParameterTypes());
if (cacheKeyMethod == null) {
throw new HystrixCachingException("method with name '" + method + "' doesn't exist in class '"
+ metaHolder.getObj().getClass() + "'");
}
if (!cacheKeyMethod.getReturnType().equals(String.class)) {
throw new HystrixCachingException("return type of cacheKey method must be String. Method: '" + method + "', Class: '"
+ metaHolder.getObj().getClass() + "'");
}
MetaHolder cMetaHolder = MetaHolder.builder().obj(metaHolder.getObj()).method(cacheKeyMethod).args(metaHolder.getArgs()).build();
cacheKeyAction = new MethodExecutionAction(cMetaHolder.getObj(), cacheKeyMethod, cMetaHolder.getArgs(), cMetaHolder);
}
return cacheKeyAction;
}
}
| 4,463 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/CacheInvocationParameter.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Set;
/**
* A parameter to an intercepted method invocation. Contains the parameter value
* as well static type and annotation information about the parameter.
*
* @author dmgcodevil
*/
public class CacheInvocationParameter {
private final Class<?> rawType;
private final Object value;
private final CacheKey cacheKeyAnnotation;
private final Set<Annotation> annotations;
private final int position;
public CacheInvocationParameter(Class<?> rawType, Object value, Annotation[] annotations, int position) {
this.rawType = rawType;
this.value = value;
this.annotations = ImmutableSet.<Annotation>builder().addAll(Arrays.asList(annotations)).build();
this.position = position;
this.cacheKeyAnnotation = (CacheKey) cacheKeyAnnotation();
}
/**
* Returns an immutable Set of all Annotations on this method parameter, never null.
*
* @return set of {@link Annotation}
*/
public Set<Annotation> getAnnotations() {
return annotations;
}
/**
* Gets {@link CacheKey} for the parameter.
*
* @return {@link CacheKey} annotation or null if the parameter isn't annotated with {@link CacheKey}.
*/
public CacheKey getCacheKeyAnnotation() {
return cacheKeyAnnotation;
}
/**
* Checks whether the parameter annotated with {@link CacheKey} or not.
*
* @return true if parameter annotated with {@link CacheKey} otherwise - false
*/
public boolean hasCacheKeyAnnotation() {
return cacheKeyAnnotation != null;
}
/**
* Gets the parameter type as declared on the method.
*
* @return parameter type
*/
public Class<?> getRawType() {
return rawType;
}
/**
* Gets the parameter value
*
* @return parameter value
*/
public Object getValue() {
return value;
}
/**
* Gets index of the parameter in the original parameter array.
*
* @return index of the parameter
*/
public int getPosition() {
return position;
}
private Annotation cacheKeyAnnotation() {
return Iterables.tryFind(annotations, new Predicate<Annotation>() {
@Override
public boolean apply(Annotation input) {
return input.annotationType().equals(CacheKey.class);
}
}).orNull();
}
}
| 4,464 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/annotation/CacheResult.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a methods that results should be cached for a Hystrix command.
* This annotation must be used in conjunction with {@link com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand} annotation.
*
* @author dmgcodevil
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CacheResult {
/**
* Method name to be used to get a key for request caching.
* The command and cache key method should be placed in the same class and have same method signature except
* cache key method return type, that should be <code>String</code>.
* <p/>
* cacheKeyMethod has higher priority than an arguments of a method, that means what actual arguments
* of a method that annotated with {@link CacheResult} will not be used to generate cache key, instead specified
* cacheKeyMethod fully assigns to itself responsibility for cache key generation.
* By default this returns empty string which means "do not use cache method".
*
* @return method name or empty string
*/
String cacheKeyMethod() default "";
}
| 4,465 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/annotation/CacheKey.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a method argument as part of the cache key.
* If no arguments are marked all arguments are used.
* If {@link CacheResult} or {@link CacheRemove} annotation has specified <code>cacheKeyMethod</code> then
* a method arguments will not be used to build cache key even if they annotated with {@link CacheKey}.
*
* @author dmgcodevil
*/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CacheKey {
/**
* Allows specify name of a certain argument property.
* for example: <code>@CacheKey("id") User user</code>,
* or in case composite property: <code>@CacheKey("profile.name") User user</code>.
* <code>null</code> properties are ignored, i.e. if <code>profile</code> is <code>null</code>
* then result of <code>@CacheKey("profile.name") User user</code> will be empty string.
*
* @return name of an argument property
*/
String value() default "";
}
| 4,466 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/cache/annotation/CacheRemove.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.cache.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks methods used to invalidate cache of a command.
* Generated cache key must be same as key generated within {@link CacheResult} context.
*
* @author dmgcodevil
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface CacheRemove {
/**
* Command name is used to find appropriate Hystrix command that cache should be cleared.
*
* @return command name
*/
String commandKey();
/**
* Method name to be used to get a key for request caching.
* The command and cache key method should be placed in the same class and have same method signature except
* cache key method return type, that should be <code>String</code>.
* <p/>
* cacheKeyMethod has higher priority than an arguments of a method, that means what actual arguments
* of a method that annotated with {@link CacheResult} will not be used to generate cache key, instead specified
* cacheKeyMethod fully assigns to itself responsibility for cache key generation.
* By default this returns empty string which means "do not use cache method".
*
* @return method name or empty string
*/
String cacheKeyMethod() default "";
}
| 4,467 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/annotation/HystrixCollapser.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.annotation;
import com.netflix.hystrix.HystrixCollapser.Scope;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to collapse some commands into a single backend dependency call.
* This annotation should be used together with {@link HystrixCommand} annotation.
* <p/>
* Example:
* <pre>
* @HystrixCollapser(batchMethod = "getUserByIds"){
* public Future<User> getUserById(String id) {
* return null;
* }
* @HystrixCommand
* public List<User> getUserByIds(List<String> ids) {
* List<User> users = new ArrayList<User>();
* for (String id : ids) {
* users.add(new User(id, "name: " + id));
* }
* return users;
* }
* </pre>
*
* A method annotated with {@link HystrixCollapser} annotation can return any
* value with compatible type, it does not affect the result of collapser execution,
* collapser method can even return {@code null} or another stub.
* Pay attention that if a collapser method returns parametrized Future then generic type must be equal to generic type of List,
* for instance:
* <pre>
* Future<User> - return type of collapser method
* List<User> - return type of batch command method
* </pre>
* <p/>
* Note: batch command method must be annotated with {@link HystrixCommand} annotation.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HystrixCollapser {
/**
* Specifies a collapser key.
* <p/>
* default => the name of annotated method.
*
* @return collapser key.
*/
String collapserKey() default "";
/**
* Method name of batch command.
* <p/>
* Method must have the following signature:
* <pre>
* java.util.List method(java.util.List)
* </pre>
* NOTE: batch method can have only one argument.
*
* @return method name of batch command
*/
String batchMethod();
/**
* Defines what scope the collapsing should occur within.
* <p/>
* default => the {@link Scope#REQUEST}.
*
* @return {@link Scope}
*/
Scope scope() default Scope.REQUEST;
/**
* Specifies collapser properties.
*
* @return collapser properties
*/
HystrixProperty[] collapserProperties() default {};
}
| 4,468 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/annotation/HystrixException.java | package com.netflix.hystrix.contrib.javanica.annotation;
/**
* Created by Mike Cowan
*/
public enum HystrixException {
RUNTIME_EXCEPTION,
}
| 4,469 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/annotation/ObservableExecutionMode.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.annotation;
import com.netflix.hystrix.HystrixObservable;
import rx.Observable;
/**
* Hystrix observable command can be executed in two different ways:
* eager - {@link HystrixObservable#observe()},
* lazy - {@link HystrixObservable#toObservable()}.
* <p/>
* This enum is used to specify desire execution mode.
* <p/>
* Created by dmgcodevil.
*/
public enum ObservableExecutionMode {
/**
* This mode lazily starts execution of the command only once the {@link Observable} is subscribed to.
*/
LAZY,
/**
* This mode eagerly starts execution of the command the same as {@link com.netflix.hystrix.HystrixCommand#queue()}
* and {@link com.netflix.hystrix.HystrixCommand#execute()}.
*/
EAGER
}
| 4,470 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/annotation/HystrixCommand.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation used to specify some methods which should be processes as hystrix commands.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HystrixCommand {
/**
* The command group key is used for grouping together commands such as for reporting,
* alerting, dashboards or team/library ownership.
* <p/>
* default => the runtime class name of annotated method
*
* @return group key
*/
String groupKey() default "";
/**
* Hystrix command key.
* <p/>
* default => the name of annotated method. for example:
* <code>
* ...
* @HystrixCommand
* public User getUserById(...)
* ...
* the command name will be: 'getUserById'
* </code>
*
* @return command key
*/
String commandKey() default "";
/**
* The thread-pool key is used to represent a
* HystrixThreadPool for monitoring, metrics publishing, caching and other such uses.
*
* @return thread pool key
*/
String threadPoolKey() default "";
/**
* Specifies a method to process fallback logic.
* A fallback method should be defined in the same class where is HystrixCommand.
* Also a fallback method should have same signature to a method which was invoked as hystrix command.
* for example:
* <code>
* @HystrixCommand(fallbackMethod = "getByIdFallback")
* public String getById(String id) {...}
*
* private String getByIdFallback(String id) {...}
* </code>
* Also a fallback method can be annotated with {@link HystrixCommand}
* <p/>
* default => see {@link com.netflix.hystrix.contrib.javanica.command.GenericCommand#getFallback()}
*
* @return method name
*/
String fallbackMethod() default "";
/**
* Specifies command properties.
*
* @return command properties
*/
HystrixProperty[] commandProperties() default {};
/**
* Specifies thread pool properties.
*
* @return thread pool properties
*/
HystrixProperty[] threadPoolProperties() default {};
/**
* Defines exceptions which should be ignored.
* Optionally these can be wrapped in HystrixRuntimeException if raiseHystrixExceptions contains RUNTIME_EXCEPTION.
*
* @return exceptions to ignore
*/
Class<? extends Throwable>[] ignoreExceptions() default {};
/**
* Specifies the mode that should be used to execute hystrix observable command.
* For more information see {@link ObservableExecutionMode}.
*
* @return observable execution mode
*/
ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;
/**
* When includes RUNTIME_EXCEPTION, any exceptions that are not ignored are wrapped in HystrixRuntimeException.
*
* @return exceptions to wrap
*/
HystrixException[] raiseHystrixExceptions() default {};
/**
* Specifies default fallback method for the command. If both {@link #fallbackMethod} and {@link #defaultFallback}
* methods are specified then specific one is used.
* note: default fallback method cannot have parameters, return type should be compatible with command return type.
*
* @return the name of default fallback method
*/
String defaultFallback() default "";
}
| 4,471 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/annotation/DefaultProperties.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to specify default parameters for
* hystrix commands (methods annotated with {@code @HystrixCommand} annotation).
*
* @author dmgcodevil
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface DefaultProperties {
/**
* Specifies default group key used for each hystrix command by default unless a command specifies group key explicitly.
* For additional info about this property see {@link HystrixCommand#groupKey()}.
*
* @return default group key
*/
String groupKey() default "";
/**
* Specifies default thread pool key used for each hystrix command by default unless a command specifies thread pool key explicitly.
* For additional info about this property see {@link HystrixCommand#threadPoolKey()}
*
* @return default thread pool
*/
String threadPoolKey() default "";
/**
* Specifies command properties that will be used for
* each hystrix command be default unless command properties explicitly specified in @HystrixCommand.
*
* @return command properties
*/
HystrixProperty[] commandProperties() default {};
/**
* Specifies thread pool properties that will be used for
* each hystrix command be default unless thread pool properties explicitly specified in @HystrixCommand.
*
* @return thread pool properties
*/
HystrixProperty[] threadPoolProperties() default {};
/**
* Defines exceptions which should be ignored.
* Optionally these can be wrapped in HystrixRuntimeException if raiseHystrixExceptions contains RUNTIME_EXCEPTION.
*
* @return exceptions to ignore
*/
Class<? extends Throwable>[] ignoreExceptions() default {};
/**
* When includes RUNTIME_EXCEPTION, any exceptions that are not ignored are wrapped in HystrixRuntimeException.
*
* @return exceptions to wrap
*/
HystrixException[] raiseHystrixExceptions() default {};
/**
* Specifies default fallback method for each command in the given class. Every command within the class should
* have a return type which is compatible with default fallback method return type.
* note: default fallback method cannot have parameters.
*
* @return the name of default fallback method
*/
String defaultFallback() default "";
}
| 4,472 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/annotation/HystrixProperty.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation allows specify Hystrix command properties in the following format:
* property name = property value.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HystrixProperty {
/**
* Property name.
*
* @return name
*/
String name();
/**
* Property value
*
* @return value
*/
String value();
}
| 4,473 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/CommonUtils.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.utils;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
/**
* Created by dmgcodevil.
*/
public final class CommonUtils {
private CommonUtils(){
}
public static Object[] createArgsForFallback(MetaHolder metaHolder, Throwable exception) {
return createArgsForFallback(metaHolder.getArgs(), metaHolder, exception);
}
public static Object[] createArgsForFallback(Object[] args, MetaHolder metaHolder, Throwable exception) {
if (metaHolder.isExtendedFallback()) {
if (metaHolder.isExtendedParentFallback()) {
args[args.length - 1] = exception;
} else {
args = Arrays.copyOf(args, args.length + 1);
args[args.length - 1] = exception;
}
} else {
if (metaHolder.isExtendedParentFallback()) {
args = ArrayUtils.remove(args, args.length - 1);
}
}
return args;
}
}
| 4,474 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/FutureDecorator.java | /**
* Copyright 2016 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.hystrix.contrib.javanica.utils;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureDecorator implements Future {
private Future origin;
public FutureDecorator(Future origin) {
this.origin = origin;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return origin.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return origin.isCancelled();
}
@Override
public boolean isDone() {
return origin.isDone();
}
@Override
public Object get() throws InterruptedException, ExecutionException {
Object result = origin.get();
if (result instanceof Future) {
return ((Future) result).get();
}
return result;
}
@Override
public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
Object result = origin.get(timeout, unit);
if (result instanceof Future) {
return ((Future) result).get();
}
return result;
}
}
| 4,475 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/FallbackMethod.java | /**
* Copyright 2016 Netflix, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.hystrix.contrib.javanica.utils;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.ExecutionType;
import com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import rx.Completable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static com.netflix.hystrix.contrib.javanica.utils.TypeHelper.flattenTypeVariables;
import static com.netflix.hystrix.contrib.javanica.utils.TypeHelper.isGenericReturnType;
import static com.netflix.hystrix.contrib.javanica.utils.TypeHelper.isParametrizedType;
import static com.netflix.hystrix.contrib.javanica.utils.TypeHelper.isReturnTypeParametrized;
import static com.netflix.hystrix.contrib.javanica.utils.TypeHelper.isTypeVariable;
import static com.netflix.hystrix.contrib.javanica.utils.TypeHelper.isWildcardType;
public class FallbackMethod {
private final Method method;
private final boolean extended;
private final boolean defaultFallback;
private ExecutionType executionType;
public static final FallbackMethod ABSENT = new FallbackMethod(null, false, false);
public FallbackMethod(Method method) {
this(method, false, false);
}
public FallbackMethod(Method method, boolean extended, boolean defaultFallback) {
this.method = method;
this.extended = extended;
this.defaultFallback = defaultFallback;
if (method != null) {
this.executionType = ExecutionType.getExecutionType(method.getReturnType());
}
}
public boolean isCommand() {
return method.isAnnotationPresent(HystrixCommand.class);
}
public boolean isPresent() {
return method != null;
}
public Method getMethod() {
return method;
}
public ExecutionType getExecutionType() {
return executionType;
}
public boolean isExtended() {
return extended;
}
public boolean isDefault() {
return defaultFallback;
}
public void validateReturnType(Method commandMethod) throws FallbackDefinitionException {
if (isPresent()) {
Class<?> commandReturnType = commandMethod.getReturnType();
if (ExecutionType.OBSERVABLE == ExecutionType.getExecutionType(commandReturnType)) {
if (ExecutionType.OBSERVABLE != getExecutionType()) {
Type commandParametrizedType = commandMethod.getGenericReturnType();
// basically any object can be wrapped into Completable, Completable itself ins't parametrized
if(Completable.class.isAssignableFrom(commandMethod.getReturnType())) {
validateCompletableReturnType(commandMethod, method.getReturnType());
return;
}
if (isReturnTypeParametrized(commandMethod)) {
commandParametrizedType = getFirstParametrizedType(commandMethod);
}
validateParametrizedType(commandParametrizedType, method.getGenericReturnType(), commandMethod, method);
} else {
validateReturnType(commandMethod, method);
}
} else if (ExecutionType.ASYNCHRONOUS == ExecutionType.getExecutionType(commandReturnType)) {
if (isCommand() && ExecutionType.ASYNCHRONOUS == getExecutionType()) {
validateReturnType(commandMethod, method);
}
if (ExecutionType.ASYNCHRONOUS != getExecutionType()) {
Type commandParametrizedType = commandMethod.getGenericReturnType();
if (isReturnTypeParametrized(commandMethod)) {
commandParametrizedType = getFirstParametrizedType(commandMethod);
}
validateParametrizedType(commandParametrizedType, method.getGenericReturnType(), commandMethod, method);
}
if (!isCommand() && ExecutionType.ASYNCHRONOUS == getExecutionType()) {
throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, "fallback cannot return Future if the fallback isn't command when the command is async."));
}
} else {
if (ExecutionType.ASYNCHRONOUS == getExecutionType()) {
throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, "fallback cannot return Future if command isn't asynchronous."));
}
if (ExecutionType.OBSERVABLE == getExecutionType()) {
throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, "fallback cannot return Observable if command isn't observable."));
}
validateReturnType(commandMethod, method);
}
}
}
private Type getFirstParametrizedType(Method m) {
Type gtype = m.getGenericReturnType();
if (gtype instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) gtype;
return pType.getActualTypeArguments()[0];
}
return null;
}
// everything can be wrapped into completable except 'void'
private void validateCompletableReturnType(Method commandMethod, Class<?> callbackReturnType) {
if (Void.TYPE == callbackReturnType) {
throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, "fallback cannot return 'void' if command return type is " + Completable.class.getSimpleName()));
}
}
private void validateReturnType(Method commandMethod, Method fallbackMethod) {
if (isGenericReturnType(commandMethod)) {
List<Type> commandParametrizedTypes = flattenTypeVariables(commandMethod.getGenericReturnType());
List<Type> fallbackParametrizedTypes = flattenTypeVariables(fallbackMethod.getGenericReturnType());
Result result = equalsParametrizedTypes(commandParametrizedTypes, fallbackParametrizedTypes);
if (!result.success) {
List<String> msg = new ArrayList<String>();
for (Error error : result.errors) {
Optional<Type> parentKindOpt = getParentKind(error.commandType, commandParametrizedTypes);
String extraHint = "";
if (parentKindOpt.isPresent()) {
Type parentKind = parentKindOpt.get();
if (isParametrizedType(parentKind)) {
extraHint = "--> " + ((ParameterizedType) parentKind).getRawType().toString() + "<Ooops!>\n";
}
}
msg.add(String.format(error.reason + "\n" + extraHint + "Command type literal pos: %s; Fallback type literal pos: %s",
positionAsString(error.commandType, commandParametrizedTypes),
positionAsString(error.fallbackType, fallbackParametrizedTypes)));
}
throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, StringUtils.join(msg, "\n")));
}
}
validatePlainReturnType(commandMethod, fallbackMethod);
}
private void validatePlainReturnType(Method commandMethod, Method fallbackMethod) {
validatePlainReturnType(commandMethod.getReturnType(), fallbackMethod.getReturnType(), commandMethod, fallbackMethod);
}
private void validatePlainReturnType(Class<?> commandReturnType, Class<?> fallbackReturnType, Method commandMethod, Method fallbackMethod) {
if (!commandReturnType.isAssignableFrom(fallbackReturnType)) {
throw new FallbackDefinitionException(createErrorMsg(commandMethod, fallbackMethod, "Fallback method '"
+ fallbackMethod + "' must return: " + commandReturnType + " or its subclass"));
}
}
private void validateParametrizedType(Type commandReturnType, Type fallbackReturnType, Method commandMethod, Method fallbackMethod) {
if (!commandReturnType.equals(fallbackReturnType)) {
throw new FallbackDefinitionException(createErrorMsg(commandMethod, fallbackMethod, "Fallback method '"
+ fallbackMethod + "' must return: " + commandReturnType + " or its subclass"));
}
}
private String createErrorMsg(Method commandMethod, Method fallbackMethod, String hint) {
return "Incompatible return types. \nCommand method: " + commandMethod + ";\nFallback method: " + fallbackMethod + ";\n"
+ (StringUtils.isNotBlank(hint) ? "Hint: " + hint : "");
}
private static final Result SUCCESS = Result.success();
private Result equalsParametrizedTypes(List<Type> commandParametrizedTypes, List<Type> fallbackParametrizedTypes) {
if (commandParametrizedTypes.size() != fallbackParametrizedTypes.size()) {
return Result.failure(Collections.singletonList(
new Error("Different size of types variables.\n" +
"Command type literals size = " + commandParametrizedTypes.size() + ": " + commandParametrizedTypes + "\n" +
"Fallback type literals size = " + fallbackParametrizedTypes.size() + ": " + fallbackParametrizedTypes + "\n"
)));
}
for (int i = 0; i < commandParametrizedTypes.size(); i++) {
Type commandParametrizedType = commandParametrizedTypes.get(i);
Type fallbackParametrizedType = fallbackParametrizedTypes.get(i);
Result result = equals(commandParametrizedType, fallbackParametrizedType);
if (!result.success) return result;
}
return SUCCESS;
}
// Regular Type#equals method cannot be used to compare parametrized types and type variables
// because it compares generic declarations, see java.lang.reflect.GenericDeclaration.
// If generic declaration is an instance of java.lang.reflect.Method then command and fallback return types have with different generic declarations which aren't the same.
// In this case we need to compare only few type properties, such as bounds for type literal and row types for parametrized types.
private static Result equals(Type commandType, Type fallbackType) {
if (isParametrizedType(commandType) && isParametrizedType(fallbackType)) {
final ParameterizedType pt1 = (ParameterizedType) commandType;
final ParameterizedType pt2 = (ParameterizedType) fallbackType;
Result result = regularEquals(pt1.getRawType(), pt2.getRawType());
return result.andThen(new Supplier<Result>() {
@Override
public Result get() {
return FallbackMethod.equals(pt1.getActualTypeArguments(), pt2.getActualTypeArguments());
}
});
} else if (isTypeVariable(commandType) && isTypeVariable(fallbackType)) {
final TypeVariable tv1 = (TypeVariable) commandType;
final TypeVariable tv2 = (TypeVariable) fallbackType;
if (tv1.getGenericDeclaration() instanceof Method && tv2.getGenericDeclaration() instanceof Method) {
Result result = equals(tv1.getBounds(), tv2.getBounds());
return result.append(new Supplier<List<Error>>() {
@Override
public List<Error> get() {
return Collections.singletonList(boundsError(tv1, tv1.getBounds(), "", tv2, tv2.getBounds()));
}
});
}
return regularEquals(tv1, tv2);
} else if (isWildcardType(commandType) && isWildcardType(fallbackType)) {
final WildcardType wt1 = (WildcardType) commandType;
final WildcardType wt2 = (WildcardType) fallbackType;
Result result = equals(wt1.getLowerBounds(), wt2.getLowerBounds());
result = result.append(new Supplier<List<Error>>() {
@Override
public List<Error> get() {
return Collections.singletonList(boundsError(wt1, wt1.getLowerBounds(), "lower", wt2, wt2.getLowerBounds()));
}
});
if (result.isFailure()) return result;
result = equals(wt1.getUpperBounds(), wt2.getUpperBounds());
return result.append(new Supplier<List<Error>>() {
@Override
public List<Error> get() {
return Collections.singletonList(boundsError(wt1, wt1.getUpperBounds(), "upper", wt2, wt2.getUpperBounds()));
}
});
} else {
return regularEquals(commandType, fallbackType);
}
}
private static Result regularEquals(final Type commandType, final Type fallbackType) {
return Result.of(Objects.equal(commandType, fallbackType), new Supplier<List<Error>>() {
@Override
public List<Error> get() {
return Collections.singletonList(new Error(
commandType,
String.format("Different types. Command type: '%s'; fallback type: '%s'", commandType, fallbackType),
fallbackType));
}
});
}
private static Optional<Type> getParentKind(Type type, List<Type> types) {
int pos = position(type, types);
if (pos <= 0) return Optional.absent();
return Optional.of(types.get(pos - 1));
}
private static String positionAsString(Type type, List<Type> types) {
int pos = position(type, types);
if (pos < 0) {
return "unknown";
}
return String.valueOf(pos);
}
private static int position(Type type, List<Type> types) {
if (type == null) return -1;
if (types == null || types.isEmpty()) return -1;
return types.indexOf(type);
}
private static Error boundsError(Type t1, Type[] b1, String boundType, Type t2, Type[] b2) {
return new Error(t1,
String.format("Different %s bounds. Command bounds: '%s'; Fallback bounds: '%s'",
boundType,
StringUtils.join(b1, ", "),
StringUtils.join(b2, ", ")),
t2);
}
private static Result equals(Type[] t1, Type[] t2) {
if (t1 == null && t2 == null) return SUCCESS;
if (t1 == null) return Result.failure();
if (t2 == null) return Result.failure();
if (t1.length != t2.length)
return Result.failure(new Error(String.format("Different size of type literals. Command size = %d, fallback size = %d",
t1.length, t2.length)));
Result result = SUCCESS;
for (int i = 0; i < t1.length; i++) {
result = result.combine(equals(t1[i], t2[i]));
if (result.isFailure()) return result;
}
return result;
}
private static class Result {
boolean success;
List<Error> errors = Collections.emptyList();
boolean isSuccess() {
return success;
}
boolean isFailure() {
return !success;
}
static Result of(boolean res, Supplier<List<Error>> errors) {
if (res) return success();
return failure(errors.get());
}
static Result success() {
return new Result(true);
}
static Result failure() {
return new Result(false);
}
static Result failure(Error... errors) {
return new Result(false, Arrays.asList(errors));
}
static Result failure(List<Error> errors) {
return new Result(false, errors);
}
Result combine(Result r) {
return new Result(this.success && r.success, merge(this.errors, r.errors));
}
Result andThen(Supplier<Result> resultSupplier) {
if (!success) return this;
return resultSupplier.get();
}
Result append(List<Error> errors) {
if (success) return this;
return failure(merge(this.errors, errors));
}
Result append(Supplier<List<Error>> errors) {
if (success) return this;
return append(errors.get());
}
static List<Error> merge(@Nonnull List<Error> e1, @Nonnull List<Error> e2) {
List<Error> res = new ArrayList<Error>(e1.size() + e2.size());
res.addAll(e1);
res.addAll(e2);
return Collections.unmodifiableList(res);
}
Result(boolean success, List<Error> errors) {
Validate.notNull(errors, "errors cannot be null");
this.success = success;
this.errors = errors;
}
Result(boolean success) {
this.success = success;
this.errors = Collections.emptyList();
}
}
private static class Error {
@Nullable
Type commandType;
String reason;
@Nullable
Type fallbackType;
Error(String reason) {
this.reason = reason;
}
Error(Type commandType, String reason, Type fallbackType) {
this.commandType = commandType;
this.reason = reason;
this.fallbackType = fallbackType;
}
}
}
| 4,476 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/AopUtils.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.utils;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.Validate;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
/**
* Provides common methods to retrieve information from JoinPoint and not only.
*/
public final class AopUtils {
private AopUtils() {
throw new UnsupportedOperationException("It's prohibited to create instances of the class.");
}
/**
* Gets a {@link Method} object from target object (not proxy class).
*
* @param joinPoint the {@link JoinPoint}
* @return a {@link Method} object or null if method doesn't exist or if the signature at a join point
* isn't sub-type of {@link MethodSignature}
*/
public static Method getMethodFromTarget(JoinPoint joinPoint) {
Method method = null;
if (joinPoint.getSignature() instanceof MethodSignature) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
method = getDeclaredMethod(joinPoint.getTarget().getClass(), signature.getName(),
getParameterTypes(joinPoint));
}
return method;
}
/**
* Gets a {@link Method} object from target object by specified method name.
*
* @param joinPoint the {@link JoinPoint}
* @param methodName the method name
* @return a {@link Method} object or null if method with specified <code>methodName</code> doesn't exist
*/
public static Method getMethodFromTarget(JoinPoint joinPoint, String methodName) {
return getDeclaredMethod(joinPoint.getTarget().getClass(), methodName,
getParameterTypes(joinPoint));
}
/**
* Gets parameter types of the join point.
*
* @param joinPoint the join point
* @return the parameter types for the method this object
* represents
*/
public static Class[] getParameterTypes(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
return method.getParameterTypes();
}
/**
* Gets declared method from specified type by mame and parameters types.
*
* @param type the type
* @param methodName the name of the method
* @param parameterTypes the parameter array
* @return a {@link Method} object or null if method doesn't exist
*/
public static Method getDeclaredMethod(Class<?> type, String methodName, Class<?>... parameterTypes) {
Method method = null;
try {
method = type.getDeclaredMethod(methodName, parameterTypes);
if(method.isBridge()){
method = MethodProvider.getInstance().unbride(method, type);
}
} catch (NoSuchMethodException e) {
Class<?> superclass = type.getSuperclass();
if (superclass != null) {
method = getDeclaredMethod(superclass, methodName, parameterTypes);
}
} catch (ClassNotFoundException e) {
Throwables.propagate(e);
} catch (IOException e) {
Throwables.propagate(e);
}
return method;
}
public static <T extends Annotation> Optional<T> getAnnotation(JoinPoint joinPoint, Class<T> annotation) {
return getAnnotation(joinPoint.getTarget().getClass(), annotation);
}
public static <T extends Annotation> Optional<T> getAnnotation(Class<?> type, Class<T> annotation) {
Validate.notNull(annotation, "annotation cannot be null");
Validate.notNull(type, "type cannot be null");
for (Annotation ann : type.getDeclaredAnnotations()) {
if (ann.annotationType().equals(annotation)) return Optional.of((T) ann);
}
Class<?> superType = type.getSuperclass();
if (superType != null && !superType.equals(Object.class)) {
return getAnnotation(superType, annotation);
}
return Optional.absent();
}
public static String getMethodInfo(Method m) {
StringBuilder info = new StringBuilder();
info.append("Method signature:").append("\n");
info.append(m.toGenericString()).append("\n");
info.append("Declaring class:\n");
info.append(m.getDeclaringClass().getCanonicalName()).append("\n");
info.append("\nFlags:").append("\n");
info.append("Bridge=").append(m.isBridge()).append("\n");
info.append("Synthetic=").append(m.isSynthetic()).append("\n");
info.append("Final=").append(Modifier.isFinal(m.getModifiers())).append("\n");
info.append("Native=").append(Modifier.isNative(m.getModifiers())).append("\n");
info.append("Synchronized=").append(Modifier.isSynchronized(m.getModifiers())).append("\n");
info.append("Abstract=").append(Modifier.isAbstract(m.getModifiers())).append("\n");
info.append("AccessLevel=").append(getAccessLevel(m.getModifiers())).append("\n");
info.append("\nReturn Type: \n");
info.append("ReturnType=").append(m.getReturnType()).append("\n");
info.append("GenericReturnType=").append(m.getGenericReturnType()).append("\n");
info.append("\nParameters:");
Class<?>[] pType = m.getParameterTypes();
Type[] gpType = m.getGenericParameterTypes();
if (pType.length != 0) {
info.append("\n");
} else {
info.append("empty\n");
}
for (int i = 0; i < pType.length; i++) {
info.append("parameter [").append(i).append("]:\n");
info.append("ParameterType=").append(pType[i]).append("\n");
info.append("GenericParameterType=").append(gpType[i]).append("\n");
}
info.append("\nExceptions:");
Class<?>[] xType = m.getExceptionTypes();
Type[] gxType = m.getGenericExceptionTypes();
if (xType.length != 0) {
info.append("\n");
} else {
info.append("empty\n");
}
for (int i = 0; i < xType.length; i++) {
info.append("exception [").append(i).append("]:\n");
info.append("ExceptionType=").append(xType[i]).append("\n");
info.append("GenericExceptionType=").append(gxType[i]).append("\n");
}
info.append("\nAnnotations:");
if (m.getAnnotations().length != 0) {
info.append("\n");
} else {
info.append("empty\n");
}
for (int i = 0; i < m.getAnnotations().length; i++) {
info.append("annotation[").append(i).append("]=").append(m.getAnnotations()[i]).append("\n");
}
return info.toString();
}
private static String getAccessLevel(int modifiers) {
if (Modifier.isPublic(modifiers)) {
return "public";
} else if (Modifier.isProtected(modifiers)) {
return "protected";
} else if (Modifier.isPrivate(modifiers)) {
return "private";
} else {
return "default";
}
}
}
| 4,477 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/EnvUtils.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.utils;
import com.netflix.hystrix.contrib.javanica.aop.aspectj.WeavingMode;
import java.util.Arrays;
/**
* Created by dmgcodevil
*/
public final class EnvUtils {
private static final String WEAVING_MODE;
static {
WEAVING_MODE = System.getProperty("weavingMode", WeavingMode.RUNTIME.name()).toUpperCase();
}
private EnvUtils(){
}
public static WeavingMode getWeavingMode() {
try {
return WeavingMode.valueOf(EnvUtils.WEAVING_MODE);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("wrong 'weavingMode' property, supported: " + Arrays.toString(WeavingMode.values()) + ", actual = " + EnvUtils.WEAVING_MODE, e);
}
}
public static boolean isCompileWeaving() {
return WeavingMode.COMPILE == getWeavingMode();
}
}
| 4,478 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/TypeHelper.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.utils;
import com.google.common.collect.TreeTraverser;
import org.apache.commons.lang3.Validate;
import javax.annotation.ParametersAreNonnullByDefault;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Helper class that provides convenient methods to work with java types.
* <p/>
* Created by dmgcodevil.
*/
public final class TypeHelper {
private TypeHelper() {
}
public static boolean isGenericReturnType(Method method) {
return isParametrizedType(method.getGenericReturnType()) || isTypeVariable(method.getGenericReturnType());
}
/**
* Check whether return type of the given method is parametrized or not.
*
* @param method the method
* @return true - if return type is {@link ParameterizedType}, otherwise - false
*/
public static boolean isReturnTypeParametrized(Method method) {
return isParametrizedType(method.getGenericReturnType());
}
public static boolean isParametrizedType(Type t) {
return t instanceof ParameterizedType;
}
public static boolean isTypeVariable(Type t) {
return t instanceof TypeVariable;
}
public static boolean isWildcardType(Type t) {
return t instanceof WildcardType;
}
/**
* Unwinds parametrized type into plain list that contains all parameters for the given type including nested parameterized types,
* for example calling the method for the following type
* <code>
* GType<GType<GDoubleType<GType<GDoubleType<Parent, Parent>>, Parent>>>
* </code>
* will return list of 8 elements:
* <code>
* [GType, GType, GDoubleType, GType, GDoubleType, Parent, Parent, Parent]
* </code>
* if the given type is not parametrized then returns list with one element which is given type passed into method.
*
* @param type the parameterized type
* @return list of {@link Type}
*/
@ParametersAreNonnullByDefault
public static List<Type> flattenTypeVariables(Type type) {
Validate.notNull(type, "type cannot be null");
List<Type> types = new ArrayList<Type>();
TreeTraverser<Type> typeTraverser = new TreeTraverser<Type>() {
@Override
public Iterable<Type> children(Type root) {
if (root instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) root;
return Arrays.asList(pType.getActualTypeArguments());
} else if (root instanceof TypeVariable) {
TypeVariable pType = (TypeVariable) root;
return Arrays.asList(pType.getBounds());
}
return Collections.emptyList();
}
};
for (Type t : typeTraverser.breadthFirstTraversal(type)) {
types.add(t);
}
return types;
}
}
| 4,479 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/MethodProvider.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.utils;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.objectweb.asm.Opcodes.ACC_BRIDGE;
import static org.objectweb.asm.Opcodes.ACC_SYNTHETIC;
import static org.objectweb.asm.Opcodes.ASM5;
/**
* Created by dmgcodevil
*/
public final class MethodProvider {
private MethodProvider() {
}
private static final MethodProvider INSTANCE = new MethodProvider();
public static MethodProvider getInstance() {
return INSTANCE;
}
private static final FallbackMethodFinder FALLBACK_METHOD_FINDER = new SpecificFallback(new DefaultCallback());
private Map<Method, Method> cache = new ConcurrentHashMap<Method, Method>();
public FallbackMethod getFallbackMethod(Class<?> type, Method commandMethod) {
return getFallbackMethod(type, commandMethod, false);
}
/**
* Gets fallback method for command method.
*
* @param enclosingType the enclosing class
* @param commandMethod the command method. in the essence it can be a fallback
* method annotated with HystrixCommand annotation that has a fallback as well.
* @param extended true if the given commandMethod was derived using additional parameter, otherwise - false
* @return new instance of {@link FallbackMethod} or {@link FallbackMethod#ABSENT} if there is no suitable fallback method for the given command
*/
public FallbackMethod getFallbackMethod(Class<?> enclosingType, Method commandMethod, boolean extended) {
if (commandMethod.isAnnotationPresent(HystrixCommand.class)) {
return FALLBACK_METHOD_FINDER.find(enclosingType, commandMethod, extended);
}
return FallbackMethod.ABSENT;
}
private void getDefaultFallback(){
}
private String getClassLevelFallback(Class<?> enclosingClass) {
if (enclosingClass.isAnnotationPresent(DefaultProperties.class)) {
return enclosingClass.getAnnotation(DefaultProperties.class).defaultFallback();
}
return StringUtils.EMPTY;
}
private static class SpecificFallback extends FallbackMethodFinder {
public SpecificFallback(FallbackMethodFinder next) {
super(next);
}
@Override
boolean isSpecific() {
return true;
}
@Override
public String getFallbackName(Class<?> enclosingType, Method commandMethod) {
return commandMethod.getAnnotation(HystrixCommand.class).fallbackMethod();
}
@Override
boolean canHandle(Class<?> enclosingType, Method commandMethod) {
return StringUtils.isNotBlank(getFallbackName(enclosingType, commandMethod));
}
}
private static class DefaultCallback extends FallbackMethodFinder {
@Override
boolean isDefault() {
return true;
}
@Override
public String getFallbackName(Class<?> enclosingType, Method commandMethod) {
String commandDefaultFallback = commandMethod.getAnnotation(HystrixCommand.class).defaultFallback();
String classDefaultFallback = Optional.fromNullable(enclosingType.getAnnotation(DefaultProperties.class))
.transform(new Function<DefaultProperties, String>() {
@Override
public String apply(DefaultProperties input) {
return input.defaultFallback();
}
}).or(StringUtils.EMPTY);
return StringUtils.defaultIfEmpty(commandDefaultFallback, classDefaultFallback);
}
@Override
boolean canHandle(Class<?> enclosingType, Method commandMethod) {
return StringUtils.isNotBlank(getFallbackName(enclosingType, commandMethod));
}
}
private static abstract class FallbackMethodFinder {
FallbackMethodFinder next;
public FallbackMethodFinder() {
}
public FallbackMethodFinder(FallbackMethodFinder next) {
this.next = next;
}
boolean isDefault() {
return false;
}
boolean isSpecific(){
return false;
}
public abstract String getFallbackName(Class<?> enclosingType, Method commandMethod);
public FallbackMethod find(Class<?> enclosingType, Method commandMethod, boolean extended) {
if (canHandle(enclosingType, commandMethod)) {
return doFind(enclosingType, commandMethod, extended);
} else if (next != null) {
return next.find(enclosingType, commandMethod, extended);
} else {
return FallbackMethod.ABSENT;
}
}
abstract boolean canHandle(Class<?> enclosingType, Method commandMethod);
private FallbackMethod doFind(Class<?> enclosingType, Method commandMethod, boolean extended) {
String name = getFallbackName(enclosingType, commandMethod);
Class<?>[] fallbackParameterTypes = null;
if (isDefault()) {
fallbackParameterTypes = new Class[0];
} else {
fallbackParameterTypes = commandMethod.getParameterTypes();
}
if (extended && fallbackParameterTypes[fallbackParameterTypes.length - 1] == Throwable.class) {
fallbackParameterTypes = ArrayUtils.remove(fallbackParameterTypes, fallbackParameterTypes.length - 1);
}
Class<?>[] extendedFallbackParameterTypes = Arrays.copyOf(fallbackParameterTypes,
fallbackParameterTypes.length + 1);
extendedFallbackParameterTypes[fallbackParameterTypes.length] = Throwable.class;
Optional<Method> exFallbackMethod = getMethod(enclosingType, name, extendedFallbackParameterTypes);
Optional<Method> fMethod = getMethod(enclosingType, name, fallbackParameterTypes);
Method method = exFallbackMethod.or(fMethod).orNull();
if (method == null) {
throw new FallbackDefinitionException("fallback method wasn't found: " + name + "(" + Arrays.toString(fallbackParameterTypes) + ")");
}
return new FallbackMethod(method, exFallbackMethod.isPresent(), isDefault());
}
}
/**
* Gets method by name and parameters types using reflection,
* if the given type doesn't contain required method then continue applying this method for all super classes up to Object class.
*
* @param type the type to search method
* @param name the method name
* @param parameterTypes the parameters types
* @return Some if method exists otherwise None
*/
public static Optional<Method> getMethod(Class<?> type, String name, Class<?>... parameterTypes) {
Method[] methods = type.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(name) && Arrays.equals(method.getParameterTypes(), parameterTypes)) {
return Optional.of(method);
}
}
Class<?> superClass = type.getSuperclass();
if (superClass != null && !superClass.equals(Object.class)) {
return getMethod(superClass, name, parameterTypes);
} else {
return Optional.absent();
}
}
/**
* Finds generic method for the given bridge method.
*
* @param bridgeMethod the bridge method
* @param aClass the type where the bridge method is declared
* @return generic method
* @throws IOException
* @throws NoSuchMethodException
* @throws ClassNotFoundException
*/
public Method unbride(final Method bridgeMethod, Class<?> aClass) throws IOException, NoSuchMethodException, ClassNotFoundException {
if (bridgeMethod.isBridge() && bridgeMethod.isSynthetic()) {
if (cache.containsKey(bridgeMethod)) {
return cache.get(bridgeMethod);
}
ClassReader classReader = new ClassReader(aClass.getName());
final MethodSignature methodSignature = new MethodSignature();
classReader.accept(new ClassVisitor(ASM5) {
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
boolean bridge = (access & ACC_BRIDGE) != 0 && (access & ACC_SYNTHETIC) != 0;
if (bridge && bridgeMethod.getName().equals(name) && getParameterCount(desc) == bridgeMethod.getParameterTypes().length) {
return new MethodFinder(methodSignature);
}
return super.visitMethod(access, name, desc, signature, exceptions);
}
}, 0);
Method method = aClass.getDeclaredMethod(methodSignature.name, methodSignature.getParameterTypes());
cache.put(bridgeMethod, method);
return method;
} else {
return bridgeMethod;
}
}
private static int getParameterCount(String desc) {
return parseParams(desc).length;
}
private static String[] parseParams(String desc) {
String params = desc.split("\\)")[0].replace("(", "");
if (params.length() == 0) {
return new String[0];
}
return params.split(";");
}
private static class MethodSignature {
String name;
String desc;
public Class<?>[] getParameterTypes() throws ClassNotFoundException {
if (desc == null) {
return new Class[0];
}
String[] params = parseParams(desc);
Class<?>[] parameterTypes = new Class[params.length];
for (int i = 0; i < params.length; i++) {
String arg = params[i].substring(1).replace("/", ".");
parameterTypes[i] = Class.forName(arg);
}
return parameterTypes;
}
}
private static class MethodFinder extends MethodVisitor {
private MethodSignature methodSignature;
public MethodFinder(MethodSignature methodSignature) {
super(ASM5);
this.methodSignature = methodSignature;
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
methodSignature.name = name;
methodSignature.desc = desc;
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
}
}
| 4,480 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/ajc/AjcUtils.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.utils.ajc;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Created by dmgcodevil
*/
public final class AjcUtils {
private AjcUtils() {
throw new UnsupportedOperationException("it's prohibited to create instances of this class");
}
public static Method getAjcMethod(final Class<?> target, final String methodName, final AdviceType adviceType, final Class<?>... pTypes) {
for (Method method : target.getDeclaredMethods()) {
if (method.getName().startsWith(methodName + adviceType.getPostfix())
&& Modifier.isFinal(method.getModifiers()) && Modifier.isStatic(method.getModifiers())) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (pTypes.length == 0 && parameterTypes.length == 0) {
return method;
}
if (pTypes.length == parameterTypes.length - 2) {
boolean match = true;
Class<?>[] origParamTypes = removeAspectjArgs(parameterTypes);
int index = 0;
for (Class<?> pType : origParamTypes) {
Class<?> expected = pTypes[index++];
if (pType != expected) {
match = false;
}
}
if (match) {
return method;
}
}
}
}
if (target.getSuperclass() != null) {
return getAjcMethod(target.getSuperclass(), methodName, adviceType, pTypes);
}
return null;
}
public static Method getAjcMethodAroundAdvice(final Class<?> target, final String methodName, final Class<?>... pTypes) {
return getAjcMethod(target, methodName, AdviceType.Around, pTypes);
}
public static Method getAjcMethodAroundAdvice(Class<?> target, MethodSignature signature) {
return getAjcMethodAroundAdvice(target, signature.getMethod().getName(), signature.getParameterTypes());
}
public static Method getAjcMethodAroundAdvice(Class<?> target, Method method) {
return getAjcMethodAroundAdvice(target, method.getName(), method.getParameterTypes());
}
public static Object invokeAjcMethod(Method method, Object target, MetaHolder metaHolder, Object... args) throws InvocationTargetException, IllegalAccessException {
method.setAccessible(true);
Object[] extArgs = new Object[args.length + 2];
extArgs[0] = target;
System.arraycopy(args, 0, extArgs, 1, args.length);
extArgs[extArgs.length - 1] = metaHolder.getJoinPoint();
return method.invoke(target, extArgs);
}
private static Class<?>[] removeAspectjArgs(Class<?>[] parameterTypes) {
Class<?>[] origParamTypes = new Class[parameterTypes.length - 2];
System.arraycopy(parameterTypes, 1, origParamTypes, 0, parameterTypes.length - 2);
return origParamTypes;
}
public enum AdviceType {
Around("_aroundBody");
private String postfix;
AdviceType(String postfix) {
this.postfix = postfix;
}
public String getPostfix() {
return postfix;
}
}
}
| 4,481 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop/aspectj/HystrixCommandAspect.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.aop.aspectj;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.netflix.hystrix.HystrixInvokable;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixException;
import com.netflix.hystrix.contrib.javanica.command.CommandExecutor;
import com.netflix.hystrix.contrib.javanica.command.ExecutionType;
import com.netflix.hystrix.contrib.javanica.command.HystrixCommandFactory;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException;
import com.netflix.hystrix.contrib.javanica.exception.FallbackInvocationException;
import com.netflix.hystrix.contrib.javanica.utils.AopUtils;
import com.netflix.hystrix.contrib.javanica.utils.FallbackMethod;
import com.netflix.hystrix.contrib.javanica.utils.MethodProvider;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import rx.Completable;
import rx.Observable;
import rx.Single;
import rx.functions.Func1;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import static com.netflix.hystrix.contrib.javanica.utils.AopUtils.getDeclaredMethod;
import static com.netflix.hystrix.contrib.javanica.utils.AopUtils.getMethodFromTarget;
import static com.netflix.hystrix.contrib.javanica.utils.AopUtils.getMethodInfo;
import static com.netflix.hystrix.contrib.javanica.utils.EnvUtils.isCompileWeaving;
import static com.netflix.hystrix.contrib.javanica.utils.ajc.AjcUtils.getAjcMethodAroundAdvice;
/**
* AspectJ aspect to process methods which annotated with {@link HystrixCommand} annotation.
*/
@Aspect
public class HystrixCommandAspect {
private static final Map<HystrixPointcutType, MetaHolderFactory> META_HOLDER_FACTORY_MAP;
static {
META_HOLDER_FACTORY_MAP = ImmutableMap.<HystrixPointcutType, MetaHolderFactory>builder()
.put(HystrixPointcutType.COMMAND, new CommandMetaHolderFactory())
.put(HystrixPointcutType.COLLAPSER, new CollapserMetaHolderFactory())
.build();
}
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void hystrixCommandAnnotationPointcut() {
}
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")
public void hystrixCollapserAnnotationPointcut() {
}
@Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
Method method = getMethodFromTarget(joinPoint);
Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
if (method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {
throw new IllegalStateException("method cannot be annotated with HystrixCommand and HystrixCollapser " +
"annotations at the same time");
}
MetaHolderFactory metaHolderFactory = META_HOLDER_FACTORY_MAP.get(HystrixPointcutType.of(method));
MetaHolder metaHolder = metaHolderFactory.create(joinPoint);
HystrixInvokable invokable = HystrixCommandFactory.getInstance().create(metaHolder);
ExecutionType executionType = metaHolder.isCollapserAnnotationPresent() ?
metaHolder.getCollapserExecutionType() : metaHolder.getExecutionType();
Object result;
try {
if (!metaHolder.isObservable()) {
result = CommandExecutor.execute(invokable, executionType, metaHolder);
} else {
result = executeObservable(invokable, executionType, metaHolder);
}
} catch (HystrixBadRequestException e) {
throw e.getCause() != null ? e.getCause() : e;
} catch (HystrixRuntimeException e) {
throw hystrixRuntimeExceptionToThrowable(metaHolder, e);
}
return result;
}
private Object executeObservable(HystrixInvokable invokable, ExecutionType executionType, final MetaHolder metaHolder) {
return mapObservable(((Observable) CommandExecutor.execute(invokable, executionType, metaHolder))
.onErrorResumeNext(new Func1<Throwable, Observable>() {
@Override
public Observable call(Throwable throwable) {
if (throwable instanceof HystrixBadRequestException) {
return Observable.error(throwable.getCause());
} else if (throwable instanceof HystrixRuntimeException) {
HystrixRuntimeException hystrixRuntimeException = (HystrixRuntimeException) throwable;
return Observable.error(hystrixRuntimeExceptionToThrowable(metaHolder, hystrixRuntimeException));
}
return Observable.error(throwable);
}
}), metaHolder);
}
private Object mapObservable(Observable observable, final MetaHolder metaHolder) {
if (Completable.class.isAssignableFrom(metaHolder.getMethod().getReturnType())) {
return observable.toCompletable();
} else if (Single.class.isAssignableFrom(metaHolder.getMethod().getReturnType())) {
return observable.toSingle();
}
return observable;
}
private Throwable hystrixRuntimeExceptionToThrowable(MetaHolder metaHolder, HystrixRuntimeException e) {
if (metaHolder.raiseHystrixExceptionsContains(HystrixException.RUNTIME_EXCEPTION)) {
return e;
}
return getCause(e);
}
private Throwable getCause(HystrixRuntimeException e) {
if (e.getFailureType() != HystrixRuntimeException.FailureType.COMMAND_EXCEPTION) {
return e;
}
Throwable cause = e.getCause();
// latest exception in flow should be propagated to end user
if (e.getFallbackException() instanceof FallbackInvocationException) {
cause = e.getFallbackException().getCause();
if (cause instanceof HystrixRuntimeException) {
cause = getCause((HystrixRuntimeException) cause);
}
} else if (cause instanceof CommandActionExecutionException) { // this situation is possible only if a callee throws an exception which type extends Throwable directly
CommandActionExecutionException commandActionExecutionException = (CommandActionExecutionException) cause;
cause = commandActionExecutionException.getCause();
}
return Optional.fromNullable(cause).or(e);
}
/**
* A factory to create MetaHolder depending on {@link HystrixPointcutType}.
*/
private static abstract class MetaHolderFactory {
public MetaHolder create(final ProceedingJoinPoint joinPoint) {
Method method = getMethodFromTarget(joinPoint);
Object obj = joinPoint.getTarget();
Object[] args = joinPoint.getArgs();
Object proxy = joinPoint.getThis();
return create(proxy, method, obj, args, joinPoint);
}
public abstract MetaHolder create(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint);
MetaHolder.Builder metaHolderBuilder(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
MetaHolder.Builder builder = MetaHolder.builder()
.args(args).method(method).obj(obj).proxyObj(proxy)
.joinPoint(joinPoint);
setFallbackMethod(builder, obj.getClass(), method);
builder = setDefaultProperties(builder, obj.getClass(), joinPoint);
return builder;
}
}
private static class CollapserMetaHolderFactory extends MetaHolderFactory {
@Override
public MetaHolder create(Object proxy, Method collapserMethod, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
HystrixCollapser hystrixCollapser = collapserMethod.getAnnotation(HystrixCollapser.class);
if (collapserMethod.getParameterTypes().length > 1 || collapserMethod.getParameterTypes().length == 0) {
throw new IllegalStateException("Collapser method must have one argument: " + collapserMethod);
}
Method batchCommandMethod = getDeclaredMethod(obj.getClass(), hystrixCollapser.batchMethod(), List.class);
if (batchCommandMethod == null)
throw new IllegalStateException("batch method is absent: " + hystrixCollapser.batchMethod());
Class<?> batchReturnType = batchCommandMethod.getReturnType();
Class<?> collapserReturnType = collapserMethod.getReturnType();
boolean observable = collapserReturnType.equals(Observable.class);
if (!collapserMethod.getParameterTypes()[0]
.equals(getFirstGenericParameter(batchCommandMethod.getGenericParameterTypes()[0]))) {
throw new IllegalStateException("required batch method for collapser is absent, wrong generic type: expected "
+ obj.getClass().getCanonicalName() + "." +
hystrixCollapser.batchMethod() + "(java.util.List<" + collapserMethod.getParameterTypes()[0] + ">), but it's " +
getFirstGenericParameter(batchCommandMethod.getGenericParameterTypes()[0]));
}
final Class<?> collapserMethodReturnType = getFirstGenericParameter(
collapserMethod.getGenericReturnType(),
Future.class.isAssignableFrom(collapserReturnType) || Observable.class.isAssignableFrom(collapserReturnType) ? 1 : 0);
Class<?> batchCommandActualReturnType = getFirstGenericParameter(batchCommandMethod.getGenericReturnType());
if (!collapserMethodReturnType
.equals(batchCommandActualReturnType)) {
throw new IllegalStateException("Return type of batch method must be java.util.List parametrized with corresponding type: expected " +
"(java.util.List<" + collapserMethodReturnType + ">)" + obj.getClass().getCanonicalName() + "." +
hystrixCollapser.batchMethod() + "(java.util.List<" + collapserMethod.getParameterTypes()[0] + ">), but it's " +
batchCommandActualReturnType);
}
HystrixCommand hystrixCommand = batchCommandMethod.getAnnotation(HystrixCommand.class);
if (hystrixCommand == null) {
throw new IllegalStateException("batch method must be annotated with HystrixCommand annotation");
}
// method of batch hystrix command must be passed to metaholder because basically collapser doesn't have any actions
// that should be invoked upon intercepted method, it's required only for underlying batch command
MetaHolder.Builder builder = metaHolderBuilder(proxy, batchCommandMethod, obj, args, joinPoint);
if (isCompileWeaving()) {
builder.ajcMethod(getAjcMethodAroundAdvice(obj.getClass(), batchCommandMethod.getName(), List.class));
}
builder.hystrixCollapser(hystrixCollapser);
builder.defaultCollapserKey(collapserMethod.getName());
builder.collapserExecutionType(ExecutionType.getExecutionType(collapserReturnType));
builder.defaultCommandKey(batchCommandMethod.getName());
builder.hystrixCommand(hystrixCommand);
builder.executionType(ExecutionType.getExecutionType(batchReturnType));
builder.observable(observable);
FallbackMethod fallbackMethod = MethodProvider.getInstance().getFallbackMethod(obj.getClass(), batchCommandMethod);
if (fallbackMethod.isPresent()) {
fallbackMethod.validateReturnType(batchCommandMethod);
builder
.fallbackMethod(fallbackMethod.getMethod())
.fallbackExecutionType(ExecutionType.getExecutionType(fallbackMethod.getMethod().getReturnType()));
}
return builder.build();
}
}
private static class CommandMetaHolderFactory extends MetaHolderFactory {
@Override
public MetaHolder create(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
HystrixCommand hystrixCommand = method.getAnnotation(HystrixCommand.class);
ExecutionType executionType = ExecutionType.getExecutionType(method.getReturnType());
MetaHolder.Builder builder = metaHolderBuilder(proxy, method, obj, args, joinPoint);
if (isCompileWeaving()) {
builder.ajcMethod(getAjcMethodFromTarget(joinPoint));
}
return builder.defaultCommandKey(method.getName())
.hystrixCommand(hystrixCommand)
.observableExecutionMode(hystrixCommand.observableExecutionMode())
.executionType(executionType)
.observable(ExecutionType.OBSERVABLE == executionType)
.build();
}
}
private enum HystrixPointcutType {
COMMAND,
COLLAPSER;
static HystrixPointcutType of(Method method) {
if (method.isAnnotationPresent(HystrixCommand.class)) {
return COMMAND;
} else if (method.isAnnotationPresent(HystrixCollapser.class)) {
return COLLAPSER;
} else {
String methodInfo = getMethodInfo(method);
throw new IllegalStateException("'https://github.com/Netflix/Hystrix/issues/1458' - no valid annotation found for: \n" + methodInfo);
}
}
}
private static Method getAjcMethodFromTarget(JoinPoint joinPoint) {
return getAjcMethodAroundAdvice(joinPoint.getTarget().getClass(), (MethodSignature) joinPoint.getSignature());
}
private static Class<?> getFirstGenericParameter(Type type) {
return getFirstGenericParameter(type, 1);
}
private static Class<?> getFirstGenericParameter(final Type type, final int nestedDepth) {
int cDepth = 0;
Type tType = type;
for (int cDept = 0; cDept < nestedDepth; cDept++) {
if (!(tType instanceof ParameterizedType))
throw new IllegalStateException(String.format("Sub type at nesting level %d of %s is expected to be generic", cDepth, type));
tType = ((ParameterizedType) tType).getActualTypeArguments()[cDept];
}
if (tType instanceof ParameterizedType)
return (Class<?>) ((ParameterizedType) tType).getRawType();
else if (tType instanceof Class)
return (Class<?>) tType;
throw new UnsupportedOperationException("Unsupported type " + tType);
}
private static MetaHolder.Builder setDefaultProperties(MetaHolder.Builder builder, Class<?> declaringClass, final ProceedingJoinPoint joinPoint) {
Optional<DefaultProperties> defaultPropertiesOpt = AopUtils.getAnnotation(joinPoint, DefaultProperties.class);
builder.defaultGroupKey(declaringClass.getSimpleName());
if (defaultPropertiesOpt.isPresent()) {
DefaultProperties defaultProperties = defaultPropertiesOpt.get();
builder.defaultProperties(defaultProperties);
if (StringUtils.isNotBlank(defaultProperties.groupKey())) {
builder.defaultGroupKey(defaultProperties.groupKey());
}
if (StringUtils.isNotBlank(defaultProperties.threadPoolKey())) {
builder.defaultThreadPoolKey(defaultProperties.threadPoolKey());
}
}
return builder;
}
private static MetaHolder.Builder setFallbackMethod(MetaHolder.Builder builder, Class<?> declaringClass, Method commandMethod) {
FallbackMethod fallbackMethod = MethodProvider.getInstance().getFallbackMethod(declaringClass, commandMethod);
if (fallbackMethod.isPresent()) {
fallbackMethod.validateReturnType(commandMethod);
builder
.fallbackMethod(fallbackMethod.getMethod())
.fallbackExecutionType(ExecutionType.getExecutionType(fallbackMethod.getMethod().getReturnType()));
}
return builder;
}
}
| 4,482 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop/aspectj/WeavingMode.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.aop.aspectj;
/**
* Created by dmgcodevil
*/
public enum WeavingMode {
COMPILE, RUNTIME
}
| 4,483 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop/aspectj/HystrixCacheAspect.java | /**
* Copyright 2015 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.hystrix.contrib.javanica.aop.aspectj;
import com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContext;
import com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContextFactory;
import com.netflix.hystrix.contrib.javanica.cache.HystrixRequestCacheManager;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.command.ExecutionType;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import org.apache.commons.lang3.Validate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import java.lang.reflect.Method;
import static com.netflix.hystrix.contrib.javanica.utils.AopUtils.getMethodFromTarget;
import static com.netflix.hystrix.contrib.javanica.utils.EnvUtils.isCompileWeaving;
import static com.netflix.hystrix.contrib.javanica.utils.ajc.AjcUtils.getAjcMethodAroundAdvice;
/**
* AspectJ aspect to process methods which annotated with annotations from
* <code>com.netflix.hystrix.contrib.javanica.cache.annotation</code> package.
*
* @author dmgcodevil
*/
@Aspect
public class HystrixCacheAspect {
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove) && !@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void cacheRemoveAnnotationPointcut() {
}
@Around("cacheRemoveAnnotationPointcut()")
public Object methodsAnnotatedWithCacheRemove(final ProceedingJoinPoint joinPoint) throws Throwable {
Method method = getMethodFromTarget(joinPoint);
Object obj = joinPoint.getTarget();
Object[] args = joinPoint.getArgs();
Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
MetaHolder metaHolder = MetaHolder.builder()
.args(args).method(method).obj(obj)
.executionType(ExecutionType.SYNCHRONOUS)
.ajcMethod(isCompileWeaving() ? getAjcMethodAroundAdvice(obj.getClass(), method) : null)
.build();
CacheInvocationContext<CacheRemove> context = CacheInvocationContextFactory
.createCacheRemoveInvocationContext(metaHolder);
HystrixRequestCacheManager.getInstance().clearCache(context);
return joinPoint.proceed();
}
}
| 4,484 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/collapser/CommandCollapser.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.collapser;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.BatchHystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.HystrixCommandBuilderFactory;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import java.util.Collection;
import java.util.List;
import static org.slf4j.helpers.MessageFormatter.arrayFormat;
/**
* Collapses multiple requests into a single {@link HystrixCommand} execution based
* on a time window and optionally a max batch size.
*/
public class CommandCollapser extends HystrixCollapser<List<Object>, Object, Object> {
private MetaHolder metaHolder;
private static final String ERROR_MSG = "Failed to map all collapsed requests to response. " +
"The expected contract has not been respected. ";
private static final String ERROR_MSF_TEMPLATE = "Collapser key: '{}', requests size: '{}', response size: '{}'";
/**
* Constructor with parameters.
*
* @param metaHolder the {@link MetaHolder}
*/
public CommandCollapser(MetaHolder metaHolder) {
super(HystrixCommandBuilderFactory.getInstance().create(metaHolder).getSetterBuilder().buildCollapserCommandSetter());
this.metaHolder = metaHolder;
}
/**
* {@inheritDoc}
*/
@Override
public Object getRequestArgument() {
return metaHolder.getArgs();
}
/**
* Creates batch command.
*/
@Override
protected HystrixCommand<List<Object>> createCommand(
Collection<CollapsedRequest<Object, Object>> collapsedRequests) {
return new BatchHystrixCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder, collapsedRequests));
}
/**
* {@inheritDoc}
*/
@Override
protected void mapResponseToRequests(List<Object> batchResponse,
Collection<CollapsedRequest<Object, Object>> collapsedRequests) {
if (batchResponse.size() < collapsedRequests.size()) {
throw new RuntimeException(createMessage(collapsedRequests, batchResponse));
}
int count = 0;
for (CollapsedRequest<Object, Object> request : collapsedRequests) {
request.setResponse(batchResponse.get(count++));
}
}
private String createMessage(Collection<CollapsedRequest<Object, Object>> requests,
List<Object> response) {
return ERROR_MSG + arrayFormat(ERROR_MSF_TEMPLATE, new Object[]{getCollapserKey().name(),
requests.size(), response.size()}).getMessage();
}
}
| 4,485 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/GenericCommand.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.contrib.javanica.exception.FallbackInvocationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.ThreadSafe;
import static com.netflix.hystrix.contrib.javanica.exception.ExceptionUtils.unwrapCause;
import static com.netflix.hystrix.contrib.javanica.utils.CommonUtils.createArgsForFallback;
/**
* Implementation of AbstractHystrixCommand which returns an Object as result.
*/
@ThreadSafe
public class GenericCommand extends AbstractHystrixCommand<Object> {
private static final Logger LOGGER = LoggerFactory.getLogger(GenericCommand.class);
public GenericCommand(HystrixCommandBuilder builder) {
super(builder);
}
/**
* {@inheritDoc}
*/
@Override
protected Object run() throws Exception {
LOGGER.debug("execute command: {}", getCommandKey().name());
return process(new Action() {
@Override
Object execute() {
return getCommandAction().execute(getExecutionType());
}
});
}
/**
* The fallback is performed whenever a command execution fails.
* Also a fallback method will be invoked within separate command in the case if fallback method was annotated with
* HystrixCommand annotation, otherwise current implementation throws RuntimeException and leaves the caller to deal with it
* (see {@link super#getFallback()}).
* The getFallback() is always processed synchronously.
* Since getFallback() can throw only runtime exceptions thus any exceptions are thrown within getFallback() method
* are wrapped in {@link FallbackInvocationException}.
* A caller gets {@link com.netflix.hystrix.exception.HystrixRuntimeException}
* and should call getCause to get original exception that was thrown in getFallback().
*
* @return result of invocation of fallback method or RuntimeException
*/
@Override
protected Object getFallback() {
final CommandAction commandAction = getFallbackAction();
if (commandAction != null) {
try {
return process(new Action() {
@Override
Object execute() {
MetaHolder metaHolder = commandAction.getMetaHolder();
Object[] args = createArgsForFallback(metaHolder, getExecutionException());
return commandAction.executeWithArgs(metaHolder.getFallbackExecutionType(), args);
}
});
} catch (Throwable e) {
LOGGER.error(FallbackErrorMessageBuilder.create()
.append(commandAction, e).build());
throw new FallbackInvocationException(unwrapCause(e));
}
} else {
return super.getFallback();
}
}
}
| 4,486 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/BatchHystrixCommand.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.exception.FallbackInvocationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.ThreadSafe;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static com.netflix.hystrix.contrib.javanica.exception.ExceptionUtils.unwrapCause;
import static com.netflix.hystrix.contrib.javanica.utils.CommonUtils.createArgsForFallback;
/**
* This command is used in collapser.
*/
@ThreadSafe
public class BatchHystrixCommand extends AbstractHystrixCommand<List<Object>> {
private static final Logger LOGGER = LoggerFactory.getLogger(BatchHystrixCommand.class);
public BatchHystrixCommand(HystrixCommandBuilder builder) {
super(builder);
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
protected List<Object> run() throws Exception {
Object[] args = toArgs(getCollapsedRequests());
return (List) process(args);
}
private Object process(final Object[] args) throws Exception {
return process(new Action() {
@Override
Object execute() {
return getCommandAction().executeWithArgs(getExecutionType(), args);
}
});
}
@Override
@SuppressWarnings("unchecked")
protected List<Object> getFallback() {
if (getFallbackAction() != null) {
final CommandAction commandAction = getFallbackAction();
try {
return (List<Object>) process(new Action() {
@Override
Object execute() {
MetaHolder metaHolder = commandAction.getMetaHolder();
Object[] args = toArgs(getCollapsedRequests());
args = createArgsForFallback(args, metaHolder, getExecutionException());
return commandAction.executeWithArgs(commandAction.getMetaHolder().getFallbackExecutionType(), args);
}
});
} catch (Throwable e) {
LOGGER.error(FallbackErrorMessageBuilder.create()
.append(commandAction, e).build());
throw new FallbackInvocationException(unwrapCause(e));
}
} else {
return super.getFallback();
}
}
private Object[] toArgs(Collection<HystrixCollapser.CollapsedRequest<Object, Object>> requests) {
return new Object[]{collect(requests)};
}
private List<Object> collect(Collection<HystrixCollapser.CollapsedRequest<Object, Object>> requests) {
List<Object> commandArgs = new ArrayList<Object>();
for (HystrixCollapser.CollapsedRequest<Object, Object> request : requests) {
final Object[] args = (Object[]) request.getArgument();
commandArgs.add(args[0]);
}
return commandArgs;
}
}
| 4,487 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/HystrixCommandBuilderFactory.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.utils.FallbackMethod;
import com.netflix.hystrix.contrib.javanica.utils.MethodProvider;
import org.apache.commons.lang3.Validate;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import static com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContextFactory.createCacheRemoveInvocationContext;
import static com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContextFactory.createCacheResultInvocationContext;
import static com.netflix.hystrix.contrib.javanica.utils.EnvUtils.isCompileWeaving;
import static com.netflix.hystrix.contrib.javanica.utils.ajc.AjcUtils.getAjcMethodAroundAdvice;
/**
* Created by dmgcodevil.
*/
public class HystrixCommandBuilderFactory {
// todo Add Cache
private static final HystrixCommandBuilderFactory INSTANCE = new HystrixCommandBuilderFactory();
public static HystrixCommandBuilderFactory getInstance() {
return INSTANCE;
}
private HystrixCommandBuilderFactory() {
}
public HystrixCommandBuilder create(MetaHolder metaHolder) {
return create(metaHolder, Collections.<HystrixCollapser.CollapsedRequest<Object, Object>>emptyList());
}
public <ResponseType> HystrixCommandBuilder create(MetaHolder metaHolder, Collection<HystrixCollapser.CollapsedRequest<ResponseType, Object>> collapsedRequests) {
validateMetaHolder(metaHolder);
return HystrixCommandBuilder.builder()
.setterBuilder(createGenericSetterBuilder(metaHolder))
.commandActions(createCommandActions(metaHolder))
.collapsedRequests(collapsedRequests)
.cacheResultInvocationContext(createCacheResultInvocationContext(metaHolder))
.cacheRemoveInvocationContext(createCacheRemoveInvocationContext(metaHolder))
.ignoreExceptions(metaHolder.getCommandIgnoreExceptions())
.executionType(metaHolder.getExecutionType())
.build();
}
private void validateMetaHolder(MetaHolder metaHolder) {
Validate.notNull(metaHolder, "metaHolder is required parameter and cannot be null");
Validate.isTrue(metaHolder.isCommandAnnotationPresent(), "hystrixCommand annotation is absent");
}
private GenericSetterBuilder createGenericSetterBuilder(MetaHolder metaHolder) {
GenericSetterBuilder.Builder setterBuilder = GenericSetterBuilder.builder()
.groupKey(metaHolder.getCommandGroupKey())
.threadPoolKey(metaHolder.getThreadPoolKey())
.commandKey(metaHolder.getCommandKey())
.collapserKey(metaHolder.getCollapserKey())
.commandProperties(metaHolder.getCommandProperties())
.threadPoolProperties(metaHolder.getThreadPoolProperties())
.collapserProperties(metaHolder.getCollapserProperties());
if (metaHolder.isCollapserAnnotationPresent()) {
setterBuilder.scope(metaHolder.getHystrixCollapser().scope());
}
return setterBuilder.build();
}
private CommandActions createCommandActions(MetaHolder metaHolder) {
CommandAction commandAction = createCommandAction(metaHolder);
CommandAction fallbackAction = createFallbackAction(metaHolder);
return CommandActions.builder().commandAction(commandAction)
.fallbackAction(fallbackAction).build();
}
private CommandAction createCommandAction(MetaHolder metaHolder) {
return new MethodExecutionAction(metaHolder.getObj(), metaHolder.getMethod(), metaHolder.getArgs(), metaHolder);
}
private CommandAction createFallbackAction(MetaHolder metaHolder) {
FallbackMethod fallbackMethod = MethodProvider.getInstance().getFallbackMethod(metaHolder.getObj().getClass(),
metaHolder.getMethod(), metaHolder.isExtendedFallback());
fallbackMethod.validateReturnType(metaHolder.getMethod());
CommandAction fallbackAction = null;
if (fallbackMethod.isPresent()) {
Method fMethod = fallbackMethod.getMethod();
Object[] args = fallbackMethod.isDefault() ? new Object[0] : metaHolder.getArgs();
if (fallbackMethod.isCommand()) {
fMethod.setAccessible(true);
HystrixCommand hystrixCommand = fMethod.getAnnotation(HystrixCommand.class);
MetaHolder fmMetaHolder = MetaHolder.builder()
.obj(metaHolder.getObj())
.method(fMethod)
.ajcMethod(getAjcMethod(metaHolder.getObj(), fMethod))
.args(args)
.fallback(true)
.defaultFallback(fallbackMethod.isDefault())
.defaultCollapserKey(metaHolder.getDefaultCollapserKey())
.fallbackMethod(fMethod)
.extendedFallback(fallbackMethod.isExtended())
.fallbackExecutionType(fallbackMethod.getExecutionType())
.extendedParentFallback(metaHolder.isExtendedFallback())
.observable(ExecutionType.OBSERVABLE == fallbackMethod.getExecutionType())
.defaultCommandKey(fMethod.getName())
.defaultGroupKey(metaHolder.getDefaultGroupKey())
.defaultThreadPoolKey(metaHolder.getDefaultThreadPoolKey())
.defaultProperties(metaHolder.getDefaultProperties().orNull())
.hystrixCollapser(metaHolder.getHystrixCollapser())
.observableExecutionMode(hystrixCommand.observableExecutionMode())
.hystrixCommand(hystrixCommand).build();
fallbackAction = new LazyCommandExecutionAction(fmMetaHolder);
} else {
MetaHolder fmMetaHolder = MetaHolder.builder()
.obj(metaHolder.getObj())
.defaultFallback(fallbackMethod.isDefault())
.method(fMethod)
.fallbackExecutionType(ExecutionType.SYNCHRONOUS)
.extendedFallback(fallbackMethod.isExtended())
.extendedParentFallback(metaHolder.isExtendedFallback())
.ajcMethod(null) // if fallback method isn't annotated with command annotation then we don't need to get ajc method for this
.args(args).build();
fallbackAction = new MethodExecutionAction(fmMetaHolder.getObj(), fMethod, fmMetaHolder.getArgs(), fmMetaHolder);
}
}
return fallbackAction;
}
private Method getAjcMethod(Object target, Method fallback) {
if (isCompileWeaving()) {
return getAjcMethodAroundAdvice(target.getClass(), fallback);
}
return null;
}
}
| 4,488 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/AsyncResult.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.command;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Fake implementation of {@link Future}. Can be used for method signatures
* which are declared with a Future return type for asynchronous execution.
* Provides abstract {@link #invoke()} method to wrap some logic for an asynchronous call.
*
* @param <T> the type of result
*/
public abstract class AsyncResult<T> implements Future<T>, ClosureCommand<T> {
private static final String ERROR_MSG = "AsyncResult is just a stub and cannot be used as complete implementation of Future";
@Override
public boolean cancel(boolean mayInterruptIfRunning) throws UnsupportedOperationException {
throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public boolean isCancelled() throws UnsupportedOperationException {
throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public boolean isDone() throws UnsupportedOperationException {
throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public T get() throws UnsupportedOperationException {
throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public T get(long timeout, TimeUnit unit) throws UnsupportedOperationException {
throw new UnsupportedOperationException(ERROR_MSG);
}
/**
* {@inheritDoc}.
*/
@Override
public abstract T invoke();
}
| 4,489 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/ExecutionType.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.command;
import com.google.common.collect.ImmutableSet;
import rx.Completable;
import rx.Observable;
import rx.Single;
import java.util.Set;
import java.util.concurrent.Future;
/**
* Specifies executions types.
*/
public enum ExecutionType {
/**
* Used for asynchronous execution of command.
*/
ASYNCHRONOUS,
/**
* Used for synchronous execution of command.
*/
SYNCHRONOUS,
/**
* Reactive execution (asynchronous callback).
*/
OBSERVABLE;
// RX types
private static final Set<? extends Class> RX_TYPES = ImmutableSet.of(Observable.class, Single.class, Completable.class);
/**
* Gets execution type for specified class type.
* @param type the type
* @return the execution type {@link ExecutionType}
*/
public static ExecutionType getExecutionType(Class<?> type) {
if (Future.class.isAssignableFrom(type)) {
return ExecutionType.ASYNCHRONOUS;
} else if (isRxType(type)) {
return ExecutionType.OBSERVABLE;
} else {
return ExecutionType.SYNCHRONOUS;
}
}
private static boolean isRxType(Class<?> cl) {
for (Class<?> rxType : RX_TYPES) {
if (rxType.isAssignableFrom(cl)) {
return true;
}
}
return false;
}
}
| 4,490 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/HystrixCommandBuilder.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.google.common.collect.ImmutableList;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContext;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import javax.annotation.concurrent.Immutable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Builder contains all necessary information required to create specific hystrix command.
*
* @author dmgcodevil
*/
@Immutable
public class HystrixCommandBuilder {
private final GenericSetterBuilder setterBuilder;
private final CommandActions commandActions;
private final CacheInvocationContext<CacheResult> cacheResultInvocationContext;
private final CacheInvocationContext<CacheRemove> cacheRemoveInvocationContext;
private final Collection<HystrixCollapser.CollapsedRequest<Object, Object>> collapsedRequests;
private final List<Class<? extends Throwable>> ignoreExceptions;
private final ExecutionType executionType;
public HystrixCommandBuilder(Builder builder) {
this.setterBuilder = builder.setterBuilder;
this.commandActions = builder.commandActions;
this.cacheResultInvocationContext = builder.cacheResultInvocationContext;
this.cacheRemoveInvocationContext = builder.cacheRemoveInvocationContext;
this.collapsedRequests = builder.collapsedRequests;
this.ignoreExceptions = builder.ignoreExceptions;
this.executionType = builder.executionType;
}
public static <ResponseType> Builder builder() {
return new Builder<ResponseType>();
}
public GenericSetterBuilder getSetterBuilder() {
return setterBuilder;
}
public CommandActions getCommandActions() {
return commandActions;
}
public CacheInvocationContext<CacheResult> getCacheResultInvocationContext() {
return cacheResultInvocationContext;
}
public CacheInvocationContext<CacheRemove> getCacheRemoveInvocationContext() {
return cacheRemoveInvocationContext;
}
public Collection<HystrixCollapser.CollapsedRequest<Object, Object>> getCollapsedRequests() {
return collapsedRequests;
}
public List<Class<? extends Throwable>> getIgnoreExceptions() {
return ignoreExceptions;
}
public ExecutionType getExecutionType() {
return executionType;
}
public static class Builder<ResponseType> {
private GenericSetterBuilder setterBuilder;
private CommandActions commandActions;
private CacheInvocationContext<CacheResult> cacheResultInvocationContext;
private CacheInvocationContext<CacheRemove> cacheRemoveInvocationContext;
private Collection<HystrixCollapser.CollapsedRequest<ResponseType, Object>> collapsedRequests = Collections.emptyList();
private List<Class<? extends Throwable>> ignoreExceptions = Collections.emptyList();
private ExecutionType executionType = ExecutionType.SYNCHRONOUS;
/**
* Sets the builder to create specific Hystrix setter, for instance HystrixCommand.Setter
*
* @param pSetterBuilder the builder to create specific Hystrix setter
* @return this {@link HystrixCommandBuilder.Builder}
*/
public Builder setterBuilder(GenericSetterBuilder pSetterBuilder) {
this.setterBuilder = pSetterBuilder;
return this;
}
/**
* Sets command actions {@link CommandActions}.
*
* @param pCommandActions the command actions
* @return this {@link HystrixCommandBuilder.Builder}
*/
public Builder commandActions(CommandActions pCommandActions) {
this.commandActions = pCommandActions;
return this;
}
/**
* Sets CacheResult invocation context, see {@link CacheInvocationContext} and {@link CacheResult}.
*
* @param pCacheResultInvocationContext the CacheResult invocation context
* @return this {@link HystrixCommandBuilder.Builder}
*/
public Builder cacheResultInvocationContext(CacheInvocationContext<CacheResult> pCacheResultInvocationContext) {
this.cacheResultInvocationContext = pCacheResultInvocationContext;
return this;
}
/**
* Sets CacheRemove invocation context, see {@link CacheInvocationContext} and {@link CacheRemove}.
*
* @param pCacheRemoveInvocationContext the CacheRemove invocation context
* @return this {@link HystrixCommandBuilder.Builder}
*/
public Builder cacheRemoveInvocationContext(CacheInvocationContext<CacheRemove> pCacheRemoveInvocationContext) {
this.cacheRemoveInvocationContext = pCacheRemoveInvocationContext;
return this;
}
/**
* Sets collapsed requests.
*
* @param pCollapsedRequests the collapsed requests
* @return this {@link HystrixCommandBuilder.Builder}
*/
public Builder collapsedRequests(Collection<HystrixCollapser.CollapsedRequest<ResponseType, Object>> pCollapsedRequests) {
this.collapsedRequests = pCollapsedRequests;
return this;
}
/**
* Sets exceptions that should be ignored and wrapped to throw in {@link com.netflix.hystrix.exception.HystrixBadRequestException}.
*
* @param pIgnoreExceptions the exceptions to be ignored
* @return this {@link HystrixCommandBuilder.Builder}
*/
public Builder ignoreExceptions(List<Class<? extends Throwable>> pIgnoreExceptions) {
this.ignoreExceptions = ImmutableList.copyOf(pIgnoreExceptions);
return this;
}
/**
* Sets execution type, see {@link ExecutionType}.
*
* @param pExecutionType the execution type
* @return this {@link HystrixCommandBuilder.Builder}
*/
public Builder executionType(ExecutionType pExecutionType) {
this.executionType = pExecutionType;
return this;
}
/**
* Creates new {@link HystrixCommandBuilder} instance.
*
* @return new {@link HystrixCommandBuilder} instance
*/
public HystrixCommandBuilder build() {
return new HystrixCommandBuilder(this);
}
}
}
| 4,491 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/CommandExecutor.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixExecutable;
import com.netflix.hystrix.HystrixInvokable;
import com.netflix.hystrix.HystrixObservable;
import com.netflix.hystrix.contrib.javanica.annotation.ObservableExecutionMode;
import com.netflix.hystrix.contrib.javanica.utils.FutureDecorator;
import org.apache.commons.lang3.Validate;
/**
* Invokes necessary method of {@link HystrixExecutable} or {@link HystrixObservable} for specified execution type:
* <p/>
* {@link ExecutionType#SYNCHRONOUS} -> {@link com.netflix.hystrix.HystrixExecutable#execute()}
* <p/>
* {@link ExecutionType#ASYNCHRONOUS} -> {@link com.netflix.hystrix.HystrixExecutable#queue()}
* <p/>
* {@link ExecutionType#OBSERVABLE} -> depends on specify observable execution mode:
* {@link ObservableExecutionMode#EAGER} - {@link HystrixObservable#observe()},
* {@link ObservableExecutionMode#LAZY} - {@link HystrixObservable#toObservable()}.
*/
public class CommandExecutor {
/**
* Calls a method of {@link HystrixExecutable} in accordance with specified execution type.
*
* @param invokable {@link HystrixInvokable}
* @param metaHolder {@link MetaHolder}
* @return the result of invocation of specific method.
* @throws RuntimeException
*/
public static Object execute(HystrixInvokable invokable, ExecutionType executionType, MetaHolder metaHolder) throws RuntimeException {
Validate.notNull(invokable);
Validate.notNull(metaHolder);
switch (executionType) {
case SYNCHRONOUS: {
return castToExecutable(invokable, executionType).execute();
}
case ASYNCHRONOUS: {
HystrixExecutable executable = castToExecutable(invokable, executionType);
if (metaHolder.hasFallbackMethodCommand()
&& ExecutionType.ASYNCHRONOUS == metaHolder.getFallbackExecutionType()) {
return new FutureDecorator(executable.queue());
}
return executable.queue();
}
case OBSERVABLE: {
HystrixObservable observable = castToObservable(invokable);
return ObservableExecutionMode.EAGER == metaHolder.getObservableExecutionMode() ? observable.observe() : observable.toObservable();
}
default:
throw new RuntimeException("unsupported execution type: " + executionType);
}
}
private static HystrixExecutable castToExecutable(HystrixInvokable invokable, ExecutionType executionType) {
if (invokable instanceof HystrixExecutable) {
return (HystrixExecutable) invokable;
}
throw new RuntimeException("Command should implement " + HystrixExecutable.class.getCanonicalName() + " interface to execute in: " + executionType + " mode");
}
private static HystrixObservable castToObservable(HystrixInvokable invokable) {
if (invokable instanceof HystrixObservable) {
return (HystrixObservable) invokable;
}
throw new RuntimeException("Command should implement " + HystrixObservable.class.getCanonicalName() + " interface to execute in observable mode");
}
}
| 4,492 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/GenericSetterBuilder.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.netflix.hystrix.contrib.javanica.exception.HystrixPropertyException;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.concurrent.Immutable;
import java.util.Collections;
import java.util.List;
import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.initializeCollapserProperties;
/**
* Builder for Hystrix Setters: {@link HystrixCommand.Setter}, {@link HystrixObservableCommand.Setter}, {@link HystrixCollapser.Setter}.
*/
@Immutable
public class GenericSetterBuilder {
private String groupKey;
private String commandKey;
private String threadPoolKey;
private String collapserKey;
private HystrixCollapser.Scope scope;
private List<HystrixProperty> commandProperties = Collections.emptyList();
private List<HystrixProperty> collapserProperties = Collections.emptyList();
private List<HystrixProperty> threadPoolProperties = Collections.emptyList();
public GenericSetterBuilder(Builder builder) {
this.groupKey = builder.groupKey;
this.commandKey = builder.commandKey;
this.threadPoolKey = builder.threadPoolKey;
this.collapserKey = builder.collapserKey;
this.scope = builder.scope;
this.commandProperties = builder.commandProperties;
this.collapserProperties = builder.collapserProperties;
this.threadPoolProperties = builder.threadPoolProperties;
}
public static Builder builder(){
return new Builder();
}
/**
* Creates instance of {@link HystrixCommand.Setter}.
*
* @return the instance of {@link HystrixCommand.Setter}
*/
public HystrixCommand.Setter build() throws HystrixPropertyException {
HystrixCommand.Setter setter = HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
if (StringUtils.isNotBlank(threadPoolKey)) {
setter.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(threadPoolKey));
}
try {
setter.andThreadPoolPropertiesDefaults(HystrixPropertiesManager.initializeThreadPoolProperties(threadPoolProperties));
} catch (IllegalArgumentException e) {
throw new HystrixPropertyException("Failed to set Thread Pool properties. " + getInfo(), e);
}
try {
setter.andCommandPropertiesDefaults(HystrixPropertiesManager.initializeCommandProperties(commandProperties));
} catch (IllegalArgumentException e) {
throw new HystrixPropertyException("Failed to set Command properties. " + getInfo(), e);
}
return setter;
}
// todo dmgcodevil: it would be better to reuse the code from build() method
public HystrixObservableCommand.Setter buildObservableCommandSetter() {
HystrixObservableCommand.Setter setter = HystrixObservableCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
try {
setter.andCommandPropertiesDefaults(HystrixPropertiesManager.initializeCommandProperties(commandProperties));
} catch (IllegalArgumentException e) {
throw new HystrixPropertyException("Failed to set Command properties. " + getInfo(), e);
}
return setter;
}
public HystrixCollapser.Setter buildCollapserCommandSetter(){
HystrixCollapserProperties.Setter propSetter = initializeCollapserProperties(collapserProperties);
return HystrixCollapser.Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey(collapserKey)).andScope(scope)
.andCollapserPropertiesDefaults(propSetter);
}
private String getInfo() {
return "groupKey: '" + groupKey + "', commandKey: '" + commandKey + "', threadPoolKey: '" + threadPoolKey + "'";
}
public static class Builder {
private String groupKey;
private String commandKey;
private String threadPoolKey;
private String collapserKey;
private HystrixCollapser.Scope scope;
private List<HystrixProperty> commandProperties = Collections.emptyList();
private List<HystrixProperty> collapserProperties = Collections.emptyList();
private List<HystrixProperty> threadPoolProperties = Collections.emptyList();
public Builder groupKey(String pGroupKey) {
this.groupKey = pGroupKey;
return this;
}
public Builder groupKey(String pGroupKey, String def) {
this.groupKey = StringUtils.isNotEmpty(pGroupKey) ? pGroupKey : def;
return this;
}
public Builder commandKey(String pCommandKey) {
this.commandKey = pCommandKey;
return this;
}
@Deprecated
public Builder commandKey(String pCommandKey, String def) {
this.commandKey = StringUtils.isNotEmpty(pCommandKey) ? pCommandKey : def;
return this;
}
public Builder collapserKey(String pCollapserKey) {
this.collapserKey = pCollapserKey;
return this;
}
public Builder scope(HystrixCollapser.Scope pScope) {
this.scope = pScope;
return this;
}
public Builder collapserProperties(List<HystrixProperty> properties) {
collapserProperties = properties;
return this;
}
public Builder commandProperties(List<HystrixProperty> properties) {
commandProperties = properties;
return this;
}
public Builder threadPoolProperties(List<HystrixProperty> properties) {
threadPoolProperties = properties;
return this;
}
public Builder threadPoolKey(String pThreadPoolKey) {
this.threadPoolKey = pThreadPoolKey;
return this;
}
public GenericSetterBuilder build(){
return new GenericSetterBuilder(this);
}
}
}
| 4,493 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/HystrixCommandFactory.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixInvokable;
import com.netflix.hystrix.contrib.javanica.collapser.CommandCollapser;
/**
* Created by dmgcodevil.
*/
public class HystrixCommandFactory {
private static final HystrixCommandFactory INSTANCE = new HystrixCommandFactory();
private HystrixCommandFactory() {
}
public static HystrixCommandFactory getInstance() {
return INSTANCE;
}
public HystrixInvokable create(MetaHolder metaHolder) {
HystrixInvokable executable;
if (metaHolder.isCollapserAnnotationPresent()) {
executable = new CommandCollapser(metaHolder);
} else if (metaHolder.isObservable()) {
executable = new GenericObservableCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder));
} else {
executable = new GenericCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder));
}
return executable;
}
public HystrixInvokable createDelayed(MetaHolder metaHolder) {
HystrixInvokable executable;
if (metaHolder.isObservable()) {
executable = new GenericObservableCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder));
} else {
executable = new GenericCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder));
}
return executable;
}
}
| 4,494 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/CommandExecutionAction.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixInvokable;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException;
/**
* Action to execute a Hystrix command.
*/
public class CommandExecutionAction implements CommandAction {
private HystrixInvokable hystrixCommand;
private MetaHolder metaHolder;
/**
* Constructor with parameters.
*
* @param hystrixCommand the hystrix command to execute.
*/
public CommandExecutionAction(HystrixInvokable hystrixCommand, MetaHolder metaHolder) {
this.hystrixCommand = hystrixCommand;
this.metaHolder = metaHolder;
}
@Override
public MetaHolder getMetaHolder() {
return metaHolder;
}
@Override
public Object execute(ExecutionType executionType) throws CommandActionExecutionException {
return CommandExecutor.execute(hystrixCommand, executionType, metaHolder);
}
@Override
public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException {
return CommandExecutor.execute(hystrixCommand, executionType, metaHolder);
}
/**
* {@inheritDoc}
*/
@Override
public String getActionName() {
if (hystrixCommand != null && hystrixCommand instanceof HystrixInvokableInfo) {
HystrixInvokableInfo info = (HystrixInvokableInfo) hystrixCommand;
return info.getCommandKey().name();
}
return "";
}
}
| 4,495 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/CommandActions.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.command;
/**
* Wrapper for command actions combines different actions together.
*
* @author dmgcodevil
*/
public class CommandActions {
private final CommandAction commandAction;
private final CommandAction fallbackAction;
public CommandActions(Builder builder) {
this.commandAction = builder.commandAction;
this.fallbackAction = builder.fallbackAction;
}
public static Builder builder() {
return new Builder();
}
public CommandAction getCommandAction() {
return commandAction;
}
public CommandAction getFallbackAction() {
return fallbackAction;
}
public boolean hasFallbackAction() {
return fallbackAction != null;
}
public static class Builder {
private CommandAction commandAction;
private CommandAction fallbackAction;
public Builder commandAction(CommandAction pCommandAction) {
this.commandAction = pCommandAction;
return this;
}
public Builder fallbackAction(CommandAction pFallbackAction) {
this.fallbackAction = pFallbackAction;
return this;
}
public CommandActions build() {
return new CommandActions(this);
}
}
}
| 4,496 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/GenericObservableCommand.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContext;
import com.netflix.hystrix.contrib.javanica.cache.HystrixCacheKeyGenerator;
import com.netflix.hystrix.contrib.javanica.cache.HystrixGeneratedCacheKey;
import com.netflix.hystrix.contrib.javanica.cache.HystrixRequestCacheManager;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException;
import com.netflix.hystrix.contrib.javanica.exception.FallbackInvocationException;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Completable;
import rx.Observable;
import rx.Single;
import rx.functions.Func1;
import javax.annotation.concurrent.ThreadSafe;
import java.util.List;
import static com.netflix.hystrix.contrib.javanica.utils.CommonUtils.createArgsForFallback;
/**
* Generic class for all observable commands executed within javanica context.
*/
@ThreadSafe
public class GenericObservableCommand extends HystrixObservableCommand {
private final CommandActions commandActions;
private final CacheInvocationContext<CacheResult> cacheResultInvocationContext;
private final CacheInvocationContext<CacheRemove> cacheRemoveInvocationContext;
private final List<Class<? extends Throwable>> ignoreExceptions;
private final ExecutionType executionType;
private final HystrixCacheKeyGenerator defaultCacheKeyGenerator = HystrixCacheKeyGenerator.getInstance();
private static final Logger LOGGER = LoggerFactory.getLogger(GenericObservableCommand.class);
public GenericObservableCommand(HystrixCommandBuilder builder) {
super(builder.getSetterBuilder().buildObservableCommandSetter());
this.commandActions = builder.getCommandActions();
this.cacheResultInvocationContext = builder.getCacheResultInvocationContext();
this.cacheRemoveInvocationContext = builder.getCacheRemoveInvocationContext();
this.ignoreExceptions = builder.getIgnoreExceptions();
this.executionType = builder.getExecutionType();
}
/**
*{@inheritDoc}.
*/
@Override
protected Observable construct() {
Observable result;
try {
Observable observable = toObservable(commandActions.getCommandAction().execute(executionType));
result = observable
.onErrorResumeNext(new Func1<Throwable, Observable>() {
@Override
public Observable call(Throwable throwable) {
if (isIgnorable(throwable)) {
return Observable.error(new HystrixBadRequestException(throwable.getMessage(), throwable));
}
return Observable.error(throwable);
}
});
flushCache();
} catch (CommandActionExecutionException throwable) {
Throwable cause = throwable.getCause();
if (isIgnorable(cause)) {
throw new HystrixBadRequestException(cause.getMessage(), cause);
}
throw throwable;
}
return result;
}
/**
*{@inheritDoc}.
*/
@Override
protected Observable resumeWithFallback() {
if (commandActions.hasFallbackAction()) {
MetaHolder metaHolder = commandActions.getFallbackAction().getMetaHolder();
Throwable cause = getExecutionException();
if (cause instanceof CommandActionExecutionException) {
cause = cause.getCause();
}
Object[] args = createArgsForFallback(metaHolder, cause);
try {
Object res = commandActions.getFallbackAction().executeWithArgs(executionType, args);
if (res instanceof Observable) {
return (Observable) res;
} else if (res instanceof Single) {
return ((Single) res).toObservable();
} else if (res instanceof Completable) {
return ((Completable) res).toObservable();
} else {
return Observable.just(res);
}
} catch (Exception e) {
LOGGER.error(AbstractHystrixCommand.FallbackErrorMessageBuilder.create()
.append(commandActions.getFallbackAction(), e).build());
throw new FallbackInvocationException(e.getCause());
}
}
return super.resumeWithFallback();
}
/**
* {@inheritDoc}.
*/
@Override
protected String getCacheKey() {
String key = null;
if (cacheResultInvocationContext != null) {
HystrixGeneratedCacheKey hystrixGeneratedCacheKey =
defaultCacheKeyGenerator.generateCacheKey(cacheResultInvocationContext);
key = hystrixGeneratedCacheKey.getCacheKey();
}
return key;
}
/**
* Clears cache for the specified hystrix command.
*/
protected void flushCache() {
if (cacheRemoveInvocationContext != null) {
HystrixRequestCacheManager.getInstance().clearCache(cacheRemoveInvocationContext);
}
}
/**
* Check whether triggered exception is ignorable.
*
* @param throwable the exception occurred during a command execution
* @return true if exception is ignorable, otherwise - false
*/
boolean isIgnorable(Throwable throwable) {
if (ignoreExceptions == null || ignoreExceptions.isEmpty()) {
return false;
}
for (Class<? extends Throwable> ignoreException : ignoreExceptions) {
if (ignoreException.isAssignableFrom(throwable.getClass())) {
return true;
}
}
return false;
}
private Observable toObservable(Object obj) {
if (Observable.class.isAssignableFrom(obj.getClass())) {
return (Observable) obj;
} else if (Completable.class.isAssignableFrom(obj.getClass())) {
return ((Completable) obj).toObservable();
} else if (Single.class.isAssignableFrom(obj.getClass())) {
return ((Single) obj).toObservable();
} else {
throw new IllegalStateException("unsupported rx type: " + obj.getClass());
}
}
}
| 4,497 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/MetaHolder.java | /**
* Copyright 2012 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.hystrix.contrib.javanica.command;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.netflix.hystrix.contrib.javanica.annotation.*;
import com.netflix.hystrix.contrib.javanica.command.closure.Closure;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Simple immutable holder to keep all necessary information about current method to build Hystrix command.
*/
// todo: replace fallback related flags with FallbackMethod class
@Immutable
public final class MetaHolder {
private final HystrixCollapser hystrixCollapser;
private final HystrixCommand hystrixCommand;
private final DefaultProperties defaultProperties;
private final Method method;
private final Method cacheKeyMethod;
private final Method ajcMethod;
private final Method fallbackMethod;
private final Object obj;
private final Object proxyObj;
private final Object[] args;
private final Closure closure;
private final String defaultGroupKey;
private final String defaultCommandKey;
private final String defaultCollapserKey;
private final String defaultThreadPoolKey;
private final ExecutionType executionType;
private final boolean extendedFallback;
private final ExecutionType collapserExecutionType;
private final ExecutionType fallbackExecutionType;
private final boolean fallback;
private boolean extendedParentFallback;
private final boolean defaultFallback;
private final JoinPoint joinPoint;
private final boolean observable;
private final ObservableExecutionMode observableExecutionMode;
private static final Function identityFun = new Function<Object, Object>() {
@Nullable
@Override
public Object apply(@Nullable Object input) {
return input;
}
};
private MetaHolder(Builder builder) {
this.hystrixCommand = builder.hystrixCommand;
this.method = builder.method;
this.cacheKeyMethod = builder.cacheKeyMethod;
this.fallbackMethod = builder.fallbackMethod;
this.ajcMethod = builder.ajcMethod;
this.obj = builder.obj;
this.proxyObj = builder.proxyObj;
this.args = builder.args;
this.closure = builder.closure;
this.defaultGroupKey = builder.defaultGroupKey;
this.defaultCommandKey = builder.defaultCommandKey;
this.defaultThreadPoolKey = builder.defaultThreadPoolKey;
this.defaultCollapserKey = builder.defaultCollapserKey;
this.defaultProperties = builder.defaultProperties;
this.hystrixCollapser = builder.hystrixCollapser;
this.executionType = builder.executionType;
this.collapserExecutionType = builder.collapserExecutionType;
this.fallbackExecutionType = builder.fallbackExecutionType;
this.joinPoint = builder.joinPoint;
this.extendedFallback = builder.extendedFallback;
this.defaultFallback = builder.defaultFallback;
this.fallback = builder.fallback;
this.extendedParentFallback = builder.extendedParentFallback;
this.observable = builder.observable;
this.observableExecutionMode = builder.observableExecutionMode;
}
public static Builder builder() {
return new Builder();
}
public HystrixCollapser getHystrixCollapser() {
return hystrixCollapser;
}
public HystrixCommand getHystrixCommand() {
return hystrixCommand;
}
public Method getMethod() {
return method;
}
public Method getCacheKeyMethod() {
return cacheKeyMethod;
}
public Method getAjcMethod() {
return ajcMethod;
}
public Object getObj() {
return obj;
}
public Object getProxyObj() {
return proxyObj;
}
public Closure getClosure() {
return closure;
}
public ExecutionType getExecutionType() {
return executionType;
}
public ExecutionType getCollapserExecutionType() {
return collapserExecutionType;
}
public Object[] getArgs() {
return args != null ? Arrays.copyOf(args, args.length) : new Object[]{};
}
public String getCommandGroupKey() {
return isCommandAnnotationPresent() ? get(hystrixCommand.groupKey(), defaultGroupKey) : "";
}
public String getDefaultGroupKey() {
return defaultGroupKey;
}
public String getDefaultThreadPoolKey() {
return defaultThreadPoolKey;
}
public String getCollapserKey() {
return isCollapserAnnotationPresent() ? get(hystrixCollapser.collapserKey(), defaultCollapserKey) : "";
}
public String getCommandKey() {
return isCommandAnnotationPresent() ? get(hystrixCommand.commandKey(), defaultCommandKey) : "";
}
public String getThreadPoolKey() {
return isCommandAnnotationPresent() ? get(hystrixCommand.threadPoolKey(), defaultThreadPoolKey) : "";
}
public String getDefaultCommandKey() {
return defaultCommandKey;
}
public String getDefaultCollapserKey() {
return defaultCollapserKey;
}
public boolean hasDefaultProperties() {
return defaultProperties != null;
}
public Optional<DefaultProperties> getDefaultProperties() {
return Optional.fromNullable(defaultProperties);
}
public Class<?>[] getParameterTypes() {
return method.getParameterTypes();
}
public boolean isCollapserAnnotationPresent() {
return hystrixCollapser != null;
}
public boolean isCommandAnnotationPresent() {
return hystrixCommand != null;
}
public JoinPoint getJoinPoint() {
return joinPoint;
}
public Method getFallbackMethod() {
return fallbackMethod;
}
public boolean hasFallbackMethod() {
return fallbackMethod != null;
}
public boolean isExtendedParentFallback() {
return extendedParentFallback;
}
public boolean hasFallbackMethodCommand() {
return fallbackMethod != null && fallbackMethod.isAnnotationPresent(HystrixCommand.class);
}
public boolean isFallback() {
return fallback;
}
public boolean isExtendedFallback() {
return extendedFallback;
}
public boolean isDefaultFallback() {
return defaultFallback;
}
@SuppressWarnings("unchecked")
public List<Class<? extends Throwable>> getCommandIgnoreExceptions() {
if (!isCommandAnnotationPresent()) return Collections.emptyList();
return getOrDefault(new Supplier<List<Class<? extends Throwable>>>() {
@Override
public List<Class<? extends Throwable>> get() {
return ImmutableList.<Class<? extends Throwable>>copyOf(hystrixCommand.ignoreExceptions());
}
}, new Supplier<List<Class<? extends Throwable>>>() {
@Override
public List<Class<? extends Throwable>> get() {
return hasDefaultProperties()
? ImmutableList.<Class<? extends Throwable>>copyOf(defaultProperties.ignoreExceptions())
: Collections.<Class<? extends Throwable>>emptyList();
}
}, this.<Class<? extends Throwable>>nonEmptyList());
}
public ExecutionType getFallbackExecutionType() {
return fallbackExecutionType;
}
public List<HystrixProperty> getCommandProperties() {
if (!isCommandAnnotationPresent()) return Collections.emptyList();
return getOrDefault(new Supplier<List<HystrixProperty>>() {
@Override
public List<HystrixProperty> get() {
return ImmutableList.copyOf(hystrixCommand.commandProperties());
}
}, new Supplier<List<HystrixProperty>>() {
@Override
public List<HystrixProperty> get() {
return hasDefaultProperties()
? ImmutableList.copyOf(defaultProperties.commandProperties())
: Collections.<HystrixProperty>emptyList();
}
}, this.<HystrixProperty>nonEmptyList());
}
public List<HystrixProperty> getCollapserProperties() {
return isCollapserAnnotationPresent() ? ImmutableList.copyOf(hystrixCollapser.collapserProperties()) : Collections.<HystrixProperty>emptyList();
}
public List<HystrixProperty> getThreadPoolProperties() {
if (!isCommandAnnotationPresent()) return Collections.emptyList();
return getOrDefault(new Supplier<List<HystrixProperty>>() {
@Override
public List<HystrixProperty> get() {
return ImmutableList.copyOf(hystrixCommand.threadPoolProperties());
}
}, new Supplier<List<HystrixProperty>>() {
@Override
public List<HystrixProperty> get() {
return hasDefaultProperties()
? ImmutableList.copyOf(defaultProperties.threadPoolProperties())
: Collections.<HystrixProperty>emptyList();
}
}, this.<HystrixProperty>nonEmptyList());
}
public boolean isObservable() {
return observable;
}
public ObservableExecutionMode getObservableExecutionMode() {
return observableExecutionMode;
}
public boolean raiseHystrixExceptionsContains(HystrixException hystrixException) {
return getRaiseHystrixExceptions().contains(hystrixException);
}
public List<HystrixException> getRaiseHystrixExceptions() {
return getOrDefault(new Supplier<List<HystrixException>>() {
@Override
public List<HystrixException> get() {
return ImmutableList.copyOf(hystrixCommand.raiseHystrixExceptions());
}
}, new Supplier<List<HystrixException>>() {
@Override
public List<HystrixException> get() {
return hasDefaultProperties()
? ImmutableList.copyOf(defaultProperties.raiseHystrixExceptions())
: Collections.<HystrixException>emptyList();
}
}, this.<HystrixException>nonEmptyList());
}
private String get(String key, String defaultKey) {
return StringUtils.isNotBlank(key) ? key : defaultKey;
}
private <T> Predicate<List<T>> nonEmptyList() {
return new Predicate<List<T>>() {
@Override
public boolean apply(@Nullable List<T> input) {
return input != null && !input.isEmpty();
}
};
}
@SuppressWarnings("unchecked")
private <T> T getOrDefault(Supplier<T> source, Supplier<T> defaultChoice, Predicate<T> isDefined) {
return getOrDefault(source, defaultChoice, isDefined, (Function<T, T>) identityFun);
}
private <T> T getOrDefault(Supplier<T> source, Supplier<T> defaultChoice, Predicate<T> isDefined, Function<T, T> map) {
T res = source.get();
if (!isDefined.apply(res)) {
res = defaultChoice.get();
}
return map.apply(res);
}
public static final class Builder {
private static final Class<?>[] EMPTY_ARRAY_OF_TYPES= new Class[0];
private HystrixCollapser hystrixCollapser;
private HystrixCommand hystrixCommand;
private DefaultProperties defaultProperties;
private Method method;
private Method cacheKeyMethod;
private Method fallbackMethod;
private Method ajcMethod;
private Object obj;
private Object proxyObj;
private Closure closure;
private Object[] args;
private String defaultGroupKey;
private String defaultCommandKey;
private String defaultCollapserKey;
private String defaultThreadPoolKey;
private ExecutionType executionType;
private ExecutionType collapserExecutionType;
private ExecutionType fallbackExecutionType;
private boolean extendedFallback;
private boolean fallback;
private boolean extendedParentFallback;
private boolean defaultFallback;
private boolean observable;
private JoinPoint joinPoint;
private ObservableExecutionMode observableExecutionMode;
public Builder hystrixCollapser(HystrixCollapser hystrixCollapser) {
this.hystrixCollapser = hystrixCollapser;
return this;
}
public Builder hystrixCommand(HystrixCommand hystrixCommand) {
this.hystrixCommand = hystrixCommand;
return this;
}
public Builder method(Method method) {
this.method = method;
return this;
}
public Builder cacheKeyMethod(Method cacheKeyMethod) {
this.cacheKeyMethod = cacheKeyMethod;
return this;
}
public Builder fallbackMethod(Method fallbackMethod) {
this.fallbackMethod = fallbackMethod;
return this;
}
public Builder fallbackExecutionType(ExecutionType fallbackExecutionType) {
this.fallbackExecutionType = fallbackExecutionType;
return this;
}
public Builder fallback(boolean fallback) {
this.fallback = fallback;
return this;
}
public Builder extendedParentFallback(boolean extendedParentFallback) {
this.extendedParentFallback = extendedParentFallback;
return this;
}
public Builder defaultFallback(boolean defaultFallback) {
this.defaultFallback = defaultFallback;
return this;
}
public Builder ajcMethod(Method ajcMethod) {
this.ajcMethod = ajcMethod;
return this;
}
public Builder obj(Object obj) {
this.obj = obj;
return this;
}
public Builder proxyObj(Object proxy) {
this.proxyObj = proxy;
return this;
}
public Builder args(Object[] args) {
this.args = args;
return this;
}
public Builder closure(Closure closure) {
this.closure = closure;
return this;
}
public Builder executionType(ExecutionType executionType) {
this.executionType = executionType;
return this;
}
public Builder collapserExecutionType(ExecutionType collapserExecutionType) {
this.collapserExecutionType = collapserExecutionType;
return this;
}
public Builder defaultGroupKey(String defGroupKey) {
this.defaultGroupKey = defGroupKey;
return this;
}
public Builder defaultCommandKey(String defCommandKey) {
this.defaultCommandKey = defCommandKey;
return this;
}
public Builder defaultThreadPoolKey(String defaultThreadPoolKey) {
this.defaultThreadPoolKey = defaultThreadPoolKey;
return this;
}
public Builder defaultCollapserKey(String defCollapserKey) {
this.defaultCollapserKey = defCollapserKey;
return this;
}
public Builder defaultProperties(@Nullable DefaultProperties defaultProperties) {
this.defaultProperties = defaultProperties;
return this;
}
public Builder joinPoint(JoinPoint joinPoint) {
this.joinPoint = joinPoint;
return this;
}
public Builder extendedFallback(boolean extendedFallback) {
this.extendedFallback = extendedFallback;
return this;
}
public Builder observable(boolean observable) {
this.observable = observable;
return this;
}
public Builder observableExecutionMode(ObservableExecutionMode observableExecutionMode) {
this.observableExecutionMode = observableExecutionMode;
return this;
}
public MetaHolder build() {
return new MetaHolder(this);
}
}
}
| 4,498 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/CommandAction.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hystrix.contrib.javanica.command;
import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException;
/**
* Simple action to encapsulate some logic to process it in a Hystrix command.
*/
public interface CommandAction {
MetaHolder getMetaHolder();
/**
* Executes action in accordance with the given execution type.
*
* @param executionType the execution type
* @return result of execution
* @throws com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException
*/
Object execute(ExecutionType executionType) throws CommandActionExecutionException;
/**
* Executes action with parameters in accordance with the given execution ty
*
* @param executionType the execution type
* @param args the parameters of the action
* @return result of execution
* @throws com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException
*/
Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException;
/**
* Gets action name. Useful for debugging.
*
* @return the action name
*/
String getActionName();
}
| 4,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.