Permalink
Browse files

introduce DeactivationFactoryMachine to easily deactivate components

  • Loading branch information...
xhanin committed Dec 21, 2014
1 parent c0bb9e6 commit 189179aba3e1b35db3c24b5f37557a6ec6307f86
@@ -0,0 +1,64 @@
+package restx.factory;
+
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.util.Set;
+
+public class DeactivationFactoryMachine implements FactoryMachine {
+
+ public static DeactivationFactoryMachine forNames(Iterable<Name<?>> names) {
+ return new DeactivationFactoryMachine(names);
+ }
+
+ public static DeactivationFactoryMachine forNames(Name<?>... names) {
+ return new DeactivationFactoryMachine(Lists.newArrayList(names));
+ }
+
+ private final ImmutableSet<String> keys;
+
+ public DeactivationFactoryMachine(Iterable<Name<?>> keys) {
+ this.keys = ImmutableSet.copyOf(Iterables.transform(keys, new Function<Name<?>, String>() {
+ @Override
+ public String apply(Name<?> input) {
+ return Factory.activationKey(input.getClazz(), input.getName());
+ }
+ }));
+ }
+
+ @Override
+ public boolean canBuild(Name<?> name) {
+ return name.getClazz() == String.class && keys.contains(name.getName());
+ }
+
+ @Override
+ public <T> MachineEngine<T> getEngine(Name<T> name) {
+ return new NoDepsMachineEngine<T>(name, priority(), BoundlessComponentBox.FACTORY) {
+ @Override
+ protected T doNewComponent(SatisfiedBOM satisfiedBOM) {
+ return (T) "false";
+ }
+ };
+ }
+
+ @Override
+ public <T> Set<Name<T>> nameBuildableComponents(Class<T> componentClass) {
+ if (componentClass != String.class) {
+ return ImmutableSet.of();
+ }
+ return Sets.newLinkedHashSet(Iterables.transform(keys, new Function<String, Name<T>>() {
+ @Override
+ public Name<T> apply(String input) {
+ return (Name<T>) Name.of(String.class, input);
+ }
+ }));
+ }
+
+ @Override
+ public int priority() {
+ return -10000;
+ }
+}
@@ -0,0 +1,20 @@
+package restx.factory;
+
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class DeactivationFactoryMachineTest {
+ @Test
+ public void should_deactivate_components() throws Exception {
+ Name<Integer> one = Name.of(Integer.class, "one");
+ Name<Integer> two = Name.of(Integer.class, "two");
+ Factory factory = Factory.builder()
+ .addMachine(new SingletonFactoryMachine<>(0, new NamedComponent(one, 1)))
+ .addMachine(new SingletonFactoryMachine<>(0, new NamedComponent(two, 2)))
+ .addMachine(DeactivationFactoryMachine.forNames(one))
+ .build();
+
+ assertThat(factory.getComponents(Integer.class)).containsExactly(2);
+ }
+}

0 comments on commit 189179a

Please sign in to comment.