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/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/PropertyBinderFactory.java | package com.netflix.fabricator;
import java.lang.reflect.Method;
/**
* Abstraction for a factory to created bindings for specific types.
* There should be one of these for each argument type. Ex. String, Integer, ...
*
* @author elandau
*
*/
public interface PropertyBinderFactory {
public PropertyBinder createBinder(Method method, String propertyName);
}
| 2,100 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/PropertyInfo.java | package com.netflix.fabricator;
/**
* Encapsulate a representation of a property and different method variations
* for setting it.
*
* I. Primitive type
* prefix.${id}.field1=boolean|number|string|list|... withField1(String value)
* withField1(Supplier<String> value)
* withField1(ListenableSupplier<String> value)
*
* II. Named
* 1. prefix.${id}.field1=${name} withField1(Foo foo);
*
* bind(Foo.class).annotatedWith("name").to(FooImpl.class) // Has a named binding
* MapBinder<String, Snack> mapbinder
* = MapBinder.newMapBinder(binder(), String.class, Snack.class);
*
* III. Policy (policy is an interface)
* 1. prefix.${id}.policy1.type MapBinder<String, Snack> mapbinder
* prefix.${id}.policy1.field1=... = MapBinder.newMapBinder(binder(), String.class, Snack.class);
*
* IV. Embedded (embedded is a complex type) withFoo(Foo foo); // No named binding
* 1. prefix.${id}.embedded1.field1
* prefix.${id}.embedded2.field2
*
* @author elandau
*/
public class PropertyInfo {
private String name;
private PropertyBinder simple;
private PropertyBinder dynamic;
private PropertyBinder binding;
public PropertyInfo(String name) {
this.name = name;
}
public void addSimple(PropertyBinder simple) {
this.simple = simple;
}
public void addDynamic(PropertyBinder dynamic) {
this.dynamic = dynamic;
}
public void addBinding(PropertyBinder binding) {
this.binding = binding;
}
public void apply(Object obj, ConfigurationNode config) throws Exception {
if (binding != null && binding.bind(obj, config)) {}
else if (dynamic != null && dynamic.bind(obj, config)) {}
else if (simple != null && simple.bind(obj, config)) {}
}
public String getName() {
return name;
}
}
| 2,101 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/Fabricator.java | package com.netflix.fabricator;
import java.util.Map;
import java.util.Properties;
import com.google.common.annotations.Beta;
import com.google.common.collect.Maps;
import com.netflix.fabricator.component.ComponentFactory;
import com.netflix.fabricator.component.ComponentManager;
import com.netflix.fabricator.component.bind.SimplePropertyBinderFactoryResolver;
import com.netflix.fabricator.properties.PropertiesTypeConfigurationResolver;
/**
* Standalone version of Fabricator instead of integrating with a DI framework.
* This should mainly be used for testing or when a DI framework is not desired.
* @author elandau
*/
@Beta
public class Fabricator {
public static class Builder {
private TypeConfigurationResolver configurationResolver;
public Builder forProperties(Properties props) {
configurationResolver = new PropertiesTypeConfigurationResolver(props, null);
return this;
}
public Fabricator build() {
return new Fabricator(this);
}
}
public static Builder builder() {
return new Builder();
}
private final TypeConfigurationResolver resolver;
private final Map<Class<?>, ComponentManager<?>> factories = Maps.newHashMap();
private final PropertyBinderResolver binderResolver = new SimplePropertyBinderFactoryResolver();
Fabricator(Builder builder) {
this.resolver = builder.configurationResolver;
}
public <T> T get(String id, Class<T> type) throws Exception {
ComponentManager<T> manager = (ComponentManager<T>) factories.get(type);
if (manager == null) {
ComponentFactory<T> factory = new BindingComponentFactory<T>(type, binderResolver, null).get();
// manager = new SynchronizedComponentManager<T>(ComponentType.from(type), );
// factories.put(type, factory);
// private final Map<Class<?>, ComponentManager<?>> factories = Maps.newHashMap();
}
// public SynchronizedComponentManager(
// ComponentType<T> type,
// Map<String, ComponentFactory<T>> factories,
// TypeConfigurationResolver config) {
return null;
}
}
| 2,102 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/TypeConfigurationResolver.java | package com.netflix.fabricator;
/**
* API for resolving the ComponentConfigurationResolver for a specified type
* A concrete TypeConfigurationResolver will normally encapsulate an entire
* configuration file that holds configurations for multiple components of
* varying types.
*
* @see PropertiesTypeConfigurationResolver
*
* @author elandau
*/
public interface TypeConfigurationResolver {
public ComponentConfigurationResolver getConfigurationFactory(String type);
}
| 2,103 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/PropertyBinder.java | package com.netflix.fabricator;
/**
* I. Primitive type
* prefix.${id}.field1=boolean|number|string|list|... withField1(String value)
* withField1(Supplier<String> value)
* withField1(ListenableSupplier<String> value)
*
* II. Named
* 1. prefix.${id}.field1=${name} withField1(Foo foo);
*
* bind(Foo.class).annotatedWith("name").to(FooImpl.class) // Has a named binding
* MapBinder<String, Snack> mapbinder
* = MapBinder.newMapBinder(binder(), String.class, Snack.class);
*
* III. Policy (policy is an interface)
* 1. prefix.${id}.policy1.type MapBinder<String, Snack> mapbinder
* prefix.${id}.policy1.field1=... = MapBinder.newMapBinder(binder(), String.class, Snack.class);
*
* IV. Embedded (embedded is a complex type) withFoo(Foo foo); // No named binding
* 1. prefix.${id}.embedded1.field1
* prefix.${id}.embedded2.field2
*
* @author elandau
*
*/
public interface PropertyBinder {
public boolean bind(Object obj, ConfigurationNode node) throws Exception;
}
| 2,104 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/BindingComponentFactory.java | package com.netflix.fabricator;
import com.google.common.base.CaseFormat;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.netflix.fabricator.component.ComponentFactory;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
/**
* Utility class for creating a binding between a type string name and an
* implementation using the builder pattern.
*
* TODO: PostConstruct and PreDestroy
*
* @author elandau
*
* @param <T>
*
*/
public class BindingComponentFactory<T> {
private static final Logger LOG = LoggerFactory.getLogger(BindingComponentFactory.class);
private static final String BUILDER_METHOD_NAME = "builder";
private static final String BUILD_METHOD_NAME = "build";
private static final String ID_METHOD_SUFFIX = "Id"; // TODO: Make this configurable
private static final String WITH_METHOD_PREFIX = "with";
private static final String SET_METHOD_PREFIX = "set";
private final ComponentFactory<T> factory;
public static interface Instantiator {
public Object create(ConfigurationNode config) throws Exception ;
}
/**
* Class determined to be the builder
*/
private Class<?> builderClass;
/**
* Map of all object properties keyed by property name.
*
* TODO: What about multiple methods for the same property?
*/
private final Map<String, PropertyInfo> properties;
/**
* Implementation determined to be best method for instantiating an instance of T or it's builder
*/
private Instantiator instantiator;
private PropertyBinderResolver binderResolver;
public BindingComponentFactory(final Class<?> clazz, PropertyBinderResolver binderResolver, final InjectionSpi injector) {
this.binderResolver = binderResolver;
try {
// Check if this class is a Builder<T> in which case just create
// an instance of the builder and treat it as a builder with builder
// method get().
if (Builder.class.isAssignableFrom(clazz)) {
this.builderClass = clazz;
this.instantiator = new Instantiator() {
public Object create(@Nullable ConfigurationNode config) {
return (Builder<?>) injector.getInstance(clazz);
}
};
}
// Check if there is a builder() method that returns an instance of the
// builder.
else {
final Method method = clazz.getMethod(BUILDER_METHOD_NAME);
this.builderClass = method.getReturnType();
this.instantiator = new Instantiator() {
public Object create(ConfigurationNode config) throws Exception {
Object obj = method.invoke(null, (Object[])null);
injector.injectMembers(obj);
return obj;
}
};
}
}
catch (Exception e) {
// Otherwise, look for a Builder inner class of T
for (final Class<?> inner : clazz.getClasses()) {
if (inner.getSimpleName().equals("Builder")) {
this.builderClass = inner;
this.instantiator = new Instantiator() {
public Object create(ConfigurationNode config) {
return injector.getInstance(inner);
}
};
break;
}
}
}
Preconditions.checkNotNull(builderClass, "No builder class found for " + clazz.getCanonicalName());
properties = makePropertiesMap(builderClass);
this.factory = new ComponentFactory<T>() {
@SuppressWarnings("unchecked")
@Override
public T create(ConfigurationNode config) {
try {
// 1. Create an instance of the builder. This still will also do basic
// dependency injection using @Inject. Named injections will be handled
// by the configuration mapping phase
Object builder = instantiator.create(config);
// 2. Set the 'id'
mapId(builder, config);
// 3. Apply configuration
mapConfiguration(builder, config);
// 4. call build()
Method buildMethod = builder.getClass().getMethod(BUILD_METHOD_NAME);
return (T) buildMethod.invoke(builder);
} catch (Exception e) {
throw new RuntimeException(String.format("Error creating component '%s' of type '%s'", config.getId(), clazz.getName()), e);
}
}
@Override
public Map<String, PropertyInfo> getProperties() {
return properties;
}
@Override
public Class<?> getRawType() {
return clazz;
}
};
}
private void mapId(Object builder, ConfigurationNode config) throws Exception {
if (config.getId() != null) {
Method idMethod = null;
try {
idMethod = builder.getClass().getMethod(WITH_METHOD_PREFIX + ID_METHOD_SUFFIX, String.class);
}catch (NoSuchMethodException e) {
// OK to ignore
}
if(idMethod == null) {
try {
idMethod = builder.getClass().getMethod(SET_METHOD_PREFIX + ID_METHOD_SUFFIX, String.class);
}catch (NoSuchMethodException e) {
// OK to ignore
}
}
if (idMethod != null) {
idMethod.invoke(builder, config.getId());
} else {
LOG.trace("cannot find id method");
}
}
}
/**
* Perform the actual configuration mapping by iterating through all parameters
* and applying the config.
*
* @param obj
* @param config
* @throws Exception
*/
private void mapConfiguration(Object obj, ConfigurationNode node) throws Exception {
for (Entry<String, PropertyInfo> prop : properties.entrySet()) {
ConfigurationNode child = node.getChild(prop.getKey());
if (child != null) {
try {
prop.getValue().apply(obj, child);
}
catch (Exception e) {
throw new Exception("Failed to map property: " + prop.getKey(), e);
}
}
}
}
private static boolean hasInjectAnnotation(Method method) {
return method.isAnnotationPresent(Inject.class) ||
method.isAnnotationPresent(javax.inject.Inject.class);
}
private static String getPropertyName(Method method) {
if (method.getName().startsWith(WITH_METHOD_PREFIX)) {
return CaseFormat.UPPER_CAMEL.to(
CaseFormat.LOWER_CAMEL,
StringUtils.substringAfter(method.getName(), WITH_METHOD_PREFIX));
}
if (method.getName().startsWith(SET_METHOD_PREFIX)) {
return CaseFormat.UPPER_CAMEL.to(
CaseFormat.LOWER_CAMEL,
StringUtils.substringAfter(method.getName(), SET_METHOD_PREFIX));
}
return null;
}
/**
* Return all deduced properties.
*
* @param builderClass
* @return
*/
private Map<String, PropertyInfo> makePropertiesMap(Class<?> builderClass) {
Map<String, PropertyInfo> properties = Maps.newHashMap();
// Iterate through each method and try to match a property
for (final Method method : builderClass.getMethods()) {
// Skip methods that do real DI. These will have been injected at object creation
if (hasInjectAnnotation(method)) {
continue;
}
// Deduce property name from the method
final String propertyName = getPropertyName(method);
if (propertyName == null) {
continue;
}
// Only support methods with a single parameter.
// TODO: Might want to support methods that take TimeUnit
Class<?>[] types = method.getParameterTypes();
if (types.length != 1) {
continue;
}
PropertyInfo prop = new PropertyInfo(propertyName);
PropertyBinder binding = binderResolver.get(method);
if (binding != null) {
prop.addBinding(binding);
properties.put(propertyName, prop);
}
}
return properties;
}
public ComponentFactory<T> get() {
return factory;
}
}
| 2,105 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/ComponentConfigurationResolver.java | package com.netflix.fabricator;
import java.util.Map;
/**
* The ComponentConfigurationResolver encapsulates the configuration naming convention
* for a specific type of components. The resolver returns the ComponentConfiguration
* for an id of it's type using whatever naming convension it chooses.
*
* @author elandau
*/
public interface ComponentConfigurationResolver {
/**
* Return a configuration for the specified type with root context for the specified key
*
* @param id
* @return
*/
public ConfigurationNode getConfiguration(String id);
/**
* Return a map of ALL component configurations for this type.
*
* @return A map where key=id and value=the configuration
*/
public Map<String, ConfigurationNode> getAllConfigurations();
}
| 2,106 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/PropertyBinderResolver.java | package com.netflix.fabricator;
import java.lang.reflect.Method;
public interface PropertyBinderResolver {
PropertyBinder get(Method method);
}
| 2,107 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/ConfigurationNode.java | package com.netflix.fabricator;
import java.util.Set;
import com.netflix.fabricator.supplier.ListenableSupplier;
public interface ConfigurationNode {
/**
* Provide the unique key for the component specified in the configuration.
* Can be null for components that are not to be cached or when accessing
* a subconfiguration such as a policy.
*
* @return
*/
public String getId();
/**
* Get a value for the property
*
* @param propertyName Simple property name (no prefix)
* @param type Expected value type (ex. Integer.class)
* @return The value or null if not found or type not supported
*/
public <T> T getValue(Class<T> type);
/**
* Get a dynamic version of the property with optional on change notification
*
* @param propertyName Simple property name (no prefix)
* @param type Expected value type (ex. Integer.class)
* @return A supplier to the value or null if type not supported
*/
public <T> ListenableSupplier<T> getDynamicValue(Class<T> type);
/**
* Return a ConfigurationSource that a sub-context of the underlying configuration.
* For example,
*
* getChild("policy") on the following JSON will return the node rooted at "policy"
*
* {
* "prop1" : "abc",
* "policy" : {
* "prop2" : "def"
* },
* }
*
*
* @return
*/
public ConfigurationNode getChild(String propertyName);
/**
* @return Return true if the property is a single value. Return false if the property
* is a nested structure
*/
public boolean isSingle();
/**
* @param propertyName
* @return Return true if the property exists.
*/
public boolean hasChild(String propertyName);
/**
* Get the component type. When using MapBinder to provide different implementations
* the type will match the key in the MapBinder.
* @return
*/
public String getType();
/**
* Return a list of properties in the configuration for which there is no method.
*
* @param supportedProperties
* @return Return a set of unknown properties.
*/
public Set<String> getUnknownProperties(Set<String> supportedProperties);
}
| 2,108 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/util/Executors2.java | package com.netflix.fabricator.util;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Utility class for creating various types of thread pools
* @author elandau
*
*/
public final class Executors2 {
static public Executor newBoundedQueueFixedPool(int numThreads, int queueDepth, ThreadFactory factory) {
final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(queueDepth);
RejectedExecutionHandler handler = new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable arg0, ThreadPoolExecutor arg1) {
try {
queue.put(arg0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
};
return new ThreadPoolExecutor(numThreads, numThreads, 1, TimeUnit.MINUTES, queue, factory, handler);
}
static public Executor newBoundedQueueFixedPool(int numThreads, int queueDepth) {
final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(queueDepth);
RejectedExecutionHandler handler = new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable arg0, ThreadPoolExecutor arg1) {
try {
queue.put(arg0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
};
return new ThreadPoolExecutor(numThreads, numThreads, 1, TimeUnit.MINUTES, queue, handler);
}
}
| 2,109 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/util/UnstoppableStopwatch.java | package com.netflix.fabricator.util;
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
public class UnstoppableStopwatch {
private final Stopwatch sw;
public UnstoppableStopwatch() {
sw = Stopwatch.createStarted();
}
public long elapsed(TimeUnit units) {
return sw.elapsed(units);
}
}
| 2,110 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/ComponentFactory.java | package com.netflix.fabricator.component;
import java.util.Map;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyInfo;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
/**
* Factory for a specific component type.
*
* @author elandau
*
* @param <T>
*/
public interface ComponentFactory<T> {
/**
* Create an instance of the component using the provided config
* @param config
* @return
* @throws ComponentCreationException
* @throws ComponentAlreadyExistsException
*/
T create(ConfigurationNode config) throws ComponentAlreadyExistsException, ComponentCreationException;
/**
* Return configuration properties of T
* @return
*/
Map<String, PropertyInfo> getProperties();
/**
* Return the actual type of T
* @return
*/
Class<?> getRawType();
}
| 2,111 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/SynchronizedComponentManager.java | package com.netflix.fabricator.component;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.netflix.fabricator.ComponentConfigurationResolver;
import com.netflix.fabricator.ComponentType;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.TypeConfigurationResolver;
import com.netflix.fabricator.annotations.Default;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* Implementation of a ComponentManager where each method is synchronized to guarantee
* thread safety. Uses guice MapBinder to specify the different types of component
* implementations.
*
* @author elandau
*
* @param <T>
*/
public class SynchronizedComponentManager<T> implements ComponentManager<T> {
private Logger LOG = LoggerFactory.getLogger(SynchronizedComponentManager.class);
private final ConcurrentMap<String, T> components = Maps.newConcurrentMap();
private final Map<String, ComponentFactory<T>> factories;
private final ComponentConfigurationResolver configResolver;
private final ComponentType<T> componentType;
@Default
@Inject(optional=true)
private ComponentFactory<T> defaultComponentFactory = null;
@Inject
public SynchronizedComponentManager(
ComponentType<T> type,
Map<String, ComponentFactory<T>> factories,
TypeConfigurationResolver config) {
this.factories = factories;
this.componentType = type;
this.configResolver = config.getConfigurationFactory(type.getType());
}
@Override
public synchronized T get(String id) throws ComponentCreationException, ComponentAlreadyExistsException {
Preconditions.checkNotNull(id, String.format("Component of type '%s' must have a id", componentType.getType()));
// Look for an existing component
T component = components.get(id);
if (component == null) {
// Get configuration context from default configuration
ConfigurationNode config = configResolver.getConfiguration(id);
if (config != null) {
// Create the object
component = getComponentFactory(config.getType()).create(config);
if (component == null) {
throw new ComponentCreationException(String.format("Error creating component of type '%s' with id '%s'", componentType.getType(), id));
}
addComponent(id, component);
}
else {
throw new ComponentCreationException(String.format("No config provided for component of type '%s' with id '%s'", componentType.getType(), id));
}
}
return component;
}
private void addComponent(String id, T component) throws ComponentCreationException{
try {
invokePostConstruct(component);
} catch (Exception e) {
throw new ComponentCreationException("Error creating component : " + id, e);
}
T oldComponent = components.put(id, component);
if (oldComponent != null) {
try {
invokePreDestroy(oldComponent);
} catch (Exception e) {
LOG.error("Error destroying component : " + id, e);
}
}
}
private static void fillAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annot, Map<String, Method> methods) {
if (clazz == null || clazz == Object.class) {
return;
}
for (Method method : clazz.getDeclaredMethods()) {
if (method.isSynthetic() || method.isBridge()) {
continue;
}
if (method.isAnnotationPresent(annot)) {
methods.putIfAbsent(method.getName(), method);
}
}
fillAnnotatedMethods(clazz.getSuperclass(), annot, methods);
for (Class<?> face : clazz.getInterfaces()) {
fillAnnotatedMethods(face, annot, methods);
}
}
private void invokePostConstruct(T component) throws Exception {
if (component == null)
return;
Map<String, Method> methods = new LinkedHashMap<>();
fillAnnotatedMethods(component.getClass(), PostConstruct.class, methods);
for (Method method : methods.values()) {
method.invoke(component, null);
}
}
private void invokePreDestroy(T component) throws Exception {
if (component == null)
return;
Map<String, Method> methods = new LinkedHashMap<>();
fillAnnotatedMethods(component.getClass(), PreDestroy.class, methods);
for (Method method : methods.values()) {
method.invoke(component, null);
}
}
private void removeComponent(String id, T component) throws Exception {
if (component == null)
return;
if (components.get(id) == component) {
components.remove(id);
invokePreDestroy(component);
}
}
@Override
public synchronized void add(String id, T component) throws ComponentAlreadyExistsException, ComponentCreationException {
Preconditions.checkNotNull(id, "Component must have a id");
Preconditions.checkNotNull(component, "Component cannot be null");
if (components.containsKey(id)) {
throw new ComponentAlreadyExistsException(id);
}
addComponent(id, component);
}
@Override
public synchronized Collection<String> getIds() {
return ImmutableSet.copyOf(components.keySet());
}
@Override
public synchronized T get(ConfigurationNode config) throws ComponentAlreadyExistsException, ComponentCreationException {
return load(config);
}
@Override
public synchronized T load(ConfigurationNode config) throws ComponentAlreadyExistsException, ComponentCreationException {
Preconditions.checkNotNull(config, "Configuration cannot be null");
Preconditions.checkNotNull(config.getId(), "Configuration must have an id");
if (config.getId() != null && components.containsKey(config.getId())) {
throw new ComponentAlreadyExistsException(config.getId());
}
T component = getComponentFactory(config.getType()).create(config);
if (component == null) {
throw new ComponentCreationException(String.format("Error creating component type '%s' with id '%s'", componentType.getType(), config.getId()));
}
addComponent(config.getId(), component);
return component;
}
@Override
public T create(ConfigurationNode config) throws ComponentCreationException, ComponentAlreadyExistsException {
T component = getComponentFactory(config.getType()).create(config);
if (component == null) {
throw new ComponentCreationException(String.format("Error creating component type '%s' with id '%s'", componentType.getType(), config.getId()));
}
try {
invokePostConstruct(component);
} catch (Exception e) {
throw new ComponentCreationException("Error creating component : " + config.getId(), e);
}
return component;
}
@Override
public synchronized void replace(String id, T component) throws ComponentAlreadyExistsException, ComponentCreationException {
Preconditions.checkNotNull(id, "Component must have a id");
Preconditions.checkNotNull(component, "Component cannot be null");
addComponent(id, component);
}
@Override
public synchronized void remove(String id) {
Preconditions.checkNotNull(id, "Component must have a id");
try {
removeComponent(id, components.get(id));
} catch (Exception e) {
LOG.error("Error shutting down component: " + id, e);
}
}
private ComponentFactory<T> getComponentFactory(String type) throws ComponentCreationException {
ComponentFactory<T> factory = null;
if (type != null) {
factory = factories.get(type);
}
if (factory == null) {
factory = defaultComponentFactory;
}
if (factory == null) {
throw new ComponentCreationException(
String.format("Failed to create component '%s'. Invalid implementation specified '%s'. Expecting one of '%s'.",
this.componentType.getType(), type, factories.keySet()));
}
return factory;
}
@Override
public synchronized void apply(Runnable operation) {
operation.run();
}
@Override
public synchronized T replace(ConfigurationNode config) throws ComponentCreationException {
Preconditions.checkNotNull(config, "Configuration cannot be null");
Preconditions.checkNotNull(config.getId(), "Configuration must have an id");
T component;
try {
component = getComponentFactory(config.getType()).create(config);
if (component == null) {
throw new ComponentCreationException(String.format("Error creating component type '%s' with id '%s'", componentType.getType(), config.getId()));
}
addComponent(config.getId(), component);
return component;
} catch (ComponentAlreadyExistsException e) {
// This can't really happen
throw new ComponentCreationException("Can't create component", e);
}
}
@Override
public synchronized T find(String id) {
return components.get(id);
}
@Override
public synchronized boolean contains(String id) {
return components.containsKey(id);
}
}
| 2,112 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/ComponentManager.java | package com.netflix.fabricator.component;
import java.util.Collection;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
/**
* The ComponentManager is meant to be the entry point into a subsystem
* that manages multiple instances of a component type, each having a
* unique ID. These can be database connections or persistent connections
* to an remote service. Specific implementations of ComponentManager
* will combine dependency injection with configuration mapping using
* any of many different configuration specifications such as .properties
* files, JSON blobs, key value pairs, YAML, etc.
*
* @author elandau
*
* @param <T>
*
* TODO: replace component
* TODO: getIfExists
*/
public interface ComponentManager<T> {
/**
* Get a component by 'id'. If the component does not exist one may be
* created from a previously specified configuration, such as a .properties
* file.
*
* @param id
* @return
* @throws ComponentCreationException
* @throws ComponentAlreadyExistsException
*/
public T get(String id) throws ComponentCreationException, ComponentAlreadyExistsException;
/**
* Find a existing component or return null if none exists
*
* @param id
* @return Existing component with matching id or null if none exists
*/
public T find(String id);
/**
* Return true if the manager contains a component with the specified id
* @param id
* @return True if exists or false otherwise
*/
public boolean contains(String id);
/**
* Get a component from a provided config that encapsulates a specific
* configuration such as an API requires containing JSON or property list
* payload. Once created the managed entity will be registered using
* the id provided in the config.
*
* @param config
* @return Newly created component or cached component if already exists
* @throws ComponentAlreadyExistsException
* @throws ComponentCreationException
*/
public T load(ConfigurationNode config) throws ComponentAlreadyExistsException, ComponentCreationException;
/**
* Create an un-id'd component
*
* @param config
* @return Newly created component
* @throws ComponentCreationException
* @throws ComponentAlreadyExistsException
*/
public T create(ConfigurationNode config) throws ComponentCreationException, ComponentAlreadyExistsException;
@Deprecated
public T get(ConfigurationNode config) throws ComponentAlreadyExistsException, ComponentCreationException;
/**
* Add an externally created entity with the specified id. Will throw
* an exception if the id is already registered.
* @param id
* @param component
* @throws ComponentAlreadyExistsException
* @throws ComponentCreationException
*/
public void add(String id, T component) throws ComponentAlreadyExistsException, ComponentCreationException;
/**
* Add an externally created entity with the specified id. Will replace
* an existing component if one with the same id already exists
* @param id
* @param component
* @throws ComponentAlreadyExistsException
* @throws ComponentCreationException
*/
public void replace(String id, T component) throws ComponentAlreadyExistsException, ComponentCreationException;
/**
* Load a component and replace the component specified by config.getId()
*
* @param config
* @throws ComponentCreationException
*/
public T replace(ConfigurationNode config) throws ComponentCreationException;
/**
* Apply the following function under a lock
* @param run
*/
public void apply(Runnable run);
/**
* @return Return a collection of all component ids
*/
public Collection<String> getIds();
/**
* Remove an element from the manager
* @param id
*/
public void remove(String id);
}
| 2,113 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/BaseComponentRefreshService.java | package com.netflix.fabricator.component;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.MapDifference.ValueDifference;
import com.netflix.fabricator.ComponentConfigurationResolver;
import com.netflix.fabricator.ComponentType;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.TypeConfigurationResolver;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
import com.netflix.governator.annotations.Configuration;
import com.netflix.governator.annotations.ConfigurationVariable;
import com.netflix.governator.annotations.binding.Background;
/**
* Service responsible for refreshing a predef
* @author elandau
*
*/
public class BaseComponentRefreshService<T> {
private static final Logger LOG = LoggerFactory.getLogger(BaseComponentRefreshService.class);
public final long DEFAULT_REFRESH_RATE = 60;
/**
* The manager for these components.
*/
private final ComponentManager<T> manager;
/**
* Executor for the refresh task
*/
private final ScheduledExecutorService executor;
/**
* Prefix based on the component type makes it possible to configure this for
* any component manager
*/
@ConfigurationVariable(name="prefix")
private final String componentName;
@Configuration(value="${prefix}.refresh.refreshRateInSeconds")
private long refreshRate = DEFAULT_REFRESH_RATE;
@Configuration(value="${prefix}.refresh.enabled")
private boolean enabled = false;
/**
* Future for refresh task
*/
private ScheduledFuture<?> refreshFuture;
/**
* Resolver for the core configuration for these components
*/
private final ComponentConfigurationResolver configResolver;
/**
* List of 'known' configurations. We keep this outside of what's in the ComponentManager
* so we can keep track of the raw configuration
*/
private Map<String, ConfigurationNode> configs = ImmutableMap.of();
@Inject
public BaseComponentRefreshService(
ComponentManager<T> manager,
ComponentType<T> type,
TypeConfigurationResolver config,
@Background ScheduledExecutorService executor) {
this.componentName = type.getType();
this.manager = manager;
this.executor = executor;
this.configResolver = config.getConfigurationFactory(type.getType());
}
@PostConstruct
public void init() {
if (enabled) {
LOG.info(String.format("Starting '%s' refresh task", componentName));
manager.apply(getUpdateTask());
this.refreshFuture = executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
manager.apply(getUpdateTask());
}
}, refreshRate, refreshRate, TimeUnit.SECONDS);
}
else {
LOG.info(String.format("'%s' refresh task diabled", componentName));
}
}
private Runnable getUpdateTask() {
return new Runnable() {
@Override
public void run() {
// Get a snapshot of the current configuration
Map<String, ConfigurationNode> newConfigs = configResolver.getAllConfigurations();
MapDifference<String, ConfigurationNode> diff = Maps.difference(newConfigs, configs);
// new configs
for (Entry<String, ConfigurationNode> entry : diff.entriesOnlyOnLeft().entrySet()) {
LOG.info("Adding config: " + entry.getKey() + " " + entry.getValue().toString());
try {
manager.load(entry.getValue());
} catch (ComponentAlreadyExistsException e) {
} catch (ComponentCreationException e) {
LOG.warn("Failed to create component " + entry.getKey(), e);
}
}
// removed configs
for (Entry<String, ConfigurationNode> entry : diff.entriesOnlyOnRight().entrySet()) {
LOG.info("Remove config: " + entry.getKey() + " " + entry.getValue().toString());
manager.remove(entry.getKey());
}
// modified configs
for (Entry<String, ValueDifference<ConfigurationNode>> entry : diff.entriesDiffering().entrySet()) {
LOG.info("Replace config: " + entry.getKey() + " " + entry.getValue().toString());
try {
manager.replace(entry.getValue().leftValue());
} catch (ComponentCreationException e) {
LOG.warn("Failed to create component " + entry.getKey(), e);
}
}
}
};
}
@PreDestroy
public void shutdown() {
if (refreshFuture != null) {
refreshFuture.cancel(true);
}
}
}
| 2,114 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/StringBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class StringBinderFactory implements PropertyBinderFactory {
private final static StringBinderFactory instance = new StringBinderFactory();
public static StringBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(String.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Object value = node.getValue(String.class);
if (value != null) {
method.invoke(obj, value);
return true;
}
else {
return false;
}
}
public String toString() {
return "StringBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,115 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/DynamicDoubleBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import com.google.common.base.Supplier;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
import com.netflix.fabricator.supplier.ListenableSupplier;
public class DynamicDoubleBinderFactory implements PropertyBinderFactory {
private final static DynamicDoubleBinderFactory instance = new DynamicDoubleBinderFactory();
public static DynamicDoubleBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Supplier.class) && !clazz.isAssignableFrom(ListenableSupplier.class)) {
return null;
}
ParameterizedType supplierType = (ParameterizedType)method.getGenericParameterTypes()[0];
final Class<?> argType = (Class<?>)supplierType.getActualTypeArguments()[0];
if (!argType.isAssignableFrom(Double.class) &&
!argType.equals(double.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Supplier<?> supplier = node.getDynamicValue(Double.class);
if (supplier != null) {
//invoke method only when property exists. Otherwise, let builder
//plug-in default values
if (supplier.get() != null) {
method.invoke(obj, supplier);
}
return true;
}
else {
//Shouldn't happen
return false;
}
}
public String toString() {
return "DynamicDoubleBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,116 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/ClassBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class ClassBinderFactory implements PropertyBinderFactory {
private final static ClassBinderFactory instance = new ClassBinderFactory();
public static ClassBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.equals(Class.class))
return null;
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
String value = node.getValue(String.class);
if (value != null) {
method.invoke(obj, Class.forName(value));
return true;
}
else {
return false;
}
}
public String toString() {
return "ClassBinderFactory["+ propertyName + "]";
}
};
}
} | 2,117 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/SimplePropertyBinderFactoryResolver.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.CaseFormat;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.netflix.fabricator.InjectionSpi;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
import com.netflix.fabricator.PropertyBinderResolver;
public class SimplePropertyBinderFactoryResolver implements PropertyBinderResolver {
private static final Logger LOG = LoggerFactory.getLogger(SimplePropertyBinderFactoryResolver.class);
private static final String WITH_METHOD_PREFIX = "with";
private static final String SET_METHOD_PREFIX = "set";
private static final List<PropertyBinderFactory> DEFAULT_PROPERTY_FACTORIES = Lists.newArrayList(
StringBinderFactory.get(),
LongBinderFactory.get(),
DoubleBinderFactory.get(),
BooleanBinderFactory.get(),
IntegerBinderFactory.get(),
EnumBinderFactory.get(),
ClassBinderFactory.get(),
DynamicStringBinderFactory.get(),
DynamicLongBinderFactory.get(),
DynamicDoubleBinderFactory.get(),
DynamicBooleanBinderFactory.get(),
DynamicIntegerBinderFactory.get(),
PropertiesBinderFactory.get()
);
private final List<PropertyBinderFactory> propertyBinders;
private final InjectionSpi injector;
public SimplePropertyBinderFactoryResolver(List<PropertyBinderFactory> propertyBinders, InjectionSpi injector) {
if (propertyBinders != null)
this.propertyBinders = Lists.newArrayList(propertyBinders);
else
this.propertyBinders = Lists.newArrayList();
this.propertyBinders.addAll(DEFAULT_PROPERTY_FACTORIES);
this.injector = injector;
}
public SimplePropertyBinderFactoryResolver() {
this(null, null);
}
@Override
public PropertyBinder get(Method method) {
// Skip methods that do real DI. These will have been injected at object creation
if (hasInjectAnnotation(method)) {
return null;
}
// Deduce property name from the method
final String propertyName = getPropertyName(method);
if (propertyName == null) {
return null;
}
// Only support methods with a single parameter.
// TODO: Might want to support methods that take TimeUnit
Class<?>[] types = method.getParameterTypes();
if (types.length != 1) {
return null;
}
// Primitive or String will be handled as configuration binding
final Class<?> argType = types[0];
for (PropertyBinderFactory factory : propertyBinders) {
PropertyBinder binder = factory.createBinder(method, propertyName);
if (binder != null) {
return binder;
}
}
return injector.createInjectableProperty(propertyName, argType, method);
}
private static boolean hasInjectAnnotation(Method method) {
return method.isAnnotationPresent(Inject.class) ||
method.isAnnotationPresent(javax.inject.Inject.class);
}
private static String getPropertyName(Method method) {
if (method.getName().startsWith(WITH_METHOD_PREFIX)) {
return CaseFormat.UPPER_CAMEL.to(
CaseFormat.LOWER_CAMEL,
StringUtils.substringAfter(method.getName(), WITH_METHOD_PREFIX));
}
if (method.getName().startsWith(SET_METHOD_PREFIX)) {
return CaseFormat.UPPER_CAMEL.to(
CaseFormat.LOWER_CAMEL,
StringUtils.substringAfter(method.getName(), SET_METHOD_PREFIX));
}
return null;
}
}
| 2,118 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/EnumBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class EnumBinderFactory implements PropertyBinderFactory {
private final static EnumBinderFactory instance = new EnumBinderFactory();
public static EnumBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isEnum()) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
String value = node.getValue(String.class);
if (value != null) {
method.invoke(obj, Enum.valueOf((Class<Enum>)method.getParameterTypes()[0], value));
return true;
}
else {
return false;
}
}
public String toString() {
return "EnumBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,119 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/DynamicIntegerBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import com.google.common.base.Supplier;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
import com.netflix.fabricator.supplier.ListenableSupplier;
public class DynamicIntegerBinderFactory implements PropertyBinderFactory {
private final static DynamicIntegerBinderFactory instance = new DynamicIntegerBinderFactory();
public static DynamicIntegerBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Supplier.class) && !clazz.isAssignableFrom(ListenableSupplier.class)) {
return null;
}
ParameterizedType supplierType = (ParameterizedType)method.getGenericParameterTypes()[0];
final Class<?> argType = (Class<?>)supplierType.getActualTypeArguments()[0];
if (!argType.isAssignableFrom(Integer.class) &&
!argType.equals(int.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Supplier<?> supplier = node.getDynamicValue(Integer.class);
if (supplier != null) {
//invoke method only when property exists. Otherwise, let builder
//plug-in default values
if (supplier.get() != null) {
method.invoke(obj, supplier);
}
return true;
}
else {
//Shouldn't happen
return false;
}
}
public String toString() {
return "DynamicIntegerBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,120 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/DynamicBooleanBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import com.google.common.base.Supplier;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
import com.netflix.fabricator.supplier.ListenableSupplier;
public class DynamicBooleanBinderFactory implements PropertyBinderFactory {
private final static DynamicBooleanBinderFactory instance = new DynamicBooleanBinderFactory();
public static DynamicBooleanBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Supplier.class) && !clazz.isAssignableFrom(ListenableSupplier.class)) {
return null;
}
ParameterizedType supplierType = (ParameterizedType)method.getGenericParameterTypes()[0];
final Class<?> argType = (Class<?>)supplierType.getActualTypeArguments()[0];
if (!argType.isAssignableFrom(Boolean.class) &&
!argType.equals(boolean.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Supplier<?> supplier = node.getDynamicValue(Boolean.class);
if (supplier != null) {
//invoke method only when property exists. Otherwise, let builder
//plug-in default values
if (supplier.get() != null) {
method.invoke(obj, supplier);
}
return true;
}
else {
//Shouldn't happen
return false;
}
}
public String toString() {
return "DynamicBooleanBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,121 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/PropertiesBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import java.util.Properties;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class PropertiesBinderFactory implements PropertyBinderFactory {
private final static PropertiesBinderFactory instance = new PropertiesBinderFactory();
public static PropertiesBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Properties.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Properties props = node.getValue(Properties.class);
if (props != null) {
method.invoke(obj, props);
return true;
}
else {
return false;
}
}
public String toString() {
return "PropertiesBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,122 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/DynamicLongBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import com.google.common.base.Supplier;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
import com.netflix.fabricator.supplier.ListenableSupplier;
public class DynamicLongBinderFactory implements PropertyBinderFactory {
private final static DynamicLongBinderFactory instance = new DynamicLongBinderFactory();
public static DynamicLongBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Supplier.class) && !clazz.isAssignableFrom(ListenableSupplier.class)) {
return null;
}
ParameterizedType supplierType = (ParameterizedType)method.getGenericParameterTypes()[0];
final Class<?> argType = (Class<?>)supplierType.getActualTypeArguments()[0];
if (!argType.isAssignableFrom(Long.class) &&
!argType.equals(long.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Supplier<?> supplier = node.getDynamicValue(Long.class);
if (supplier != null) {
//invoke method only when property exists. Otherwise, let builder
//plug-in default values
if (supplier.get() != null) {
method.invoke(obj, supplier);
}
return true;
}
else {
//Shouldn't happen
return false;
}
}
public String toString() {
return "DynamicLongBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,123 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/LongBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class LongBinderFactory implements PropertyBinderFactory {
private final static LongBinderFactory instance = new LongBinderFactory();
public static LongBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Long.class) &&
!clazz.equals(long.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Object value = node.getValue(Long.class);
if (value != null) {
method.invoke(obj, value);
return true;
}
else {
return false;
}
}
public String toString() {
return "LongBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,124 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/BooleanBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class BooleanBinderFactory implements PropertyBinderFactory {
private final static BooleanBinderFactory instance = new BooleanBinderFactory();
public static BooleanBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Boolean.class) &&
!clazz.equals(boolean.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Object value = node.getValue(Boolean.class);
if (value != null) {
method.invoke(obj, value);
return true;
}
else {
return false;
}
}
public String toString() {
return "BooleanBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,125 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/DynamicStringBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import com.google.common.base.Supplier;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
import com.netflix.fabricator.supplier.ListenableSupplier;
public class DynamicStringBinderFactory implements PropertyBinderFactory {
private final static DynamicStringBinderFactory instance = new DynamicStringBinderFactory();
public static DynamicStringBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Supplier.class) && !clazz.isAssignableFrom(ListenableSupplier.class)) {
return null;
}
ParameterizedType supplierType = (ParameterizedType)method.getGenericParameterTypes()[0];
final Class<?> argType = (Class<?>)supplierType.getActualTypeArguments()[0];
if (!argType.isAssignableFrom(String.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Supplier<?> supplier = node.getDynamicValue(String.class);
if (supplier != null) {
//invoke method only when property exists. Otherwise, let builder
//plug-in default values
if (supplier.get() != null) {
method.invoke(obj, supplier);
}
return true;
}
else {
//Shouldn't happen
return false;
}
}
public String toString() {
return "DynamicStringBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,126 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/DoubleBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class DoubleBinderFactory implements PropertyBinderFactory {
private final static DoubleBinderFactory instance = new DoubleBinderFactory();
public static DoubleBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Double.class) &&
!clazz.equals(double.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Object value = node.getValue(Double.class);
if (value != null) {
method.invoke(obj, value);
return true;
}
else {
return false;
}
}
public String toString() {
return "DoubleBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,127 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/bind/IntegerBinderFactory.java | package com.netflix.fabricator.component.bind;
import java.lang.reflect.Method;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderFactory;
public class IntegerBinderFactory implements PropertyBinderFactory {
private final static IntegerBinderFactory instance = new IntegerBinderFactory();
public static IntegerBinderFactory get() {
return instance;
}
@Override
public PropertyBinder createBinder(final Method method, final String propertyName) {
final Class<?>[] types = method.getParameterTypes();
final Class<?> clazz = types[0];
if (!clazz.isAssignableFrom(Integer.class) &&
!clazz.equals(int.class)) {
return null;
}
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
Object value = node.getValue(Integer.class);
if (value != null) {
method.invoke(obj, value);
return true;
}
else {
return false;
}
}
public String toString() {
return "IntegerBinderFactory["+ propertyName + "]";
}
};
}
}
| 2,128 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/exception/ComponentNotFoundException.java | package com.netflix.fabricator.component.exception;
public class ComponentNotFoundException extends Exception {
private static final long serialVersionUID = 5358538299200779367L;
public ComponentNotFoundException(String message, Throwable t) {
super(message, t);
}
}
| 2,129 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/exception/ComponentCreationException.java | package com.netflix.fabricator.component.exception;
public class ComponentCreationException extends Exception {
private static final long serialVersionUID = 7847902103334820478L;
public ComponentCreationException(String message) {
super(message);
}
public ComponentCreationException(String message, Throwable t) {
super(message, t);
}
}
| 2,130 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/component/exception/ComponentAlreadyExistsException.java | package com.netflix.fabricator.component.exception;
public class ComponentAlreadyExistsException extends Exception {
private static final long serialVersionUID = -5928460848593945925L;
public ComponentAlreadyExistsException(String message) {
super(message);
}
}
| 2,131 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/annotations/Default.java | package com.netflix.fabricator.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation;
@BindingAnnotation
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Default
{
}
| 2,132 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/annotations/Type.java | package com.netflix.fabricator.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation specifying an interface type and it's type name in configuration files
*
* @author elandau
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Type {
String value();
}
| 2,133 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/annotations/TypeImplementation.java | package com.netflix.fabricator.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation specifying a specific subtype.
* This is the value used to determine which instance to allocate in
* a configuration of polymorphic components.
*
*
* @author elandau
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TypeImplementation {
String value();
}
| 2,134 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/properties/PropertiesTypeConfigurationResolver.java | package com.netflix.fabricator.properties;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.netflix.fabricator.ComponentConfigurationResolver;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.TypeConfigurationResolver;
import com.netflix.fabricator.jackson.JacksonComponentConfiguration;
/**
* TypeConfiguration resolver following the convention of ${id}.${type}. to determine
* the root configuration context for a component
*
* @author elandau
*
*/
public class PropertiesTypeConfigurationResolver implements TypeConfigurationResolver {
private static String DEFAULT_FORMAT_STRING = "%s.%s";
// TOOD: Feature to provide a different field from which to determine the type
// TODO: Feature to provide entirely custom logic to determine the type
private static String TYPE_FIELD = "type";
/**
* Map of type to ComponentConfigurationResolver overrides in the event that the
* naming convention used in this class is not adequate
*/
private final Map<String, ComponentConfigurationResolver> overrides;
/**
* Properties object containing ALL configuration properties for all components
* of varying types
*/
private final Properties properties;
private final ObjectMapper mapper = new ObjectMapper();
@Inject
public PropertiesTypeConfigurationResolver(Properties properties, Map<String, ComponentConfigurationResolver> overrides) {
if (overrides == null) {
overrides = Maps.newHashMap();
}
this.overrides = overrides;
this.properties = properties;
}
@Override
public ComponentConfigurationResolver getConfigurationFactory(final String componentType) {
// Look for overrides
ComponentConfigurationResolver factory = overrides.get(componentType);
if (factory != null)
return factory;
return new ComponentConfigurationResolver() {
@Override
public ConfigurationNode getConfiguration(final String key) {
String prefix = String.format(DEFAULT_FORMAT_STRING, key, componentType);
if (properties.containsKey(prefix)) {
String json = properties.getProperty(prefix).trim();
if (!json.isEmpty() && json.startsWith("{") && json.endsWith("}")) {
try {
JsonNode node = mapper.readTree(json);
if (node.get(TYPE_FIELD) == null)
throw new Exception("Missing 'type' field");
return new JacksonComponentConfiguration(key, node.get(TYPE_FIELD).asText(), node);
} catch (Exception e) {
throw new RuntimeException(
String.format("Unable to parse json from '%s'. (%s)",
prefix,
StringUtils.abbreviate(json, 256)),
e);
}
}
}
String typeField = Joiner.on(".").join(prefix, TYPE_FIELD);
String typeValue = properties.getProperty(typeField);
if (componentType == null) {
throw new RuntimeException(String.format("Type for '%s' not specified '%s'", typeField, componentType));
}
return new PropertiesComponentConfiguration(
key,
typeValue,
properties,
prefix);
}
@Override
public Map<String, ConfigurationNode> getAllConfigurations() {
Map<String, ConfigurationNode> configs = Maps.newHashMap();
for (Object key : properties.keySet()) {
String[] parts = StringUtils.split(key.toString(), ".");
if (parts.length > 1) {
String type = parts[1];
if (type.equals(componentType)) {
String id = parts[0];
if (!configs.containsKey(id)) {
configs.put(id, getConfiguration(id));
}
}
}
}
return configs;
}
};
}
}
| 2,135 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/properties/AbstractPropertiesComponentConfiguration.java | package com.netflix.fabricator.properties;
import com.netflix.fabricator.ConfigurationNode;
/**
* Base source for 'properties' driven configuration where each 'child'
* is namespaced by a property prefix
*
* @author elandau
*
*/
public abstract class AbstractPropertiesComponentConfiguration implements ConfigurationNode {
/**
* This is the property/field name
*/
private final String id;
/**
* Element type stored in this property.
*
* TODO: may considering moving this out
*/
private final String type;
/**
* This is the full property name with prefix
*/
private final String fullName;
public AbstractPropertiesComponentConfiguration(String id, String type) {
this.id = id;
this.type = type;
this.fullName = "";
}
public AbstractPropertiesComponentConfiguration(String id, String type, String fullName) {
this.id = id;
this.type = type;
this.fullName = fullName;
}
@Override
public String getId() {
return id;
}
@Override
public String getType() {
return type;
}
public String getFullName() {
return this.fullName;
}
}
| 2,136 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/properties/PropertiesComponentConfiguration.java | package com.netflix.fabricator.properties;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Supplier;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.supplier.ListenableSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Properties;
import java.util.Set;
public class PropertiesComponentConfiguration extends AbstractPropertiesComponentConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(PropertiesComponentConfiguration.class);
private final Properties props;
public PropertiesComponentConfiguration(String id, String type, Properties props, String fullName) {
super(id, type, fullName);
this.props = props;
}
public PropertiesComponentConfiguration(String id, String type, Properties props) {
super(id, type);
this.props = props;
}
public static abstract class StaticListenableSupplier<T> implements ListenableSupplier<T> {
StaticListenableSupplier() {
}
@Override
public void onChange(Function<T, Void> func) {
// noop
}
}
@SuppressWarnings("unchecked")
@Override
public <T> ListenableSupplier<T> getDynamicValue(Class<T> type) {
if ( String.class.isAssignableFrom(type) ) {
return (ListenableSupplier<T>) new StaticListenableSupplier<String>() {
@Override
public String get() {
final String value = props.getProperty(getFullName());
if (value == null)
return null;
return value;
}
};
}
else if ( Boolean.class.isAssignableFrom(type)
|| Boolean.TYPE.isAssignableFrom(type)
|| boolean.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Boolean>() {
@Override
public Boolean get() {
final String value = props.getProperty(getFullName());
if (value == null)
return null;
return Boolean.valueOf(value);
}
};
}
else if ( Integer.class.isAssignableFrom(type)
|| Integer.TYPE.isAssignableFrom(type)
|| int.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Integer>() {
@Override
public Integer get() {
final String value = props.getProperty(getFullName());
if (value == null)
return null;
return Integer.valueOf(value);
}
};
}
else if ( Long.class.isAssignableFrom(type)
|| Long.TYPE.isAssignableFrom(type)
|| long.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Long>() {
@Override
public Long get() {
final String value = props.getProperty(getFullName());
if (value == null)
return null;
return Long.valueOf(value);
}
};
}
else if ( Double.class.isAssignableFrom(type)
|| Double.TYPE.isAssignableFrom(type)
|| double.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Double>() {
@Override
public Double get() {
final String value = props.getProperty(getFullName());
if (value == null)
return null;
return Double.valueOf(value);
}
};
}
else if ( Properties.class.isAssignableFrom(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Properties>() {
@Override
public Properties get() {
if (props.containsKey(getFullName())) {
throw new RuntimeException(getFullName() + " is not a root for a properties structure");
}
String prefix = getFullName() + ".";
Properties result = new Properties();
for (String prop : props.stringPropertyNames()) {
if (prop.startsWith(prefix)) {
result.setProperty(prop.substring(prefix.length()), props.getProperty(prop));
}
}
return result;
}
};
}
else {
LOG.warn(String.format("Unknown type '%s' for property '%s'", type.getCanonicalName(), getFullName()));
return null;
}
}
@Override
public ConfigurationNode getChild(String name) {
String fullName = Joiner.on(".").skipNulls().join(getFullName(), name);
return new PropertiesComponentConfiguration(
name,
props.getProperty(Joiner.on(".").join(fullName, "type")), // TODO: Make 'type' configurable
props,
fullName);
}
@Override
public boolean isSingle() {
return props.containsKey(getFullName());
}
@Override
public boolean hasChild(String propertyName) {
return props.containsKey(Joiner.on(".").skipNulls().join(getFullName(), propertyName));
}
@Override
public Set<String> getUnknownProperties(Set<String> supportedProperties) {
return Collections.emptySet();
}
@Override
public <T> T getValue(Class<T> type) {
Supplier<T> supplier = this.getDynamicValue(type);
if (supplier != null)
return supplier.get();
return null;
}
@Override
public String toString() {
return new StringBuilder()
.append("PropertiesComponentConfiguration[")
.append("id=").append(getId())
.append(",type=").append(getType())
.append(",full=").append(getFullName())
.append(",props=").append(props)
.append("]")
.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((props == null) ? 0 : props.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PropertiesComponentConfiguration other = (PropertiesComponentConfiguration) obj;
if (props == null) {
if (other.props != null)
return false;
} else if (!props.equals(other.props))
return false;
return true;
}
}
| 2,137 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/properties/PropertiesConfigurationModule.java | package com.netflix.fabricator.properties;
import java.util.Properties;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.MapBinder;
import com.netflix.fabricator.ComponentConfigurationResolver;
import com.netflix.fabricator.TypeConfigurationResolver;
public class PropertiesConfigurationModule extends AbstractModule {
private final Properties props;
public PropertiesConfigurationModule(Properties props) {
this.props = props;
}
@Override
protected void configure() {
bind(Properties.class).toInstance(props);
MapBinder.newMapBinder(binder(), String.class, ComponentConfigurationResolver.class);
bind(TypeConfigurationResolver.class).to(PropertiesTypeConfigurationResolver.class);
}
}
| 2,138 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/supplier/SupplierWithDefault.java | package com.netflix.fabricator.supplier;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.netflix.fabricator.supplier.ListenableSupplier;
/**
* Implementation of a ListenableSupplier that gets it's value from an optional
* ListenableSupplier but returns a default value if the source returns {$code null}.
*
* <pre> {@code
public class Service {
public class Builder {
// Define a SupplierWithDefault in your code.
private final SupplierWithDefault<String> param1 = SupplierWithDefault.from("DefaultValue");
// Assign an optional 'source'. This will be called by a Mapper that supports dynamic
// values (@see ArchaiusConfigurationProviderMapper).
public Builder withParam1(ListenableSupplier<String> source) {
param1.setSource(source);
return this;
}
public Service build() {
return new Service(this);
}
}
// The service's reference to the supplier
private final ListenableSupplier<String> param1;
protected Service(Builder builder) {
this.param1 = builder.param1;
// Set an optional callback notification for when the value changes
param1.onChange(new Function<String, Void>() {
public Void apply(String newValue) {
System.out.println("Got a new value for newValue");
}
});
}
}} </pre>
* @author elandau
*
* @param <T>
*/
public class SupplierWithDefault<T> implements ListenableSupplier<T> {
private final T defaultValue;
private ListenableSupplier<T> source;
public SupplierWithDefault(T defaultValue) {
this.defaultValue = defaultValue;
this.source = new ListenableSupplier<T>() {
@Override
public T get() {
return SupplierWithDefault.this.defaultValue;
}
@Override
public void onChange(Function<T, Void> func) {
// throw new RuntimeException("Change notification not supported");
}
};
}
public static <T> SupplierWithDefault<T> from(T defaultValue) {
return new SupplierWithDefault<T>(defaultValue);
}
@Override
public T get() {
T value = source.get();
if (value == null) {
return defaultValue;
}
return value;
}
/**
* Set the ListenableSupplier from which the value will be read and a notification
* can be subscribed to.
* @param supplier
*/
public void setSource(ListenableSupplier<T> supplier) {
source = supplier;
}
/**
* Set a 'fixed' value to be returned.
* @param value
*/
public void setValue(T value) {
addOverride(Suppliers.ofInstance(value));
}
/**
* Set the onChange callback on the source. Note that the function reference is lost
* if source is changed
*/
public void onChange(Function<T, Void> func) {
source.onChange(func);
}
/**
* Assign a simple Supplier that does not provide change notification
* This will result in an exception being thrown if the client code tries to listen
* for changes
* @param supplier
*/
public void addOverride(final Supplier<T> supplier) {
source = new ListenableSupplier<T>() {
@Override
public T get() {
return supplier.get();
}
@Override
public void onChange(Function<T, Void> func) {
throw new RuntimeException("Change notification not supported");
}
};
}
}
| 2,139 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/supplier/ListenableSupplier.java | package com.netflix.fabricator.supplier;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
/**
* Extension to the supplier interface to allow for a notification
* callback whenever the value changes. Note that the function
* may be called in response to get() or from an underlying update
* mechanism.
*
* @author elandau
*
* @param <T>
*/
public interface ListenableSupplier<T> extends Supplier<T> {
public void onChange(Function<T, Void> func);
}
| 2,140 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/doc/OutputStreamConfigDocumenter.java | package com.netflix.fabricator.doc;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import com.google.inject.Binding;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Singleton;
import com.google.inject.multibindings.MapBinderBinding;
import com.google.inject.multibindings.MultibinderBinding;
import com.google.inject.multibindings.MultibindingsTargetVisitor;
import com.google.inject.multibindings.OptionalBinderBinding;
import com.google.inject.spi.DefaultBindingTargetVisitor;
import com.netflix.fabricator.PropertyInfo;
import com.netflix.fabricator.component.ComponentFactory;
@Singleton
public class OutputStreamConfigDocumenter {
private final Injector injector;
@Inject
public OutputStreamConfigDocumenter(Injector injector) {
this.injector = injector;
}
public static class Visitor
extends DefaultBindingTargetVisitor<Object, MapBinderBinding<?>>
implements MultibindingsTargetVisitor<Object, MapBinderBinding<?>> {
@Override
public MapBinderBinding<?> visit(
MultibinderBinding<? extends Object> multibinding) {
// TODO Auto-generated method stub
return null;
}
@Override
public MapBinderBinding<?> visit(
MapBinderBinding<? extends Object> mapBinder) {
if (mapBinder.getValueTypeLiteral().getRawType().isAssignableFrom(ComponentFactory.class)) {
System.out.println(mapBinder.getValueTypeLiteral());
for (Entry<?, Binding<?>> entry : mapBinder.getEntries()) {
ComponentFactory<?> factory = (ComponentFactory<?>) entry.getValue().getProvider().get();
System.out.println(String.format(" for type='%s' use class '%s' with properties: ", entry.getKey(), factory.getRawType().getSimpleName()));
for (Entry<String, PropertyInfo> propEntry : factory.getProperties().entrySet()) {
PropertyInfo prop = propEntry.getValue();
String name = propEntry.getKey();
// System.out.println(String.format(" %-20s %-10s %-10s", name, prop.getType().getSimpleName(), prop.isDynamic() ? "(dynamic)" : ""));
}
}
}
return mapBinder;
}
@Override
public MapBinderBinding<?> visit(
OptionalBinderBinding<? extends Object> optionalbinding) {
// TODO Auto-generated method stub
return null;
}
}
@PostConstruct
public void init() {
for (Entry<Key<?>, Binding<?>> entry : this.injector.getAllBindings().entrySet()) {
Key<?> key = entry.getKey();
Binding<?> binding = entry.getValue();
binding.acceptTargetVisitor(new Visitor());
}
}
}
| 2,141 |
0 | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/jackson/JacksonComponentConfiguration.java | package com.netflix.fabricator.jackson;
import java.util.Properties;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.supplier.ListenableSupplier;
public class JacksonComponentConfiguration implements ConfigurationNode {
private static Logger LOG = LoggerFactory.getLogger(JacksonComponentConfiguration.class);
public static abstract class StaticListenableSupplier<T> implements ListenableSupplier<T> {
StaticListenableSupplier() {
}
@Override
public void onChange(Function<T, Void> func) {
throw new IllegalStateException("Change notification not supported");
}
}
private final String id;
private final String type;
private final JsonNode node;
public JacksonComponentConfiguration(String id, String type, JsonNode node) {
super();
this.id = id;
if (type == null && node.has("type")) {
this.type = node.get("type").asText();
}
else {
this.type = type;
}
this.node = node;
}
@Override
public String getId() {
return id;
}
@Override
public String getType() {
return type;
}
@Override
public ConfigurationNode getChild(String name) {
JsonNode child = node.get(name);
if (child == null)
return null;
return new JacksonComponentConfiguration(name, null, child);
}
@Override
public boolean isSingle() {
Preconditions.checkNotNull(node, String.format("Node for '%s' is null", id));
return !node.isObject() && !node.isArray();
}
@Override
public boolean hasChild(String propertyName) {
return node.get(propertyName) != null;
}
@Override
public Set<String> getUnknownProperties(Set<String> supportedProperties) {
return null;
}
@Override
public <T> T getValue(Class<T> type) {
Supplier<T> supplier = this.getDynamicValue(type);
if (supplier != null)
return supplier.get();
return null;
}
@SuppressWarnings("unchecked")
@Override
public <T> ListenableSupplier<T> getDynamicValue(Class<T> type) {
if (node != null) {
if ( String.class.isAssignableFrom(type) ) {
return (ListenableSupplier<T>) new StaticListenableSupplier<String>() {
@Override
public String get() {
return node.asText();
}
};
}
else if ( Boolean.class.isAssignableFrom(type)
|| Boolean.TYPE.isAssignableFrom(type)
|| boolean.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Boolean>() {
@Override
public Boolean get() {
return node.asBoolean();
}
};
}
else if ( Integer.class.isAssignableFrom(type)
|| Integer.TYPE.isAssignableFrom(type)
|| int.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Integer>() {
@Override
public Integer get() {
return node.asInt();
}
};
}
else if ( Long.class.isAssignableFrom(type)
|| Long.TYPE.isAssignableFrom(type)
|| long.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Long>() {
@Override
public Long get() {
return node.asLong();
}
};
}
else if ( Double.class.isAssignableFrom(type)
|| Double.TYPE.isAssignableFrom(type)
|| double.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Double>() {
@Override
public Double get() {
return node.asDouble();
}
};
}
else if ( Properties.class.isAssignableFrom(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Properties>() {
@Override
public Properties get() {
Properties result = new Properties();
for (String prop : Lists.newArrayList(node.fieldNames())) {
result.setProperty(prop, node.get(prop).asText());
}
return result;
}
};
}
}
LOG.warn(String.format("Unknown type '%s' for property '%s'", type.getCanonicalName(), getId()));
return null;
}
@Override
public String toString() {
return "JacksonComponentConfiguration [id=" + id + ", type=" + type
+ ", node=" + node + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((node == null) ? 0 : node.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JacksonComponentConfiguration other = (JacksonComponentConfiguration) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (node == null) {
if (other.node != null)
return false;
} else if (!node.equals(other.node))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 2,142 |
0 | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator/component/TestBindings.java | package com.netflix.fabricator.component;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.netflix.fabricator.annotations.Type;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
import com.netflix.fabricator.guice.ComponentModuleBuilder;
import com.netflix.fabricator.properties.PropertiesConfigurationModule;
public class TestBindings {
@Type("somecomponent")
public static class SomeComponent {
public static class Builder {
private Class<?> clazz = null;
public void withClazz(Class<?> clazz) {
this.clazz = clazz;
}
public SomeComponent build() {
return new SomeComponent(this);
}
}
private final Class<?> clazz;
public static Builder builder() {
return new Builder();
}
private SomeComponent(Builder builder) {
this.clazz = builder.clazz;
}
public Class<?> getClazz() {
return clazz;
}
}
@Test
public void test() throws ComponentCreationException, ComponentAlreadyExistsException {
Properties props = new Properties();
props.setProperty("id1.somecomponent.clazz", "java.lang.String");
Injector injector = Guice.createInjector(
new PropertiesConfigurationModule(props),
new ComponentModuleBuilder<SomeComponent>()
.manager(SynchronizedComponentManager.class)
.build(SomeComponent.class)
);
ComponentManager<SomeComponent> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeComponent>>() {}));
SomeComponent component = manager.get("id1");
Assert.assertEquals(String.class, component.getClazz());
}
}
| 2,143 |
0 | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator/component/TestLifecycle.java | package com.netflix.fabricator.component;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
import com.netflix.fabricator.guice.ComponentModuleBuilder;
import com.netflix.fabricator.properties.PropertiesConfigurationModule;
public class TestLifecycle {
@Test
public void test() throws ComponentCreationException, ComponentAlreadyExistsException {
Properties props = new Properties();
props.setProperty("id1.simple.clazz", "java.lang.String");
Injector injector = Guice.createInjector(
new PropertiesConfigurationModule(props),
new ComponentModuleBuilder<SimpleComponent>()
.manager(SynchronizedComponentManager.class)
.build(SimpleComponent.class)
);
ComponentManager<SimpleComponent> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SimpleComponent>>() {}));
SimpleComponent component = manager.get("id1");
Assert.assertTrue(component.wasPostConstructCalled());
manager.remove("id1");
Assert.assertTrue(component.wasPreDestroyCalled());
}
}
| 2,144 |
0 | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator/component/NoImplementationTest.java | package com.netflix.fabricator.component;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.netflix.fabricator.annotations.Type;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
import com.netflix.fabricator.guice.ComponentModuleBuilder;
import com.netflix.fabricator.properties.PropertiesConfigurationModule;
public class NoImplementationTest {
@Type("somecomponent")
public static class SomeComponent {
public static class Builder {
private int value = 0;
public void withProperty(int value) {
this.value = value;
}
public SomeComponent build() {
return new SomeComponent(this);
}
}
private final int value;
public static Builder builder() {
return new Builder();
}
private SomeComponent(Builder builder) {
this.value = builder.value;
}
public int getProperty() {
return value;
}
}
@Test
public void test() throws ComponentCreationException, ComponentAlreadyExistsException {
Properties props = new Properties();
props.setProperty("id1.NIWS.property", "123");
Injector injector = Guice.createInjector(
new PropertiesConfigurationModule(props),
new ComponentModuleBuilder<SomeComponent>()
.manager(SynchronizedComponentManager.class)
.typename("NIWS")
.build(SomeComponent.class)
);
ComponentManager<SomeComponent> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeComponent>>() {}));
SomeComponent component = manager.get("id1");
Assert.assertEquals(123, component.getProperty());
}
}
| 2,145 |
0 | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator/component/SimpleComponent.java | package com.netflix.fabricator.component;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import com.netflix.fabricator.annotations.Type;
@Type("simple")
public class SimpleComponent {
public static class Builder {
private String str = null;
private Class<?> cls = null;
private Integer i = null;
private Boolean b = null;
private Double d = null;
private Short shrt = null;
private Properties props = null;
public Builder withString(String str) {
this.str = str;
return this;
}
public Builder withInteger(Integer i) {
this.i = i;
return this;
}
public Builder withClass(Class<?> cs) {
this.cls = cls;
return this;
}
public Builder withBoolean(boolean b) {
this.b = b;
return this;
}
public Builder withDouble(double d) {
this.d = d;
return this;
}
// public Builder withShort(short shrt) {
// this.shrt = shrt;
// return this;
// }
public Builder withProperties(Properties props) {
this.props = props;
return this;
}
public SimpleComponent build() {
return new SimpleComponent(this);
}
}
private final Builder builder;
public static Builder builder() {
return new Builder();
}
private SimpleComponent(Builder builder) {
this.builder = builder;
}
public String getString() {
return builder.str;
}
public Boolean hasString() {
return builder.str != null;
}
public Integer getInteger() {
return builder.i;
}
public Boolean hasInteger() {
return builder.i != null;
}
public Short getShort() {
return builder.shrt;
}
public Boolean hasShort() {
return builder.shrt != null;
}
public Double getDouble() {
return builder.d;
}
public Boolean hasDouble() {
return builder.d != null;
}
public Boolean getBoolean() {
return builder.b;
}
public Boolean hasBoolean() {
return builder.b != null;
}
public Class _getClass() {
return builder.cls;
}
public Boolean hasClass() {
return builder.cls != null;
}
public Properties getProperties() {
return builder.props;
}
public Boolean hasProperties() {
return builder.props != null;
}
private boolean postConstructCalled = false;
@PostConstruct
public void init() {
this.postConstructCalled = true;
}
public boolean wasPostConstructCalled() {
return postConstructCalled;
}
private boolean preDestroyCalled = false;
@PreDestroy
public void shutdown() {
this.preDestroyCalled = true;
}
public boolean wasPreDestroyCalled() {
return preDestroyCalled;
}
}
| 2,146 |
0 | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/test/java/com/netflix/fabricator/component/TestJsonValue.java | package com.netflix.fabricator.component;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.netflix.fabricator.annotations.Type;
import com.netflix.fabricator.component.TestBindings.SomeComponent;
import com.netflix.fabricator.component.TestBindings.SomeComponent.Builder;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
import com.netflix.fabricator.guice.ComponentModuleBuilder;
import com.netflix.fabricator.properties.PropertiesConfigurationModule;
public class TestJsonValue {
private static String json =
"{"
+ " \"type\":\"somecomponent\","
+ " \"a\":\"_a\""
+ "}";
@Type("somecomponent")
public static class SomeComponent {
public static class Builder {
private String a = null;
public void withA(String a) {
this.a = a;
}
public SomeComponent build() {
return new SomeComponent(this);
}
}
private final String a;
public static Builder builder() {
return new Builder();
}
private SomeComponent(Builder builder) {
this.a = builder.a;
}
public String getA() {
return a;
}
}
@Test
public void test() throws ComponentCreationException, ComponentAlreadyExistsException {
Properties props = new Properties();
props.setProperty("id1.somecomponent", json);
Injector injector = Guice.createInjector(
new PropertiesConfigurationModule(props),
new ComponentModuleBuilder<SomeComponent>()
.manager(SynchronizedComponentManager.class)
.build(SomeComponent.class)
);
ComponentManager<SomeComponent> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeComponent>>() {}));
SomeComponent component = manager.get("id1");
Assert.assertEquals("_a", component.getA());
}
}
| 2,147 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/GuiceBindingComponentFactoryProvider.java | package com.netflix.fabricator.guice;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;
import com.google.inject.spi.Toolable;
import com.netflix.fabricator.BindingComponentFactory;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.InjectionSpi;
import com.netflix.fabricator.PropertyBinder;
import com.netflix.fabricator.PropertyBinderResolver;
import com.netflix.fabricator.component.ComponentFactory;
import com.netflix.fabricator.component.bind.SimplePropertyBinderFactoryResolver;
import com.netflix.fabricator.guice.mapping.EmbeddedComponentManagerBinding;
import com.netflix.fabricator.guice.mapping.NamedComponentManagerBinding;
import com.netflix.fabricator.guice.mapping.EmbeddedComponentFactoryBinding;
import com.netflix.fabricator.guice.mapping.EmbeddedMapToComponentFactoryBinding;
import com.netflix.fabricator.guice.mapping.NamedMapBinding;
import com.netflix.fabricator.guice.mapping.NamedBinding;
import com.netflix.fabricator.guice.mapping.PropertyInjection;
/**
* Utility class for creating a binding between a type string name and an
* implementation using the builder pattern.
*
* TODO: PostConstruct and PreDestroy
*
* @author elandau
*
* @param <T>
*
*/
public class GuiceBindingComponentFactoryProvider<T> implements ProviderWithExtensionVisitor<ComponentFactory<T>>, InjectionSpi {
private static final Logger LOG = LoggerFactory.getLogger(GuiceBindingComponentFactoryProvider.class);
private SettableInjector injector = new SettableInjector();
private BindingComponentFactory<T> factory;
private PropertyBinderResolver binderResolver;
private Class<?> clazz;
public GuiceBindingComponentFactoryProvider(final Class<?> clazz) {
this(clazz, new SettableInjector());
}
public GuiceBindingComponentFactoryProvider(final Class<?> clazz, SettableInjector injector) {
this.binderResolver = new SimplePropertyBinderFactoryResolver(null, this);
this.clazz = clazz;
if (injector != null)
initialize(injector);
}
@Override
public ComponentFactory<T> get() {
return factory.get();
}
/**
* This is needed for 'initialize(injector)' below to be called so the provider
* can get the injector after it is instantiated.
*/
@Override
public <B, V> V acceptExtensionVisitor(
BindingTargetVisitor<B, V> visitor,
ProviderInstanceBinding<? extends B> binding) {
return visitor.visit(binding);
}
@Inject
@Toolable
void initialize(Injector injector) {
this.injector.set(injector);
this.factory = new BindingComponentFactory<T>(clazz, binderResolver, this);
}
@Override
public PropertyBinder createInjectableProperty(final String propertyName, Class<?> argType, Method method) {
// Allowable bindings for named binding
final PropertyInjection namedPropertyInjection = new PropertyInjection(argType, injector, method);
namedPropertyInjection
.addStrategy(new NamedBinding()) // T
.addStrategy(new NamedMapBinding()) // Map<String, T>
.addStrategy(new NamedComponentManagerBinding(propertyName) // ComponentManager<T>
);
// Allowable bindings for embedded structures
final PropertyInjection embeddedPropertyInjection = new PropertyInjection(argType, injector, method);
embeddedPropertyInjection
.addStrategy(new EmbeddedComponentManagerBinding(propertyName)) // ComponentManager<T>
.addStrategy(new EmbeddedMapToComponentFactoryBinding()) // Map<String, ComponentFactory<T>>
.addStrategy(new EmbeddedComponentFactoryBinding()) // ComponentFactory<T>
.addStrategy(new NamedMapBinding() // Does this belong here
);
//Build up a sequence of Binding resolving and value retrieving processes.
//Any successful step will terminate the sequence
return new PropertyBinder() {
@Override
public boolean bind(Object obj, ConfigurationNode node) throws Exception {
// Property value is a simple 'string'
// Look for 'named' binding or 'key' in a mapbinder
if (node.isSingle()) {
String value = node.getValue(String.class);
if (value != null) {
if (namedPropertyInjection.execute(value, obj, node)) {
return true;
}
}
else {
// Hmmm...
}
return false;
}
// Property is a structure
else {
return embeddedPropertyInjection.execute(null, obj, node);
}
}
};
}
@Override
public <S> S getInstance(Class<S> clazz) {
return injector.getInstance(clazz);
}
@Override
public void injectMembers(Object obj) {
injector.injectMembers(obj);
}
}
| 2,148 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/ComponentModuleBuilder.java | package com.netflix.fabricator.guice;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.MapBinder;
import com.google.inject.name.Names;
import com.google.inject.util.Types;
import com.netflix.fabricator.Builder;
import com.netflix.fabricator.ComponentType;
import com.netflix.fabricator.annotations.Default;
import com.netflix.fabricator.annotations.TypeImplementation;
import com.netflix.fabricator.annotations.Type;
import com.netflix.fabricator.component.ComponentFactory;
import com.netflix.fabricator.component.ComponentManager;
import com.netflix.governator.guice.lazy.LazySingletonScope;
/**
* Utility class for creating a binding between a type string name and an
* implementation using the builder pattern.
*
* @author elandau
*
* @param <T>
*/
public class ComponentModuleBuilder<T> {
private Map<String, Provider<ComponentFactory<T>>> bindings = Maps.newHashMap();
private Set<String> ids = Sets.newHashSet();
private Map<String, T> instances = Maps.newHashMap();
private Class<? extends ComponentManager> managerClass;
private String typeName;
public Module build(final Class<T> type) {
return new AbstractModule() {
@Override
protected void configure() {
TypeLiteral componentFactoryTypeLiteral = TypeLiteral.get(Types.newParameterizedType(ComponentFactory.class, type));
if (managerClass != null) {
TypeLiteral<ComponentType<T>> componentType = (TypeLiteral<ComponentType<T>>) TypeLiteral.get(Types.newParameterizedType(ComponentType.class, type));
if (typeName == null) {
Type typeAnnot = type.getAnnotation(Type.class);
Preconditions.checkNotNull(typeAnnot, "Missing @Type annotation for " + type.getCanonicalName());
bind(componentType)
.toInstance(new ComponentType<T>(typeAnnot.value()));
}
else {
bind(componentType)
.toInstance(new ComponentType<T>(typeName));
}
TypeLiteral<ComponentManager<T>> managerType = (TypeLiteral<ComponentManager<T>>) TypeLiteral.get(Types.newParameterizedType(ComponentManager.class, type));
TypeLiteral<ComponentManager<T>> managerTypeImpl = (TypeLiteral<ComponentManager<T>>) TypeLiteral.get(Types.newParameterizedType(managerClass, type));
bind(managerType)
.to(managerTypeImpl)
.in(LazySingletonScope.get());
if (!Modifier.isAbstract(type.getModifiers() )) {
bind(componentFactoryTypeLiteral)
.annotatedWith(Default.class)
.toProvider(new GuiceBindingComponentFactoryProvider<T>((Class<T>) type))
.in(LazySingletonScope.get());
}
}
// Create the multi binder for this type.
MapBinder<String, ComponentFactory<T>> factories = (MapBinder<String, ComponentFactory<T>>) MapBinder.newMapBinder(
binder(),
TypeLiteral.get(String.class),
componentFactoryTypeLiteral
);
// Add different sub types to the multi binder
for (Entry<String, Provider<ComponentFactory<T>>> entry : bindings.entrySet()) {
factories.addBinding(entry.getKey()).toProvider(entry.getValue());
}
// Add specific named ids
for (String id : ids) {
bind(type)
.annotatedWith(Names.named(id))
.toProvider(new NamedInstanceProvider(id, TypeLiteral.get(Types.newParameterizedType(ComponentManager.class, type))));
}
// Add externally provided named instances
for (Entry<String, T> entry : instances.entrySet()) {
bind(type)
.annotatedWith(Names.named(entry.getKey()))
.toInstance(entry.getValue());
}
}
};
}
/**
* Identifies a specific subclass of the component type. The mapper will create
* an instance of class 'type' whenever it sees the value 'id' for the type
* field in the configuration specification (i.e. .properties or .json data)
*
* @param subTypeName
* @param subType
*/
public ComponentModuleBuilder<T> implementation(String subTypeName, Class<? extends T> subType) {
bindings.put(subTypeName, new GuiceBindingComponentFactoryProvider<T>(subType));
return this;
}
public ComponentModuleBuilder<T> implementation(Class<? extends T> type) {
TypeImplementation subType = type.getAnnotation(TypeImplementation.class);
Preconditions.checkNotNull(subType, "Missing @TypeImplementation for class " + type.getCanonicalName());
bindings.put(subType.value(), new GuiceBindingComponentFactoryProvider<T>((Class<T>) type));
return this;
}
public ComponentModuleBuilder<T> factory(String subType, final Class<? extends ComponentFactory<T>> factory) {
bindings.put(subType, new ComponentFactoryFactoryProvider<T>(factory));
return this;
}
public ComponentModuleBuilder<T> typename(String typeName) {
this.typeName = typeName;
return this;
}
public ComponentModuleBuilder<T> manager(Class<? extends ComponentManager> clazz) {
managerClass = clazz;
return this;
}
/**
* Specify a builder (as a Factory) on which configuration will be mapped and the
* final object created when the builder's build() method is called. Use this
* when you don't have access to the implementing class.
*
* Example usage,
*
* install(new ComponentMouldeBuilder<SomeComponent>()
* .builder("type", MyCompomentBuilder.class)
* .build();
*
* public class MyComponentBuilder implements Builder<SomeComponent> {
* public MyComponentBuilder withSomeProperty(String value) {
* ...
* }
*
* ...
*
* public SomeComponent build() {
* return new SomeComponentImpl(...);
* }
* }
*
* @param type
* @param builder
* @return
*/
public ComponentModuleBuilder<T> builder(String type, Class<? extends Builder<T>> builder) {
bindings.put(type, new GuiceBindingComponentFactoryProvider<T>(builder));
return this;
}
/**
* Indicate a specific instance for id. This makes it possible to inject an instance
* using @Named('id') instead of the ComponentManager
*
* @param id
* @return
*/
public ComponentModuleBuilder<T> named(String id) {
ids.add(id);
return this;
}
/**
* A a named instance of an existing component. No configuration will be done here.
* @param id
* @param instance
* @return
*/
public ComponentModuleBuilder<T> named(String id, T instance) {
instances.put(id, instance);
return this;
}
}
| 2,149 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/NamedInstanceProvider.java | package com.netflix.fabricator.guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;
import com.google.inject.spi.Toolable;
import com.netflix.fabricator.component.ComponentManager;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;
/**
* Special provider that links a ComponentManager with a named instance of a
* Component so that the component may be inject by
*
* void SomeServiceConstructor(@Named("componentId") ComponentType component) {
* }
*
* To use,
*
* install(ComponentModuleBuilder<ComponentType>().builder()
* .named("componentId")
* .build());
*
* @author elandau
*
* @param <T>
*/
public class NamedInstanceProvider<T> implements ProviderWithExtensionVisitor<T> {
private ComponentManager<T> manager;
private final String id;
private TypeLiteral<ComponentManager<T>> typeLiteral;
public NamedInstanceProvider(String id, TypeLiteral<ComponentManager<T>> typeLiteral) {
this.id = id;
this.typeLiteral = typeLiteral;
}
@Override
public T get() {
try {
return manager.get(id);
}
catch (ComponentCreationException e) {
throw new RuntimeException(e);
}
catch (ComponentAlreadyExistsException e) {
throw new RuntimeException(e);
}
}
@Override
public <B, V> V acceptExtensionVisitor(
BindingTargetVisitor<B, V> visitor,
ProviderInstanceBinding<? extends B> binding) {
return visitor.visit(binding);
}
@Inject
@Toolable
void initialize(Injector injector) {
manager = injector.getInstance(Key.get(typeLiteral));
}
}
| 2,150 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/ComponentFactoryFactoryProvider.java | package com.netflix.fabricator.guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;
import com.google.inject.spi.Toolable;
import com.netflix.fabricator.component.ComponentFactory;
public class ComponentFactoryFactoryProvider<T> implements ProviderWithExtensionVisitor<ComponentFactory<T>> {
private Class<? extends ComponentFactory<T>> clazz;
private ComponentFactory<T> factory;
public ComponentFactoryFactoryProvider(final Class<? extends ComponentFactory<T>> clazz) {
this.clazz = clazz;
}
@Override
public ComponentFactory<T> get() {
return factory;
}
/**
* This is needed for 'initialize(injector)' below to be called so the provider
* can get the injector after it is instantiated.
*/
@Override
public <B, V> V acceptExtensionVisitor(
BindingTargetVisitor<B, V> visitor,
ProviderInstanceBinding<? extends B> binding) {
return visitor.visit(binding);
}
@Inject
@Toolable
void initialize(Injector injector) {
this.factory = (ComponentFactory<T>) injector.getInstance(clazz);
}
}
| 2,151 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/SettableInjector.java | package com.netflix.fabricator.guice;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.MembersInjector;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeConverterBinding;
public class SettableInjector implements Injector {
private Injector injector;
@Override
public void injectMembers(Object instance) {
injector.injectMembers(instance);
}
@Override
public <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral) {
return injector.getMembersInjector(typeLiteral);
}
@Override
public <T> MembersInjector<T> getMembersInjector(Class<T> type) {
return injector.getMembersInjector(type);
}
@Override
public Map<Key<?>, Binding<?>> getBindings() {
return injector.getBindings();
}
@Override
public Map<Key<?>, Binding<?>> getAllBindings() {
return injector.getAllBindings();
}
@Override
public <T> Binding<T> getBinding(Key<T> key) {
return injector.getBinding(key);
}
@Override
public <T> Binding<T> getBinding(Class<T> type) {
return injector.getBinding(type);
}
@Override
public <T> Binding<T> getExistingBinding(Key<T> key) {
return injector.getExistingBinding(key);
}
@Override
public <T> List<Binding<T>> findBindingsByType(TypeLiteral<T> type) {
return injector.findBindingsByType(type);
}
@Override
public <T> Provider<T> getProvider(Key<T> key) {
return injector.getProvider(key);
}
@Override
public <T> Provider<T> getProvider(Class<T> type) {
return injector.getProvider(type);
}
@Override
public <T> T getInstance(Key<T> key) {
return injector.getInstance(key);
}
@Override
public <T> T getInstance(Class<T> type) {
return injector.getInstance(type);
}
@Override
public Injector getParent() {
return injector.getParent();
}
@Override
public Injector createChildInjector(Iterable<? extends Module> modules) {
return injector.createChildInjector(modules);
}
@Override
public Injector createChildInjector(Module... modules) {
return injector.createChildInjector(modules);
}
@Override
public Map<Class<? extends Annotation>, Scope> getScopeBindings() {
return injector.getScopeBindings();
}
@Override
public Set<TypeConverterBinding> getTypeConverterBindings() {
return injector.getTypeConverterBindings();
}
public void set(Injector injector) {
this.injector = injector;
}
}
| 2,152 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/EmbeddedComponentFactoryBinding.java | package com.netflix.fabricator.guice.mapping;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.util.Types;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.component.ComponentFactory;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
/**
* Look for a binding of type : ComponentFactory<T>
*
* Created by hyuan on 1/17/14.
*/
public class EmbeddedComponentFactoryBinding implements BindingReslove {
@Override
public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception {
ParameterizedType subType = Types.newParameterizedType(ComponentFactory.class, argType);
Key<ComponentFactory<?>> subKey = (Key<ComponentFactory<?>>) Key.get(subType);
Binding<ComponentFactory<?>> binding = injector.getExistingBinding(subKey);
if (binding != null) {
ComponentFactory<?> factory = injector.getInstance(subKey);
if (factory != null) {
Object subObject = factory.create(node);
method.invoke(obj, subObject);
return true;
}
}
return false;
}
}
| 2,153 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/PropertyInjectionStrategy.java | package com.netflix.fabricator.guice.mapping;
import com.netflix.fabricator.ConfigurationNode;
/**
* Created by hyuan on 1/16/14.
*/
public interface PropertyInjectionStrategy {
PropertyInjectionStrategy addStrategy(BindingReslove concretePropertyInjectionImpl);
boolean execute(String name, Object targetObj, ConfigurationNode node) throws Exception;
}
| 2,154 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/CompositeNoExistingBinding.java | package com.netflix.fabricator.guice.mapping;
import com.google.common.base.Preconditions;
import com.google.inject.Injector;
import com.netflix.fabricator.BindingComponentFactory;
import com.netflix.fabricator.ConfigurationNode;
import java.lang.reflect.Method;
/**
* Created by hyuan on 1/17/14.
*/
public class CompositeNoExistingBinding implements BindingReslove {
private final String propertyName;
private final BindingComponentFactory<?> provider;
public CompositeNoExistingBinding(String propertyName, BindingComponentFactory<?> provider) {
Preconditions.checkNotNull(propertyName);
Preconditions.checkNotNull(provider);
this.propertyName = propertyName;
this.provider = provider;
}
@Override
public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception {
if (node != null) {
Object subObject = provider.get().create(node);
method.invoke(obj, subObject);
}
return true;
}
}
| 2,155 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/PropertyInjection.java | package com.netflix.fabricator.guice.mapping;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.netflix.fabricator.ConfigurationNode;
import java.lang.reflect.Method;
import java.util.List;
/**
* Created by hyuan on 1/16/14.
*/
public class PropertyInjection implements PropertyInjectionStrategy {
private final List<BindingReslove> injectionStrategies;
private final Class<?> argType;
private final Injector injector;
private final Method buildMethod;
public PropertyInjection(Class<?> argType, Injector injector, Method method) {
Preconditions.checkNotNull(argType);
Preconditions.checkNotNull(injector);
Preconditions.checkNotNull(method);
this.argType = argType;
this.injector = injector;
this.buildMethod = method;
injectionStrategies = Lists.newArrayList();
}
@Override
public PropertyInjectionStrategy addStrategy(BindingReslove concretePropertyInjectionImpl) {
injectionStrategies.add(concretePropertyInjectionImpl);
return this;
}
@Override
public boolean execute(String name, Object targetObj, ConfigurationNode node) throws Exception {
for (BindingReslove strategy : injectionStrategies) {
if (strategy.execute(name, targetObj, node, argType, injector, buildMethod)) {
return true;
}
}
return false;
}
}
| 2,156 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/NamedBinding.java | package com.netflix.fabricator.guice.mapping;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;
import com.netflix.fabricator.ConfigurationNode;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
/**
* Look for a named binding of type : T
*
* Created by hyuan on 1/16/14.
*/
public class NamedBinding implements BindingReslove {
@Override
public boolean execute(String name, Object obj, ConfigurationNode config, Class<?> argType, Injector injector, Method method) throws Exception {
Binding<?> binding;
Type pType = method.getGenericParameterTypes()[0];
if (pType != null) {
binding = injector.getExistingBinding(Key.get(pType, Names.named(name)));
}
else {
binding = injector.getExistingBinding(Key.get(argType, Names.named(name)));
}
if (binding != null) {
method.invoke(obj, binding.getProvider().get());
return true;
}
return false;
}
}
| 2,157 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/EmbeddedComponentManagerBinding.java | package com.netflix.fabricator.guice.mapping;
import java.lang.reflect.Method;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.component.ComponentManager;
/**
* Look for a binding of type : ComponentManager<T>
*
* @author elandau
*/
public class EmbeddedComponentManagerBinding implements BindingReslove {
private String propertyName;
public EmbeddedComponentManagerBinding(String propertyName) {
this.propertyName = propertyName;
}
@Override
public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception {
TypeLiteral<ComponentManager<?>> managerLiteral = (TypeLiteral<ComponentManager<?>>) TypeLiteral.get(Types.newParameterizedType(ComponentManager.class, argType));
Binding<ComponentManager<?>> managerBinding = injector.getExistingBinding(Key.get(managerLiteral));
if (managerBinding != null) {
ComponentManager<?> manager = managerBinding.getProvider().get();
try {
method.invoke(obj, manager.create(node));
return true;
}
catch (Exception e) {
throw new Exception(String.format(
"Unable to get component '%s' (%s) for property '%s' must be one of %s",
name, argType.getSimpleName(), propertyName, manager.getIds()), e);
}
}
return false;
}
}
| 2,158 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/ComponentFactoryBinding.java | package com.netflix.fabricator.guice.mapping;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Map;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.component.ComponentFactory;
public class ComponentFactoryBinding implements BindingReslove {
@Override
public boolean execute(String name, Object obj, ConfigurationNode config, Class<?> argType, Injector injector, Method method) throws Exception {
ParameterizedType componentFactoryProviderType = Types.newParameterizedTypeWithOwner(Provider.class, ComponentFactory.class, argType);
// Look for a MapBinder binding
TypeLiteral<Map<String, ?>> mapLiteral = (TypeLiteral<Map<String, ?>>) TypeLiteral.get(
Types.mapOf(String.class, componentFactoryProviderType));
Binding<Map<String, ?>> mapBinding = injector.getExistingBinding(Key.get(mapLiteral));
if (mapBinding != null) {
Map<String, ?> map = mapBinding.getProvider().get();
if (map.containsKey(name)) {
method.invoke(obj, map.get(name));
return true;
}
}
return false;
}
}
| 2,159 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/BindingReslove.java | package com.netflix.fabricator.guice.mapping;
import com.google.inject.Injector;
import com.netflix.fabricator.ConfigurationNode;
import java.lang.reflect.Method;
/**
* Created by hyuan on 1/16/14.
*/
public interface BindingReslove {
boolean execute(String name, Object obj, ConfigurationNode config, Class<?> argType, Injector injector, Method method) throws Exception;
}
| 2,160 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/EmbeddedMapToComponentFactoryBinding.java | package com.netflix.fabricator.guice.mapping;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.component.ComponentFactory;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Look for a binding where type is in the map binding : Map<String, ComponentFactory<T>>
*
* Created by hyuan on 1/17/14.
*/
public class EmbeddedMapToComponentFactoryBinding implements BindingReslove {
@Override
public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception {
if (argType.isInterface()) {
@SuppressWarnings("unchecked")
TypeLiteral<Map<String, ComponentFactory<?>>> mapType =
(TypeLiteral<Map<String, ComponentFactory<?>>>) TypeLiteral.get(
Types.mapOf(String.class,
Types.newParameterizedType(
ComponentFactory.class,
argType)));
Key<Map<String, ComponentFactory<?>>> mapKey = Key.get(mapType);
Binding<Map<String, ComponentFactory<?>>> binding = injector.getExistingBinding(mapKey);
if (binding != null) {
if (node.getType() != null) {
Map<String, ComponentFactory<?>> map = binding.getProvider().get();
ComponentFactory<?> factory = map.get(node.getType());
if (factory != null) {
Object subObject = factory
.create(node);
method.invoke(obj, subObject);
return true;
}
}
}
}
return false;
}
}
| 2,161 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/NamedMapBinding.java | package com.netflix.fabricator.guice.mapping;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
import com.netflix.fabricator.ConfigurationNode;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Look for a named component in a map binding : Map<String, T>
*
* Created by hyuan on 1/16/14.
*/
public class NamedMapBinding implements BindingReslove {
@Override
public boolean execute(String name, Object obj, ConfigurationNode config, Class<?> argType, Injector injector, Method method) throws Exception {
// Look for a MapBinder binding
TypeLiteral<Map<String, ?>> mapLiteral = (TypeLiteral<Map<String, ?>>) TypeLiteral.get(
Types.mapOf(String.class, argType));
Binding<Map<String, ?>> mapBinding = injector.getExistingBinding(Key.get(mapLiteral));
if (mapBinding != null) {
Map<String, ?> map = mapBinding.getProvider().get();
if (map.containsKey(name)) {
method.invoke(obj, map.get(name));
return true;
}
}
return false;
}
}
| 2,162 |
0 | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice | Create_ds/fabricator/fabricator-guice/src/main/java/com/netflix/fabricator/guice/mapping/NamedComponentManagerBinding.java | package com.netflix.fabricator.guice.mapping;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
import com.netflix.fabricator.ConfigurationNode;
import com.netflix.fabricator.component.ComponentManager;
import java.lang.reflect.Method;
/**
* Look for a named component in the binding of type : ComponentManager<T>
*
* Created by hyuan on 1/16/14.
*/
public class NamedComponentManagerBinding implements BindingReslove {
private String propertyName;
public NamedComponentManagerBinding(String propertyName) {
this.propertyName = propertyName;
}
@Override
public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception {
TypeLiteral<ComponentManager<?>> managerLiteral = (TypeLiteral<ComponentManager<?>>) TypeLiteral.get(Types.newParameterizedType(ComponentManager.class, argType));
Binding<ComponentManager<?>> managerBinding = injector.getExistingBinding(Key.get(managerLiteral));
if (managerBinding != null) {
ComponentManager<?> manager = managerBinding.getProvider().get();
try {
method.invoke(obj, manager.get(name));
return true;
}
catch (Exception e) {
throw new Exception(String.format(
"Unable to get component '%s' (%s) for property '%s' must be one of %s",
name, argType.getSimpleName(), propertyName, manager.getIds()), e);
}
}
return false;
}
}
| 2,163 |
0 | Create_ds/runtime-health/health-api/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/test/java/com/netflix/runtime/health/api/HealthBuilderTest.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.runtime.health.api;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class HealthBuilderTest {
@Test
public void healthyStatus() {
Health health = Health.healthy().build();
assertNotNull(health);
assertNotNull(health.isHealthy());
assertTrue(health.isHealthy());
assertNotNull(health.getDetails());
assertTrue(health.getDetails().isEmpty());
}
@Test
public void healthyStatusWithDetails() {
Health health = Health.healthy()
.withDetail("foo", "bar")
.withDetail("baz", "qux").build();
assertNotNull(health);
assertNotNull(health.isHealthy());
assertTrue(health.isHealthy());
assertNotNull(health.getDetails());
assertFalse(health.getDetails().isEmpty());
assertEquals("bar", health.getDetails().get("foo"));
assertEquals("qux", health.getDetails().get("baz"));
assertFalse(health.getErrorMessage().isPresent());
}
@Test
public void unhealthyStatus() {
Health health = Health.unhealthy().build();
assertNotNull(health);
assertNotNull(health.isHealthy());
assertFalse(health.isHealthy());
assertNotNull(health.getDetails());
assertTrue(health.getDetails().isEmpty());
assertFalse(health.getErrorMessage().isPresent());
}
@Test
public void unhealthyStatusWithExceptoin() {
Health health = Health.unhealthy()
.withException(new RuntimeException("Boom"))
.build();
assertNotNull(health);
assertNotNull(health.isHealthy());
assertFalse(health.isHealthy());
assertNotNull(health.getDetails());
assertFalse(health.getDetails().isEmpty());
assertEquals("java.lang.RuntimeException: Boom", health.getDetails().get(Health.ERROR_KEY));
assertEquals("java.lang.RuntimeException: Boom", health.getErrorMessage().get());
}
@Test
public void unhealthyStatusWithDetails() {
Health health = Health.unhealthy()
.withException(new RuntimeException("Boom"))
.withDetail("foo", "bar")
.withDetail("baz", "qux").build();
assertNotNull(health);
assertNotNull(health.isHealthy());
assertFalse(health.isHealthy());
assertNotNull(health.getDetails());
assertFalse(health.getDetails().isEmpty());
assertEquals("bar", health.getDetails().get("foo"));
assertEquals("qux", health.getDetails().get("baz"));
assertEquals("java.lang.RuntimeException: Boom", health.getDetails().get(Health.ERROR_KEY));
assertEquals("java.lang.RuntimeException: Boom", health.getErrorMessage().get());
}
@Test
public void exceptionOnNullDetailKey() {
assertThatThrownBy(() -> Health.healthy().withDetail(null, "value"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Key must not be null");
}
@Test
public void exceptionOnNullDetailValue() {
assertThatThrownBy(() -> Health.healthy().withDetail("key", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Data must not be null");
}
@Test
public void exceptionOnReservedErrorKeySet() {
assertThatThrownBy(() -> Health.healthy().withDetail("error", "some error"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("\"error\" is a reserved key and may not be overridden");
}
}
| 2,164 |
0 | Create_ds/runtime-health/health-api/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/test/java/com/netflix/runtime/health/api/IndicatorMatchersTest.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.runtime.health.api;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IndicatorMatchersTest {
private static class A implements HealthIndicator {
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
}
private static class B implements HealthIndicator {
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
}
private static class C implements HealthIndicator {
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
}
@Test
public void testEmpty() {
assertTrue(IndicatorMatchers.build().matches(new A()));
}
@Test
public void testInclude() {
assertTrue(IndicatorMatchers.includes(A.class.getName(), B.class.getName()).build().matches(new A()));
assertTrue(IndicatorMatchers.includes(A.class.getName(), B.class.getName()).build().matches(new B()));
assertFalse(IndicatorMatchers.includes(A.class.getName(), B.class.getName()).build().matches(new C()));
}
@Test
public void testAdditiveInclude() {
assertTrue(IndicatorMatchers.includes(A.class.getName()).includes(B.class.getName()).build().matches(new A()));
assertTrue(IndicatorMatchers.includes(A.class.getName()).includes(B.class.getName()).build().matches(new B()));
assertFalse(IndicatorMatchers.includes(A.class.getName()).includes(B.class.getName()).build().matches(new C()));
}
@Test
public void testExclude() {
assertFalse(IndicatorMatchers.excludes(A.class.getName(), B.class.getName()).build().matches(new A()));
assertFalse(IndicatorMatchers.excludes(A.class.getName(), B.class.getName()).build().matches(new B()));
assertTrue(IndicatorMatchers.excludes(A.class.getName(), B.class.getName()).build().matches(new C()));
}
@Test
public void testAdditiveExclude() {
assertFalse(IndicatorMatchers.excludes(A.class.getName()).excludes(B.class.getName()).build().matches(new A()));
assertFalse(IndicatorMatchers.excludes(A.class.getName()).excludes(B.class.getName()).build().matches(new B()));
assertTrue(IndicatorMatchers.excludes(A.class.getName()).excludes(B.class.getName()).build().matches(new C()));
}
@Test
public void testIncludesAndExcludes() {
assertTrue(IndicatorMatchers.includes(A.class.getName()).excludes(B.class.getName()).build().matches(new A()));
assertFalse(IndicatorMatchers.includes(A.class.getName()).excludes(B.class.getName()).build().matches(new B()));
assertFalse(IndicatorMatchers.includes(A.class.getName()).excludes(B.class.getName()).build().matches(new C()));
}
@Test
public void testExcludeBeatsInclude() {
assertFalse(IndicatorMatchers.includes(A.class.getName()).excludes(A.class.getName()).build().matches(new A()));
}
}
| 2,165 |
0 | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health/api/HealthIndicatorCallback.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.runtime.health.api;
/***
* Basic interface passed to {@link HealthIndicator} instances allowing them to
* provide their view of {@link Health}
*/
public interface HealthIndicatorCallback {
void inform(Health status);
} | 2,166 |
0 | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health/api/IndicatorMatchers.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.runtime.health.api;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* Static builder of for creating an {@link IndicatorMatcher} instance. Excluded
* indicators will take priority over included ones.
*
* <pre>
* IndicatorMatchers.includes(someIndicatorInstance)
* .excludes("someIndicatorName")
* .build();
* </pre>
*/
public class IndicatorMatchers {
public static IndicatorMatcherBuilder includes(String... indicatorNames) {
return new IndicatorMatcherBuilder().includes(indicatorNames);
}
public static IndicatorMatcherBuilder excludes(String... indicatorNames) {
return new IndicatorMatcherBuilder().excludes(indicatorNames);
}
public static IndicatorMatcher build() {
return unused -> true;
}
public static class IndicatorMatcherBuilder {
public final List<String> includedIndicatorNames;
public final List<String> excludedIndicatorNames;
public IndicatorMatcherBuilder() {
this.includedIndicatorNames = new ArrayList<>();
this.excludedIndicatorNames = new ArrayList<>();
}
public IndicatorMatcherBuilder includes(String... indicatorNames) {
if (indicatorNames != null) {
includedIndicatorNames.addAll(Arrays.asList(indicatorNames));
}
return this;
}
public IndicatorMatcherBuilder excludes(String... indicatorNames) {
if (indicatorNames != null) {
excludedIndicatorNames.addAll(Arrays.asList(indicatorNames));
}
return this;
}
public IndicatorMatcher build() {
return indicator -> {
return excludedIndicatorNames.stream().noneMatch(i -> indicator.getName().equals(i))
&& (includedIndicatorNames.isEmpty()
|| includedIndicatorNames.stream().anyMatch(indicator.getName()::equals));
};
}
}
}
| 2,167 |
0 | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health/api/HealthCheckAggregator.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.runtime.health.api;
import java.util.concurrent.CompletableFuture;
/**
* The HealthCheckAggregator consolidates implementations of {@link HealthIndicator} and is responsible
* for invoking each of them and returning a composite view of their status.
*/
public interface HealthCheckAggregator {
/**
* Invoke all configured {@link HealthIndicator} instances and return the overall health.
*/
CompletableFuture<HealthCheckStatus> check();
/**
* Invoke all configured {@link HealthIndicator} instances and return the overall health.
* {@link HealthIndicator}s not matched by the provided {@link IndicatorMatcher} will be reported
* as "suppressed" and will not have their {@link Health} considered as part of {@link HealthCheckStatus}.isHealthy().
*
* This can be used to prevent a set of {@link HealthIndicator}s from marking your service as "unhealthy", while still
* surfacing the information about their failure.
*/
CompletableFuture<HealthCheckStatus> check(IndicatorMatcher matcher);
}
| 2,168 |
0 | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health/api/IndicatorMatcher.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.runtime.health.api;
/**
* A matcher used when invoking {@link HealthCheckAggregator}.check() to explicitly include/exclude which
* indicators should be used when calculating the healthiness of the application. See {@link IndicatorMatchers}
* for creating IndicatorMatchers programmatically.
*/
public interface IndicatorMatcher {
boolean matches(HealthIndicator indicator);
}
| 2,169 |
0 | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health/api/HealthCheckStatus.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.runtime.health.api;
import java.util.ArrayList;
import java.util.List;
/**
* Immutable status returned by {@link HealthCheckAggregator}.
*/
public class HealthCheckStatus {
private final boolean isHealthy;
private final List<Health> healthResults;
private final List<Health> suppressedHealthResults;
public HealthCheckStatus(boolean isHealthy, List<Health> indicators) {
this.isHealthy = isHealthy;
this.healthResults = new ArrayList<>(indicators);
this.suppressedHealthResults = new ArrayList<>();
}
public HealthCheckStatus(boolean isHealthy, List<Health> indicators, List<Health> suppressedIndicators) {
this.isHealthy = isHealthy;
this.healthResults = new ArrayList<>(indicators);
this.suppressedHealthResults = new ArrayList<>(suppressedIndicators);
}
public boolean isHealthy() {
return isHealthy;
}
/**
* Health results returned by instances of {@link HealthIndicator} and not suppressed by an {@link IndicatorMatcher}.
*/
public List<Health> getHealthResults() {
return healthResults;
}
/**
* Health results returned by instances of {@link HealthIndicator} but suppressed by an {@link IndicatorMatcher}.
*/
public List<Health> getSuppressedHealthResults() {
return suppressedHealthResults;
}
public static HealthCheckStatus create(boolean isHealthy, List<Health> indicators) {
return new HealthCheckStatus(isHealthy, indicators);
}
public static HealthCheckStatus create(boolean isHealthy, List<Health> indicators, List<Health> suppressedIndicators) {
return new HealthCheckStatus(isHealthy, indicators, suppressedIndicators);
}
@Override
public String toString() {
return "HealthCheckStatus[isHealthy=" + isHealthy + ", indicators=" + healthResults + ", + suppressedIndicators=" + suppressedHealthResults + "]";
}
}
| 2,170 |
0 | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health/api/Health.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.runtime.health.api;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
/**
* Immutable health check instance returned from a {@link HealthIndicator}
*
* This may be one of {@link Health}.healthy() or {@link Health}.unhealthy().
* Additional details may be provided (ex. {@link Health}.unhealthy(exception).withDetails(...)
*/
public final class Health {
public static final String ERROR_KEY = "error";
public static final String CACHE_KEY = "cached";
public static final String NAME_KEY = "className";
private final Map<String, Object> details;
private final boolean isHealthy;
private Health(boolean isHealthy) {
this.isHealthy=isHealthy;
this.details = new LinkedHashMap<>();
}
private Health(boolean isHealthy, Map<String, Object> details) {
this.isHealthy = isHealthy;
this.details = new LinkedHashMap<>(details);
}
private Health(Health health) {
this.isHealthy = health.isHealthy();
this.details = health.getDetails();
}
/**
* @return Map of named attributes that provide additional information regarding the health.
* For example, a CPU health check may return Unhealthy with attribute "usage"="90%"
*/
public Map<String, Object> getDetails() {
return this.details;
}
/**
* @return True if healthy or false otherwise.
*/
public boolean isHealthy() {
return this.isHealthy;
}
public Optional<String> getErrorMessage() {
return Optional.ofNullable((String) getDetails().get(ERROR_KEY));
}
/**
* Create a new {@link Builder} instance with a {@link Health} of "healthy".
* @return a new {@link Builder} instance
*/
public static Builder healthy() {
return from(new Health(true));
}
/**
* Create a new {@link Builder} instance with a {@link Health} of "unhealthy"
* which includes the provided exception details.
* @param ex the exception
* @return a new {@link Builder} instance
*/
public static Builder unhealthy(Throwable ex) {
return unhealthy().withException(ex);
}
/**
* Create a new {@link Builder} instance with a {@link Health} of "unhealthy".
* @return a new {@link Builder} instance
*/
public static Builder unhealthy() {
return from(new Health(false));
}
/**
* Create a new {@link Builder} instance with a specific {@link Health}.
* @param health the health
* @return a new {@link Builder} instance
*/
public static Builder from(Health health) {
return new Builder(health);
}
/**
* Builder for creating immutable {@link Health} instances.
*/
public static class Builder {
private final boolean isHealthy;
private final Map<String, Object> details;
/**
* Create new Builder instance using a {@link Health}
* @param health the {@link Health} to use
*/
private Builder(Health health) {
assertNotNull(health, "Health must not be null");
this.isHealthy = health.isHealthy();
this.details = health.getDetails();
}
/**
* Record detail for given {@link Exception}.
* @param ex the exception
* @return this {@link Builder} instance
*/
public Builder withException(Throwable ex) {
assertNotNull(ex, "Exception must not be null");
this.details.put(ERROR_KEY, ex.getClass().getName() + ": " + ex.getMessage());
return this;
}
/**
* Record detail using {@code key} and {@code value}.
* @param key the detail key
* @param data the detail data
* @return this {@link Builder} instance
*/
public Builder withDetail(String key, Object data) {
assertNotNull(key, "Key must not be null");
assertNotNull(data, "Data must not be null");
assertNotReservedKey(key, "\""+key+"\" is a reserved key and may not be overridden");
this.details.put(key, data);
return this;
}
/**
* Create a new {@link Health} from the provided information.
* @return a new {@link Health} instance
*/
public Health build() {
return new Health(this.isHealthy, this.details);
}
}
private static void assertNotNull(Object test, String message) {
if(test == null){
throw new IllegalArgumentException(message);
}
}
private static void assertNotReservedKey(Object key, String message) {
if(ERROR_KEY.equals(key)){
throw new IllegalArgumentException(message);
}
}
@Override
public String toString() {
return "Health [details=" + details + ", isHealthy=" + isHealthy + "]";
}
}
| 2,171 |
0 | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-api/src/main/java/com/netflix/runtime/health/api/HealthIndicator.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.runtime.health.api;
/**
* Basic interface for defining health indication logic. 0 or more HealthIndicators are used to determine
* the application health. HealthIndicators are tracked by a {@link HealthCheckAggregator}
* where the default implementation uses all registered HealthIndicators.
*
* HealthIndicator can inject types that are to be consulted for health indication, call out to shell
* scripts or call a remote service.
*
* To register a health indicator,
* <code>
* InjectorBuilder.fromModules(new HealthModule() {
* protected void configureHealth() {
* bindAdditionalHealthIndicator().to(MyCustomerIndicator.class);
* }
* }).createInjector()
* </code>
*
* Here is a sample health indicator implementation.
*
* <code>
* public class MyHealthIndicator implements HealthIndicator {
* {@literal @}Inject
* public MyHealthIndicator(MyService service) {
* this.service = service;
* }
*
* {@literal @}Inject
*
* public void check(HealthIndicatorCallback healthCallback) {
* if (service.getErrorRate() {@literal >} 0.1) {
* healthCallback.inform(Health.unhealthy()
* .withDetails("errorRate", service.getErrorRate()));
* }
* else {
* healthCallback.inform(Health.healthy());
* }
* }
* }
* </code>
*
* @author elandau
*/
public interface HealthIndicator {
/**
* Inform the provided {@link HealthIndicatorCallback} of the {@link Health}.
*
* Implementations should catch exceptions and return a status of unhealthy to provide customized messages.
* Uncaught exceptions will be captured by the default implementation of {@link HealthCheckAggregator} and
* returned as an unhealthy status automatically.
*
* Implementations of {@link HealthCheckAggregator} will also handle threading and timeouts for implementations
* of {@link HealthIndicator}. Each {@link HealthIndicator} will be run in its own thread with a timeout.
* Implementations should not spawn additional threads (or at least take responsibility for killing them).
* Timeouts will result in an unhealthy status being returned for any slow {@link HealthIndicator}
* with a status message indicating that it has timed out.
*/
void check(HealthIndicatorCallback healthCallback);
/**
* Name used in displaying and filtering (see {@link IndicatorMatcher}) HealthIndicators.
*/
default String getName() {
return this.getClass().getName();
}
}
| 2,172 |
0 | Create_ds/runtime-health/health-guice/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-guice/src/test/java/com/netflix/runtime/health/guice/HealthModuleTest.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.runtime.health.guice;
import static org.junit.Assert.*;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.netflix.archaius.guice.ArchaiusModule;
import com.netflix.governator.InjectorBuilder;
import com.netflix.governator.LifecycleInjector;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
public class HealthModuleTest {
static HealthIndicator healthy = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
};
static HealthIndicator unhealthy = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.unhealthy().build());
}
};
@Test
public void testNoIndicators() throws InterruptedException, ExecutionException {
LifecycleInjector injector = InjectorBuilder.fromModules(new HealthModule(), new ArchaiusModule()).createInjector();
HealthCheckAggregator aggregator = injector.getInstance(HealthCheckAggregator.class);
assertNotNull(aggregator);
HealthCheckStatus healthCheckStatus = aggregator.check().get();
assertTrue(healthCheckStatus.isHealthy());
assertEquals(0, healthCheckStatus.getHealthResults().size());
}
@Test
public void testMultipleIndicators() throws InterruptedException, ExecutionException {
LifecycleInjector injector = InjectorBuilder.fromModules(new HealthModule(), new ArchaiusModule(), new AbstractModule() {
@Override
protected void configure() {
Multibinder<HealthIndicator> healthIndicatorBinder = Multibinder.newSetBinder(binder(), HealthIndicator.class);
healthIndicatorBinder.addBinding().toInstance(healthy);
}
}, new AbstractModule() {
@Override
protected void configure() {
Multibinder<HealthIndicator> healthIndicatorBinder = Multibinder.newSetBinder(binder(), HealthIndicator.class);
healthIndicatorBinder.addBinding().toInstance(unhealthy);
}
}).createInjector();
HealthCheckAggregator aggregator = injector.getInstance(HealthCheckAggregator.class);
assertNotNull(aggregator);
HealthCheckStatus healthCheckStatus = aggregator.check().get();
assertFalse(healthCheckStatus.isHealthy());
assertEquals(2, healthCheckStatus.getHealthResults().size());
}
@Test
public void testConfiguringIndicatorsByExtendingHealthModule() throws InterruptedException, ExecutionException {
LifecycleInjector injector = InjectorBuilder.fromModules(new HealthModule() {
@Override
protected void configureHealth() {
bindAdditionalHealthIndicator().toInstance(healthy);
}
}, new ArchaiusModule()).createInjector();
HealthCheckAggregator aggregator = injector.getInstance(HealthCheckAggregator.class);
assertNotNull(aggregator);
HealthCheckStatus healthCheckStatus = aggregator.check().get();
assertTrue(healthCheckStatus.isHealthy());
assertEquals(1, healthCheckStatus.getHealthResults().size());
}
@Test
public void testMultipleInstancesOfHealthModuleInstalled() throws InterruptedException, ExecutionException {
LifecycleInjector injector = InjectorBuilder.fromModules(new HealthModule() {
@Override
protected void configureHealth() {
bindAdditionalHealthIndicator().toInstance(healthy);
}
}, new HealthModule() {
@Override
protected void configureHealth() {
bindAdditionalHealthIndicator().toInstance(unhealthy);
}
}, new ArchaiusModule()).createInjector();
HealthCheckAggregator aggregator = injector.getInstance(HealthCheckAggregator.class);
assertNotNull(aggregator);
HealthCheckStatus healthCheckStatus = aggregator.check().get();
assertFalse(healthCheckStatus.isHealthy());
assertEquals(2, healthCheckStatus.getHealthResults().size());
}
}
| 2,173 |
0 | Create_ds/runtime-health/health-guice/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-guice/src/main/java/com/netflix/runtime/health/guice/HealthModule.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.runtime.health.guice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Key;
import com.google.inject.Provides;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.multibindings.Multibinder;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.archaius.guice.ArchaiusModule;
import com.netflix.governator.event.ApplicationEventDispatcher;
import com.netflix.governator.event.guava.GuavaApplicationEventModule;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.core.HealthCheckStatusChangedEvent;
import com.netflix.runtime.health.core.SimpleHealthCheckAggregator;
import com.netflix.runtime.health.core.caching.DefaultCachingHealthCheckAggregator;
/***
* Guice module for installing runtime-health components. Installing this module
* providers support for registered custom {@link HealthIndicator}s. {@link HealthCheckStatusChangedEvent}s
* are dispatched each time the aggregated {@link HealthCheckStatus} for the application changes.
*
* For configuration of caching and timeouts of {@link HealthIndicator}s, see {@link HealthAggregatorConfiguration}.
*
* Custom {@link HealthIndicator}s may be registered as follows:
* <code>
* InjectorBuilder.fromModules(new HealthModule() {
* protected void configureHealth() {
* bindAdditionalHealthIndicator().to(MyCustomerIndicator.class);
* }
* }).createInjector()
* </code>
*
*/
public class HealthModule extends AbstractModule {
@Override
final protected void configure() {
install(new InternalHealthModule());
configureHealth();
}
/***
* Override to provide custom {@link HealthIndicator}s
*/
protected void configureHealth() {
};
final protected LinkedBindingBuilder<HealthIndicator> bindAdditionalHealthIndicator() {
return Multibinder.newSetBinder(binder(), HealthIndicator.class).addBinding();
}
private final static class InternalHealthModule extends AbstractModule {
@Provides
@Singleton
public HealthAggregatorConfiguration healthConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(HealthAggregatorConfiguration.class);
}
@Override
protected void configure() {
install(new GuavaApplicationEventModule());
requireBinding(Key.get(ConfigProxyFactory.class));
bind(HealthCheckAggregator.class).toProvider(HealthProvider.class).asEagerSingleton();
}
@Override
public boolean equals(Object obj) {
return getClass().equals(obj.getClass());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public String toString() {
return "InternalHealthModule[]";
}
}
private static class HealthProvider implements Provider<HealthCheckAggregator> {
@Inject(optional = true)
private Set<HealthIndicator> indicators;
@Inject
private HealthAggregatorConfiguration config;
@Inject
private ApplicationEventDispatcher dispatcher;
@Override
public HealthCheckAggregator get() {
if (indicators == null) {
indicators = Collections.emptySet();
}
if (config.cacheHealthIndicators()) {
return new DefaultCachingHealthCheckAggregator(new ArrayList<HealthIndicator>(indicators),
config.getCacheIntervalInMillis(), TimeUnit.MILLISECONDS, config.getAggregatorWaitIntervalInMillis(),
TimeUnit.MILLISECONDS, dispatcher);
} else {
return new SimpleHealthCheckAggregator(new ArrayList<HealthIndicator>(indicators),
config.getAggregatorWaitIntervalInMillis(), TimeUnit.MILLISECONDS, dispatcher);
}
}
}
}
| 2,174 |
0 | Create_ds/runtime-health/health-guice/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-guice/src/main/java/com/netflix/runtime/health/guice/HealthAggregatorConfiguration.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.runtime.health.guice;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.api.HealthIndicator;
@Configuration(prefix="health.aggregator")
public interface HealthAggregatorConfiguration {
/***
* Should health indicator results be cached between invocations.
*/
@DefaultValue("true")
boolean cacheHealthIndicators();
/***
* Number of milliseconds for which the {@link HealthCheckAggregator} should cache the response of
* any {@link HealthIndicator}.
*/
@DefaultValue("5000")
long getCacheIntervalInMillis();
/***
* Number of milliseconds for which the {@link HealthCheckAggregator} should wait for the response
* of any {@link HealthIndicator} before considering it as unhealthy and canceling invocation.
*/
@DefaultValue("1000")
long getAggregatorWaitIntervalInMillis();
}
| 2,175 |
0 | Create_ds/runtime-health/health-integrations/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/test/java/com/netflix/runtime/health/eureka/EurekaHealthStatusBridgeModuleTest.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.runtime.health.eureka;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.discovery.EurekaClient;
import com.netflix.governator.InjectorBuilder;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.core.HealthCheckStatusChangedEvent;
@RunWith(MockitoJUnitRunner.class)
public class EurekaHealthStatusBridgeModuleTest {
Injector injector;
@Mock ApplicationInfoManager infoManager;
@Mock EurekaClient eurekaClient;
@Mock HealthCheckAggregator healthCheckAggregator;
@Captor ArgumentCaptor<HealthCheckStatusChangedEvent> healthStatusChangedEventCaptor;
@Test
public void testHealthCheckHandlerRegistered() {
InjectorBuilder.fromModules(new EurekaHealthStatusBridgeModule(), new AbstractModule() {
@Override
protected void configure() {
bind(ApplicationInfoManager.class).toInstance(infoManager);
bind(EurekaClient.class).toInstance(eurekaClient);
bind(HealthCheckAggregator.class).toInstance(healthCheckAggregator);
}
}).createInjector();
Mockito.verify(eurekaClient, Mockito.times(1)).registerHealthCheck(Mockito.any(HealthCheckHandler.class));
}
}
| 2,176 |
0 | Create_ds/runtime-health/health-integrations/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/test/java/com/netflix/runtime/health/status/ArchaiusHealthStatusFilterModuleTest.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.runtime.health.status;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.Key;
import com.netflix.archaius.api.config.SettableConfig;
import com.netflix.archaius.api.inject.RuntimeLayer;
import com.netflix.archaius.guice.ArchaiusModule;
import com.netflix.governator.InjectorBuilder;
import com.netflix.governator.LifecycleInjector;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
import com.netflix.runtime.health.api.IndicatorMatcher;
public class ArchaiusHealthStatusFilterModuleTest {
private static class A implements HealthIndicator {
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
@Override
public String getName() {
return "A";
}
}
private static class B implements HealthIndicator {
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
@Override
public String getName() {
return "B";
}
}
private LifecycleInjector injector;
private SettableConfig config;
private IndicatorMatcher matcher;
@Before
public void init() {
injector = InjectorBuilder.fromModules(new ArchaiusModule(), new ArchaiusHealthStatusFilterModule()).createInjector();
config = injector.getInstance(Key.get(SettableConfig.class, RuntimeLayer.class));
matcher = injector.getInstance(IndicatorMatcher.class);
}
@Test
public void testDefault() {
assertTrue(matcher.matches(new A()));
assertTrue(matcher.matches(new B()));
}
@Test
public void testInclusion() {
config.setProperty("health.status.indicators.include", "A");
assertTrue(matcher.matches(new A()));
assertFalse(matcher.matches(new B()));
config.setProperty("health.status.indicators.include", "B");
assertFalse(matcher.matches(new A()));
assertTrue(matcher.matches(new B()));
config.setProperty("health.status.indicators.include", "A,B");
assertTrue(matcher.matches(new A()));
assertTrue(matcher.matches(new B()));
}
@Test
public void testExclusion() {
config.setProperty("health.status.indicators.exclude", "A");
assertFalse(matcher.matches(new A()));
assertTrue(matcher.matches(new B()));
config.setProperty("health.status.indicators.exclude", "B");
assertTrue(matcher.matches(new A()));
assertFalse(matcher.matches(new B()));
config.setProperty("health.status.indicators.exclude", "A,B");
assertFalse(matcher.matches(new A()));
assertFalse(matcher.matches(new B()));
}
@Test
public void testStringSplittingProducesNoWeirdEffects() {
config.setProperty("health.status.indicators.exclude", ",,A,,");
assertFalse(matcher.matches(new A()));
assertTrue(matcher.matches(new B()));
}
}
| 2,177 |
0 | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health/servlet/HealthStatusServlet.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.runtime.health.servlet;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.IndicatorMatcher;
import com.netflix.runtime.health.status.ArchaiusHealthStatusFilterModule;
@Singleton
public final class HealthStatusServlet extends HttpServlet {
private static final long serialVersionUID = -6518168654611266480L;
@Inject
private HealthCheckAggregator healthCheckAggregator;
/***
* See {@link ArchaiusHealthStatusFilterModule} for default implementation.
*/
@com.google.inject.Inject(optional=true)
private IndicatorMatcher matcher;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException {
HealthCheckStatus health;
try {
if(matcher != null ) {
health = this.healthCheckAggregator.check(matcher).get();
} else {
health = this.healthCheckAggregator.check().get();
}
} catch (Exception e) {
throw new ServletException(e);
}
if(health.isHealthy()) {
resp.setStatus(200);
}
else {
resp.setStatus(500);
}
String content = health.toString();
resp.setContentLength(content.length());
resp.setContentType("text/plain");
resp.getWriter().print(content);
}
}
| 2,178 |
0 | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health/eureka/EurekaStatusChangeEvent.java | package com.netflix.runtime.health.eureka;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.StatusChangeEvent;
import com.netflix.governator.event.ApplicationEvent;
public class EurekaStatusChangeEvent extends StatusChangeEvent implements ApplicationEvent {
public EurekaStatusChangeEvent(StatusChangeEvent event) {
this(event.getPreviousStatus(), event.getStatus());
}
public EurekaStatusChangeEvent(InstanceStatus previous, InstanceStatus current) {
super(previous, current);
}
} | 2,179 |
0 | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health/eureka/HealthAggregatorEurekaHealthCheckHandler.java | package com.netflix.runtime.health.eureka;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.IndicatorMatcher;
/**
* A Eureka HealthCheckHandler instance which consults a HealthAggregator for
* its status. This may be registered with a EurekaClient instance as follows:
*
* <pre>
* {@literal @}Inject
* EurekaClient eurekaClient;
* {@literal @}Inject
* HealthCheckAggregator healthCheckAggregator;
* {@literal @}Inject
* IndicatorMatcher matcher;
*
* {@literal @}PostConstruct
* public void init() {
* eurekaClient.registerHealthCheck(
new HealthAggregatorEurekaHealthCheckHandler(healthCheckAggregator, matcher));
* }
* </pre>
*/
public class HealthAggregatorEurekaHealthCheckHandler implements HealthCheckHandler {
private final HealthCheckAggregator healthCheckAggregator;
private final IndicatorMatcher matcher;
public HealthAggregatorEurekaHealthCheckHandler(HealthCheckAggregator healthCheckAggregator, IndicatorMatcher matcher) {
this.healthCheckAggregator = healthCheckAggregator;
this.matcher = matcher;
}
@Override
public InstanceStatus getStatus(InstanceStatus currentStatus) {
try {
if (matcher != null) {
return getInstanceStatusForHealth(healthCheckAggregator.check(matcher).get());
} else {
return getInstanceStatusForHealth(healthCheckAggregator.check().get());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private InstanceStatus getInstanceStatusForHealth(HealthCheckStatus health) {
if (health.isHealthy()) {
return InstanceStatus.UP;
} else {
return InstanceStatus.DOWN;
}
}
}
| 2,180 |
0 | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health/eureka/EurekaHealthStatusBridgeModule.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.runtime.health.eureka;
import java.util.concurrent.ExecutionException;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.ApplicationInfoManager.StatusChangeListener;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.StatusChangeEvent;
import com.netflix.governator.event.ApplicationEventDispatcher;
import com.netflix.governator.spi.LifecycleListener;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.IndicatorMatcher;
/**
* Installing this module couples Eureka status (UP/DOWN/STARTING) to {@link HealthCheckStatus}. After injector creation, Eureka will be provided
* with a {@link HealthCheckHandler} instance which delegates to
* {@link HealthCheckAggregator}. A "healthy" status will report UP and
* "unhealthy" will report DOWN in Eureka.
*
* Please note that prior to injector creation being completed, Eureka will
* remain at its default status of STARTING unless it is explicitly set
* otherwise.
*/
public class EurekaHealthStatusBridgeModule extends AbstractModule {
@Override
protected void configure() {
bind(EurekaHealthStatusInformingApplicationEventListener.class).asEagerSingleton();
}
private static class EurekaHealthStatusInformingApplicationEventListener implements LifecycleListener {
@com.google.inject.Inject(optional = true)
private Provider<ApplicationEventDispatcher> eventDispatcher;
@Inject
private Provider<ApplicationInfoManager> applicationInfoManager;
@Inject
private Provider<HealthCheckAggregator> healthCheckAggregator;
@Inject
private Provider<EurekaClient> eurekaClient;
/***
* See {@link com.netflix.runtime.health.status.ArchaiusHealthStatusFilterModule} for default implementation.
*/
@com.google.inject.Inject(optional=true)
private IndicatorMatcher matcher;
@PostConstruct
public void init() throws InterruptedException, ExecutionException {
if (eventDispatcher != null) {
applicationInfoManager.get().registerStatusChangeListener(new StatusChangeListener() {
@Override
public void notify(StatusChangeEvent statusChangeEvent) {
eventDispatcher.get().publishEvent(new EurekaStatusChangeEvent(statusChangeEvent));
}
@Override
public String getId() {
return "eurekaHealthStatusBridgeModuleStatusChangeListener";
}
});
}
}
@Override
public void onStarted() {
eurekaClient.get().registerHealthCheck(
new HealthAggregatorEurekaHealthCheckHandler(healthCheckAggregator.get(), matcher));
}
@Override
public void onStopped(Throwable error) {
}
}
@Override
public boolean equals(Object obj) {
return obj != null && getClass().equals(obj.getClass());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
| 2,181 |
0 | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health/status/HealthStatusInclusionConfiguration.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.runtime.health.status;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.PropertyName;
@Configuration(prefix="health.status.indicators")
public interface HealthStatusInclusionConfiguration {
@PropertyName(name="include")
String[] includedIndicators();
@PropertyName(name="exclude")
String[] excludedIndicators();
}
| 2,182 |
0 | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-integrations/src/main/java/com/netflix/runtime/health/status/ArchaiusHealthStatusFilterModule.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.runtime.health.status;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.IndicatorMatcher;
import com.netflix.runtime.health.api.IndicatorMatchers;
import com.netflix.runtime.health.eureka.EurekaHealthStatusBridgeModule;
import com.netflix.runtime.health.servlet.HealthStatusServlet;
/***
* Installing this module will provide an implementation of {@link IndicatorMatcher} backed by Archaius2.
* This {@link IndicatorMatcher} will be used by both the {@link EurekaHealthStatusBridgeModule} and
* the {@link HealthStatusServlet} to specify which {@link HealthIndicator}s will be used in
* determining the healthiness of your application.
*/
public class ArchaiusHealthStatusFilterModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
public HealthStatusInclusionConfiguration healthConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(HealthStatusInclusionConfiguration.class);
}
@Provides
@Singleton
public IndicatorMatcher IndicatorMatcher(HealthStatusInclusionConfiguration config) {
return new ArchaiusDrivenStatusFilter(config);
}
private static class ArchaiusDrivenStatusFilter implements IndicatorMatcher {
private final HealthStatusInclusionConfiguration config;
public ArchaiusDrivenStatusFilter(HealthStatusInclusionConfiguration config) {
this.config = config;
}
@Override
public boolean matches(HealthIndicator indicator) {
return IndicatorMatchers
.includes(config.includedIndicators())
.excludes(config.excludedIndicators()).build()
.matches(indicator);
}
}
@Override
public boolean equals(Object obj) {
return obj != null && getClass().equals(obj.getClass());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
| 2,183 |
0 | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health/core/SimpleHealthCheckAggregatorMetricsTest.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.runtime.health.core;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.netflix.governator.event.ApplicationEventDispatcher;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
import com.netflix.spectator.api.DefaultRegistry;
@RunWith(MockitoJUnitRunner.class)
public class SimpleHealthCheckAggregatorMetricsTest {
@Mock ApplicationEventDispatcher dispatcher;
DefaultRegistry registry;
SimpleHealthCheckAggregator aggregator;
@Before
public void init() {
this.registry = new DefaultRegistry();
}
static HealthIndicator nonResponsive = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
}
};
static HealthIndicator exceptional = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
throw new RuntimeException("Boom");
}
};
static HealthIndicator unhealthy = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.unhealthy().build());
}
};
static HealthIndicator healthy = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
};
@Test(timeout=1000)
public void testHealthyIsRecorded() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy), 1, TimeUnit.SECONDS, dispatcher, registry);
aggregator.check().get();
assertEquals(1, registry.counter("runtime.health", "status", "HEALTHY").count());
}
@Test(timeout=1000)
public void testUnHealthyIsRecorded() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(unhealthy), 1, TimeUnit.SECONDS, dispatcher, registry);
aggregator.check().get();
assertEquals(1, registry.counter("runtime.health", "status", "UNHEALTHY").count());
}
@Test(timeout=1000)
public void testTimeoutIsRecorded() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(nonResponsive), 50, TimeUnit.MILLISECONDS, dispatcher, registry);
aggregator.check().get();
assertEquals(1, registry.counter("runtime.health", "status", "TIMEOUT").count());
}
}
| 2,184 |
0 | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health/core/SimpleHealthCheckAggregatorTest.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.runtime.health.core;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
import com.netflix.runtime.health.api.IndicatorMatchers;
public class SimpleHealthCheckAggregatorTest {
SimpleHealthCheckAggregator aggregator;
static HealthIndicator nonResponsive = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
}
};
static HealthIndicator exceptional = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
throw new RuntimeException("Boom");
}
};
static HealthIndicator unhealthy = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.unhealthy().build());
}
};
static HealthIndicator healthy = new HealthIndicator() {
@Override
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
};
@Test(timeout=1000)
public void testEmptyListIsHealthy() throws Exception {
aggregator = new SimpleHealthCheckAggregator(new ArrayList<>(), 1, TimeUnit.SECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(0, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
@Test(timeout=1000)
public void testAllHealthy() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,healthy), 1, TimeUnit.SECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(2, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
@Test(timeout=1000)
public void testOneUnheathy() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,unhealthy), 1, TimeUnit.SECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertFalse(aggregatedHealth.isHealthy());
assertEquals(2, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
@Test(timeout=1000)
public void testAllUnheathy() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(unhealthy,unhealthy), 1, TimeUnit.SECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertFalse(aggregatedHealth.isHealthy());
assertEquals(2, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
@Test(timeout=1000)
public void testOneHealthyAndOneExceptional() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,exceptional), 1, TimeUnit.SECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertFalse(aggregatedHealth.isHealthy());
assertEquals(2, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
@Test(timeout=1000)
public void testOneHealthyAndOneNonResponsive() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,nonResponsive), 50, TimeUnit.MILLISECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertFalse(aggregatedHealth.isHealthy());
assertEquals(2, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
Health failed = aggregatedHealth.getHealthResults().stream().filter(h->!h.isHealthy()).findFirst().get();
assertNotNull(failed);
assertTrue(failed.getErrorMessage().isPresent());
assertEquals("java.util.concurrent.TimeoutException: Timed out waiting for response", failed.getErrorMessage().get());
}
@Test(timeout=1000)
public void testWithDetails() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(
(callback)->callback.inform(Health.healthy().withDetail("foo", "bar").build()),
(callback)->callback.inform(Health.unhealthy(new RuntimeException("Boom")).build())), 1, TimeUnit.SECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertFalse(aggregatedHealth.isHealthy());
assertEquals(2, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
List<Health> indicators = aggregator.check().get().getHealthResults();
assertThat(indicators).flatExtracting(s->s.getDetails().keySet()).contains("foo", "error");
assertThat(indicators).flatExtracting(s->s.getDetails().values()).contains("bar", "java.lang.RuntimeException: Boom");
}
@Test(timeout=1000)
public void testClassNameAdded() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,unhealthy,nonResponsive), 10, TimeUnit.MILLISECONDS);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertFalse(aggregatedHealth.isHealthy());
assertEquals(3, aggregatedHealth.getHealthResults().size());
assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
assertThat(aggregatedHealth.getHealthResults()).extracting(h->h.getDetails().get("className")).isNotNull();
}
@Test(timeout = 1000)
public void testIncludeFilterExcludes() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy, unhealthy), 10, TimeUnit.MILLISECONDS);
HealthCheckStatus aggregatedHealth = aggregator
.check(IndicatorMatchers.excludes(unhealthy.getName()).build()).get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(1, aggregatedHealth.getHealthResults().size());
assertEquals(1, aggregatedHealth.getSuppressedHealthResults().size());
assertThat(aggregatedHealth.getHealthResults()).extracting(h -> h.getDetails().get("className")).isNotNull();
}
@Test(timeout = 1000)
public void testIncludeFilterIncludes() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy, unhealthy, nonResponsive), 10, TimeUnit.MILLISECONDS);
HealthCheckStatus aggregatedHealth = aggregator
.check(IndicatorMatchers.includes(healthy.getName()).build()).get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(1, aggregatedHealth.getHealthResults().size());
assertEquals(2, aggregatedHealth.getSuppressedHealthResults().size());
assertThat(aggregatedHealth.getHealthResults()).extracting(h -> h.getDetails().get("className")).isNotNull();
}
@Test(timeout = 1000)
public void testIncludeFilterIncludesAndExcludes() throws Exception {
aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy, unhealthy, nonResponsive), 10, TimeUnit.MILLISECONDS);
HealthCheckStatus aggregatedHealth = aggregator
.check(IndicatorMatchers
.includes(healthy.getName(), unhealthy.getName())
.excludes(unhealthy.getName())
.build()).get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(1, aggregatedHealth.getHealthResults().size());
assertEquals(2, aggregatedHealth.getSuppressedHealthResults().size());
assertThat(aggregatedHealth.getHealthResults()).extracting(h -> h.getDetails().get("className")).isNotNull();
}
} | 2,185 |
0 | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health/core/SimpleHealthCheckAggregatorEventsTest.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.runtime.health.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.netflix.governator.event.ApplicationEventDispatcher;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
@RunWith(MockitoJUnitRunner.class)
public class SimpleHealthCheckAggregatorEventsTest {
@Mock ApplicationEventDispatcher dispatcher;
HealthIndicator changing;
@Before
public void setup() {
changing = new HealthIndicator() {
int counter = 0;
@Override
public void check(HealthIndicatorCallback healthCallback) {
if (counter++ == 0)
healthCallback.inform(Health.healthy().build());
else
healthCallback.inform(Health.unhealthy().build());
}
};
}
@Test(timeout = 1000)
public void testChangingHealthSendsFirstEventWhenNoListeners() throws Exception {
SimpleHealthCheckAggregator aggregator = new SimpleHealthCheckAggregator(Collections.emptyList(), 100, TimeUnit.SECONDS,dispatcher);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(0, aggregatedHealth.getHealthResults().size());
Thread.sleep(10);
Mockito.verify(dispatcher, Mockito.times(1)).publishEvent(Mockito.any());
}
@Test(timeout = 1000)
public void testChangingHealthSendsEvent() throws Exception {
SimpleHealthCheckAggregator aggregator = new SimpleHealthCheckAggregator(Arrays.asList(changing), 100, TimeUnit.SECONDS,dispatcher);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(1, aggregatedHealth.getHealthResults().size());
Thread.sleep(10);
Mockito.verify(dispatcher, Mockito.times(1)).publishEvent(Mockito.any());
aggregator.check().get();
Thread.sleep(10);
Mockito.verify(dispatcher, Mockito.times(2)).publishEvent(Mockito.any());
aggregator.check().get();
Thread.sleep(10);
Mockito.verifyNoMoreInteractions(dispatcher);
}
}
| 2,186 |
0 | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health/core | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health/core/caching/DefaultCachingHealthCheckAggregatorTest.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.runtime.health.core.caching;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
public class DefaultCachingHealthCheckAggregatorTest {
@Test(timeout=1000)
public void testCachedIndicatorNameNotHidden() throws Exception {
DefaultCachingHealthCheckAggregator aggregator = new DefaultCachingHealthCheckAggregator(
Arrays.asList(new TestHealthIndicator()), 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS, null);
HealthCheckStatus aggregatedHealth = aggregator.check().get();
assertTrue(aggregatedHealth.isHealthy());
assertEquals(1, aggregatedHealth.getHealthResults().size());
assertEquals(TestHealthIndicator.class.getName(), aggregatedHealth.getHealthResults().get(0).getDetails().get("className"));
}
private static class TestHealthIndicator implements HealthIndicator {
public void check(HealthIndicatorCallback healthCallback) {
healthCallback.inform(Health.healthy().build());
}
}
}
| 2,187 |
0 | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health/core | Create_ds/runtime-health/health-core/src/test/java/com/netflix/runtime/health/core/caching/CachingHealthIndicatorTest.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.runtime.health.core.caching;
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Before;
import org.junit.Test;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
public class CachingHealthIndicatorTest {
HealthIndicator testHealthIndicator;
AtomicLong realCount;
AtomicLong cachedCount;
@Before
public void init() {
realCount = new AtomicLong();
cachedCount = new AtomicLong();
this.testHealthIndicator = new HealthIndicator() {
long startTime = System.nanoTime();
@Override
public void check(HealthIndicatorCallback c) {
System.out.println("real call: " + (System.nanoTime() - startTime));
realCount.incrementAndGet();
c.inform(Health.healthy().build());
}
};
}
@Test
public void testWithoutCaching() {
for (int x = 0; x < 10; x++) {
testHealthIndicator.check(h -> cachedCount.incrementAndGet());
}
assertEquals(10, realCount.get());
assertEquals(10, cachedCount.get());
}
@Test
public void testWithCaching() {
CachingHealthIndicator cachedIndicator = CachingHealthIndicator.wrap(testHealthIndicator, 100,
TimeUnit.MILLISECONDS);
for (int x = 0; x < 10; x++) {
cachedIndicator.check(h -> {
cachedCount.incrementAndGet();
});
}
assertEquals(1, realCount.get());
assertEquals(10, cachedCount.get());
}
@Test
public void testWithCachingAndExpiry() throws InterruptedException {
CachingHealthIndicator cachedIndicator = CachingHealthIndicator.wrap(testHealthIndicator, 100,
TimeUnit.MILLISECONDS);
long startTime = System.nanoTime();
// first real call expected at +000ms, second at +100ms, third at +200ms
for (int x = 0; x < 10; x++) {
cachedIndicator.check(h -> {
System.out.println("cached call: " + (System.nanoTime() - startTime));
cachedCount.incrementAndGet();
});
Thread.sleep(25);
}
assertEquals(10, cachedCount.get());
assertEquals(3, realCount.get());
}
@Test
public void testValueActuallyCached() {
CachingHealthIndicator cachedIndicator = CachingHealthIndicator.wrap(testHealthIndicator, 100,
TimeUnit.MILLISECONDS);
CallbackShim firstHealth = new CallbackShim();
CallbackShim cachedHeath = new CallbackShim();
cachedIndicator.check(firstHealth);
cachedIndicator.check(cachedHeath);
assertEquals(firstHealth.status.isHealthy(), cachedHeath.status.isHealthy());
assertEquals(true, cachedHeath.status.getDetails().get("cached"));
}
private class CallbackShim implements HealthIndicatorCallback {
public Health status;
@Override
public void inform(Health status) {
this.status = status;
}
}
}
| 2,188 |
0 | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health/core/HealthCheckStatusChangedEvent.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.runtime.health.core;
import com.netflix.governator.event.ApplicationEvent;
import com.netflix.governator.event.EventListener;
import com.netflix.runtime.health.api.HealthCheckStatus;
/***
* An {@link ApplicationEvent} fired each team the overall health of an application changes.
* See @{@link EventListener} for details on how to consume.
*/
public class HealthCheckStatusChangedEvent implements ApplicationEvent {
private final HealthCheckStatus health;
public HealthCheckStatusChangedEvent(HealthCheckStatus health) {
this.health = health;
}
public HealthCheckStatus getHealth() {
return health;
}
}
| 2,189 |
0 | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health/core/SimpleHealthCheckAggregator.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.runtime.health.core;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.governator.event.ApplicationEventDispatcher;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthCheckAggregator;
import com.netflix.runtime.health.api.HealthCheckStatus;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
import com.netflix.runtime.health.api.IndicatorMatcher;
import com.netflix.runtime.health.api.IndicatorMatchers;
import com.netflix.spectator.api.Registry;
/**
*/
public class SimpleHealthCheckAggregator implements HealthCheckAggregator, Closeable {
private static final Logger LOG = LoggerFactory.getLogger(SimpleHealthCheckAggregator.class);
private static final int HEALTH_CHECK_EXECUTOR_POOL_SIZE = 3;
private final List<HealthIndicator> indicators;
private final ScheduledExecutorService scheduledExecutor;
private final ExecutorService healthCheckExecutor;
private final TimeUnit units;
private final long maxWaitTime;
private final ApplicationEventDispatcher eventDispatcher;
private final AtomicBoolean previousHealth;
private final Optional<Registry> registry;
public SimpleHealthCheckAggregator(List<HealthIndicator> indicators, long maxWaitTime, TimeUnit units) {
this(indicators, maxWaitTime, units, null);
}
public SimpleHealthCheckAggregator(List<HealthIndicator> indicators, long maxWaitTime, TimeUnit units,
ApplicationEventDispatcher eventDispatcher) {
this(indicators, maxWaitTime, units, eventDispatcher, null);
}
public SimpleHealthCheckAggregator(List<HealthIndicator> indicators, long maxWaitTime, TimeUnit units,
ApplicationEventDispatcher eventDispatcher, Registry registry) {
this.indicators = new ArrayList<>(indicators);
this.maxWaitTime = maxWaitTime;
this.units = units;
this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "healthIndicatorMonitor");
thread.setDaemon(true);
return thread;
}
});
this.healthCheckExecutor = Executors.newFixedThreadPool(HEALTH_CHECK_EXECUTOR_POOL_SIZE, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "healthIndicatorExecutor");
thread.setDaemon(true);
return thread;
}
});
this.eventDispatcher = eventDispatcher;
this.previousHealth = new AtomicBoolean();
this.registry = Optional.ofNullable(registry);
}
@Override
public CompletableFuture<HealthCheckStatus> check() {
return check(IndicatorMatchers.build());
}
public CompletableFuture<HealthCheckStatus> check(IndicatorMatcher matcher) {
final List<HealthIndicatorCallbackImpl> callbacks = new ArrayList<>(indicators.size());
final CompletableFuture<HealthCheckStatus> future = new CompletableFuture<HealthCheckStatus>();
final AtomicInteger counter = new AtomicInteger(indicators.size());
if (eventDispatcher != null) {
future.whenComplete((h, e) -> {
if (h != null && previousHealth.compareAndSet(!h.isHealthy(), h.isHealthy())) {
eventDispatcher.publishEvent(new HealthCheckStatusChangedEvent(h));
}
});
}
List<CompletableFuture<?>> futures = indicators.stream().map(indicator -> {
HealthIndicatorCallbackImpl callback = new HealthIndicatorCallbackImpl(indicator, !matcher.matches(indicator)) {
@Override
public void inform(Health status) {
setHealth(status);
if (counter.decrementAndGet() == 0) {
future.complete(getStatusFromCallbacks(callbacks));
}
}
};
callbacks.add(callback);
return CompletableFuture.runAsync(() -> {
try {
indicator.check(callback);
} catch (Exception ex) {
callback.inform(Health.unhealthy(ex).build());
}
}, healthCheckExecutor);
}).collect(Collectors.toList());
if(indicators.size() == 0) {
future.complete(HealthCheckStatus.create(true, Collections.emptyList()));
}
if (maxWaitTime != 0 && units != null) {
scheduledExecutor.schedule(new Runnable() {
@Override
public void run() {
future.complete(getStatusFromCallbacks(callbacks));
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).cancel(true);
}
}, maxWaitTime, units);
}
return doWithFuture(future);
}
protected CompletableFuture<HealthCheckStatus> doWithFuture(CompletableFuture<HealthCheckStatus> future) {
return future.whenComplete((status, error) -> {
if (status.getHealthResults().stream().filter(s -> s.getErrorMessage().orElse("").contains(TimeoutException.class.getName())).count() > 0) {
registry.ifPresent(r -> r.counter("runtime.health", "status", "TIMEOUT").increment());
} else {
registry.ifPresent(r -> r.counter("runtime.health", "status", status.isHealthy() ? "HEALTHY" : "UNHEALTHY").increment());
}
LOG.debug("Health Status: {}", status);
});
}
protected HealthCheckStatus getStatusFromCallbacks(final List<HealthIndicatorCallbackImpl> callbacks) {
List<Health> healths = new ArrayList<>();
List<Health> suppressedHealths = new ArrayList<>();
boolean isHealthy = callbacks.stream()
.map(callback -> {
Health health = Health.from(callback.getHealthOrTimeout())
.withDetail(Health.NAME_KEY, callback.getIndicator().getName()).build();
if(callback.isSuppressed()) {
suppressedHealths.add(health);
return Health.healthy().build();
} else {
healths.add(health);
return health;
}
})
.map(health -> health.isHealthy())
.reduce(true, (a,b) -> a && b);
return HealthCheckStatus.create(isHealthy, healths, suppressedHealths);
}
abstract class HealthIndicatorCallbackImpl implements HealthIndicatorCallback {
private volatile Health health;
private final HealthIndicator indicator;
private final boolean suppressed;
HealthIndicatorCallbackImpl(HealthIndicator indicator, boolean suppressed) {
this.indicator = indicator;
this.suppressed = suppressed;
}
void setHealth(Health health) {
this.health = health;
}
public Health getHealthOrTimeout() {
return health != null
? health
: Health
.unhealthy(new TimeoutException("Timed out waiting for response"))
.build();
}
public HealthIndicator getIndicator() {
return this.indicator;
}
public boolean isSuppressed() {
return this.suppressed;
}
}
@Override
public void close() throws IOException {
this.healthCheckExecutor.shutdown();
this.scheduledExecutor.shutdown();
}
} | 2,190 |
0 | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health/core | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health/core/caching/CachingHealthIndicator.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.runtime.health.core.caching;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.netflix.runtime.health.api.Health;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.api.HealthIndicatorCallback;
/**
* HealthIndicator wrapper implementation that caches the response
*
* @author elandau
*
*/
public class CachingHealthIndicator implements HealthIndicator {
private static class CacheEntry {
private final long expirationTime;
private final Health health;
CacheEntry(long expirationTime, Health health) {
super();
this.expirationTime = expirationTime;
this.health = health;
}
long getExpirationTime() {
return expirationTime;
}
Health getHealth() {
return health;
}
}
private final AtomicBoolean busy;
private final long interval;
private final HealthIndicator delegate;
private volatile CacheEntry cachedHealth;
private CachingHealthIndicator(HealthIndicator delegate, long interval, TimeUnit units) {
this.delegate = delegate;
this.interval = TimeUnit.NANOSECONDS.convert(interval, units);
this.busy = new AtomicBoolean(false);
this.cachedHealth = new CacheEntry(0L, null);
}
@Override
public void check(HealthIndicatorCallback callback) {
CacheEntry cacheEntry = this.cachedHealth;
long currentTime = System.nanoTime();
if (currentTime > cacheEntry.getExpirationTime()) {
if (busy.compareAndSet(false, true)) {
try {
delegate.check(h -> {
this.cachedHealth = new CacheEntry(currentTime + interval,
Health.from(h).withDetail(Health.CACHE_KEY, true).build());
callback.inform(h);
});
return;
} finally {
busy.set(false);
}
}
}
callback.inform(cacheEntry.getHealth());
}
public static CachingHealthIndicator wrap(HealthIndicator delegate, long interval, TimeUnit units) {
return new CachingHealthIndicator(delegate, interval, units);
}
public String getName() {
return delegate.getName();
}
}
| 2,191 |
0 | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health/core | Create_ds/runtime-health/health-core/src/main/java/com/netflix/runtime/health/core/caching/DefaultCachingHealthCheckAggregator.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.runtime.health.core.caching;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.netflix.governator.event.ApplicationEventDispatcher;
import com.netflix.runtime.health.api.HealthIndicator;
import com.netflix.runtime.health.core.SimpleHealthCheckAggregator;
public class DefaultCachingHealthCheckAggregator extends SimpleHealthCheckAggregator {
public DefaultCachingHealthCheckAggregator(List<HealthIndicator> indicators, long cacheInterval, TimeUnit cacheIntervalUnits,
long aggregatorWaitInterval, TimeUnit aggregatorWaitUnits, ApplicationEventDispatcher eventDispatcher) {
super(indicators.stream().map(delegate -> CachingHealthIndicator.wrap(delegate, cacheInterval, cacheIntervalUnits))
.collect(Collectors.toList()), aggregatorWaitInterval, aggregatorWaitUnits, eventDispatcher);
}
}
| 2,192 |
0 | Create_ds/PigPen/pigpen-parquet/src/main/java/pigpen | Create_ds/PigPen/pigpen-parquet/src/main/java/pigpen/parquet/PigPenParquetWriteSupport.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 pigpen.parquet;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import parquet.hadoop.api.WriteSupport;
import parquet.io.api.RecordConsumer;
import parquet.schema.MessageType;
import parquet.schema.MessageTypeParser;
import clojure.lang.IFn;
import clojure.lang.RT;
import clojure.lang.Symbol;
import clojure.lang.Var;
public class PigPenParquetWriteSupport extends WriteSupport<Map<String, Object>> {
private static final IFn WRITE;
static {
final Var require = RT.var("clojure.core", "require");
require.invoke(Symbol.intern("pigpen.parquet.core"));
WRITE = RT.var("pigpen.parquet.core", "write");
}
private RecordConsumer recordConsumer;
private MessageType rootSchema;
@Override
public WriteSupport.WriteContext init(final Configuration configuration) {
final String schema = configuration.get("schema");
this.rootSchema = MessageTypeParser.parseMessageType(schema);
return new WriteContext(this.rootSchema, new HashMap<String, String>());
}
@Override
public void prepareForWrite(final RecordConsumer recordConsumer) {
this.recordConsumer = recordConsumer;
}
@Override
public void write(final Map<String, Object> record) {
WRITE.invoke(this.recordConsumer, this.rootSchema, record);
}
}
| 2,193 |
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/OperationUtil.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 pigpen.cascading;
import org.apache.hadoop.io.BytesWritable;
import clojure.lang.IFn;
import clojure.lang.RT;
import clojure.lang.Symbol;
import clojure.lang.Var;
public class OperationUtil {
public static IFn getVar(final String name) {
final Var require = RT.var("clojure.core", "require");
require.invoke(Symbol.intern("pigpen.runtime"));
require.invoke(Symbol.intern("pigpen.cascading.runtime"));
return RT.var("pigpen.cascading.runtime", name);
}
public static byte[] getBytes(final BytesWritable bw) {
if (bw.getCapacity() == bw.getLength()) {
return bw.getBytes();
} else {
return copyBytes(bw);
}
}
public static byte[] copyBytes(final BytesWritable bw) {
final byte[] ret = new byte[bw.getLength()];
System.arraycopy(bw.getBytes(), 0, ret, 0, bw.getLength());
return ret;
}
}
| 2,194 |
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/InduceSentinelNils.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 pigpen.cascading;
import cascading.flow.FlowProcess;
import cascading.operation.BaseOperation;
import cascading.operation.Function;
import cascading.operation.FunctionCall;
import cascading.tuple.Fields;
import clojure.lang.IFn;
public class InduceSentinelNils extends BaseOperation implements Function {
private static final IFn INDUCE_NILS = OperationUtil.getVar("induce-sentinel-nil");
private final Integer index;
public InduceSentinelNils(final Integer index, final Fields fields) {
super(fields);
this.index = index;
}
@Override
public void operate(final FlowProcess flowProcess, final FunctionCall functionCall) {
INDUCE_NILS.invoke(functionCall, this.index);
}
}
| 2,195 |
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/SingleIterationSeq.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 pigpen.cascading;
import java.io.IOException;
import java.io.NotSerializableException;
import java.util.Iterator;
import clojure.lang.ASeq;
import clojure.lang.IPersistentMap;
import clojure.lang.ISeq;
/**
* This sequence behaves like a normal iterator-seq up to a certain size.
* If the max size is exceeded, it will only allow one iteration. The objective
* is to become immune to memory problems resulting from holding onto the head for
* large collections but still support operations such as count, max, etc.
*/
public class SingleIterationSeq extends ASeq {
private static int MAX_SIZE = 1000;
private final Iterator iter;
private final State state;
private static class State {
volatile Object val;
volatile Object rest;
volatile int index;
}
public static SingleIterationSeq create(Iterator iter) {
return create(iter, 0);
}
private static SingleIterationSeq create(Iterator iter, int index) {
if (iter.hasNext()) {
return new SingleIterationSeq(iter, index);
}
return null;
}
private SingleIterationSeq(Iterator iter, int index) {
this.iter = iter;
state = new State();
this.state.val = state;
this.state.rest = state;
this.state.index = index;
}
private SingleIterationSeq(IPersistentMap meta, Iterator iter, State state) {
super(meta);
this.iter = iter;
this.state = state;
}
public Object first() {
if (state.val == state) {
synchronized (state) {
if (state.val == state) {
state.val = iter.next();
}
}
}
return state.val;
}
public ISeq next() {
if (state.rest == state) {
synchronized (state) {
if (state.rest == state) {
first();
if (state.index < MAX_SIZE) {
state.rest = create(iter, state.index + 1);
return (ISeq)state.rest;
} else {
state.rest = iter;
return create(iter, state.index + 1);
}
}
}
}
if (state.rest == iter) {
throw new UnsupportedOperationException("This Seq can only be traversed once.");
}
return (ISeq)state.rest;
}
public SingleIterationSeq withMeta(IPersistentMap meta) {
return new SingleIterationSeq(meta, iter, state);
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
throw new NotSerializableException(getClass().getName());
}
}
| 2,196 |
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/PigPenFunction.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 pigpen.cascading;
import cascading.flow.FlowProcess;
import cascading.operation.BaseOperation;
import cascading.operation.Function;
import cascading.operation.FunctionCall;
import cascading.operation.OperationCall;
import cascading.tuple.Fields;
import clojure.lang.IFn;
public class PigPenFunction extends BaseOperation implements Function {
private static final IFn PREPARE = OperationUtil.getVar("prepare");
private static final IFn OPERATE = OperationUtil.getVar("function-operate");
private final String context;
public PigPenFunction(final String context, final Fields fields) {
super(fields);
this.context = context;
}
@Override
public void prepare(final FlowProcess flowProcess, final OperationCall operationCall) {
super.prepare(flowProcess, operationCall);
operationCall.setContext(PREPARE.invoke(this.context));
}
@Override
public void operate(final FlowProcess flowProcess, final FunctionCall functionCall) {
OPERATE.invoke(functionCall);
}
}
| 2,197 |
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/RankBuffer.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 pigpen.cascading;
import java.util.Iterator;
import cascading.flow.FlowProcess;
import cascading.operation.BaseOperation;
import cascading.operation.Buffer;
import cascading.operation.BufferCall;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
public class RankBuffer extends BaseOperation implements Buffer {
public RankBuffer(Fields fields) {
super(fields);
}
@Override
public void operate(FlowProcess flowProcess, BufferCall bufferCall) {
int rank = 0;
Iterator<TupleEntry> iterator = bufferCall.getArgumentsIterator();
while (iterator.hasNext()) {
TupleEntry entry = iterator.next();
bufferCall.getOutputCollector().add(new Tuple(rank++, entry.getObject(0)));
}
}
}
| 2,198 |
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/GroupBuffer.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 pigpen.cascading;
import cascading.flow.FlowProcess;
import cascading.operation.BaseOperation;
import cascading.operation.Buffer;
import cascading.operation.BufferCall;
import cascading.operation.OperationCall;
import cascading.tuple.Fields;
import clojure.lang.IFn;
public class GroupBuffer extends BaseOperation implements Buffer {
private static final IFn PREPARE = OperationUtil.getVar("prepare");
private static final IFn OPERATE = OperationUtil.getVar("group-operate");
private final String context;
public GroupBuffer(final String context, final Fields fields) {
super(fields);
this.context = context;
}
@Override
public void prepare(final FlowProcess flowProcess, final OperationCall operationCall) {
super.prepare(flowProcess, operationCall);
operationCall.setContext(PREPARE.invoke(this.context));
}
@Override
public void operate(final FlowProcess flowProcess, final BufferCall bufferCall) {
OPERATE.invoke(bufferCall);
}
}
| 2,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.