1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.ui.framework.ioc;
35
36 import info.magnolia.objectfactory.annotation.LazySingleton;
37
38 import java.lang.annotation.Annotation;
39 import java.util.ArrayList;
40 import java.util.List;
41 import java.util.Objects;
42
43 import javax.inject.Singleton;
44
45 import com.google.inject.AbstractModule;
46 import com.google.inject.Key;
47 import com.google.inject.Module;
48 import com.google.inject.binder.ScopedBindingBuilder;
49 import com.google.inject.internal.Scoping;
50 import com.google.inject.spi.Element;
51 import com.google.inject.spi.Elements;
52
53
54
55
56
57
58
59
60
61
62
63
64
65 final class RebindUiComponentScopes extends AbstractModule {
66
67 private final Module sourceModule;
68
69 RebindUiComponentScopes(Module sourceModule) {
70 this.sourceModule = sourceModule;
71 }
72
73 @Override
74 @SuppressWarnings("unchecked")
75 protected void configure() {
76 final List<Element> elements = Elements.getElements(sourceModule);
77 final List<Element> elementsToWrite = new ArrayList<>(elements);
78
79 GuiceSpi.getBindings(elements).forEach(binding -> {
80 final Scoping scoping = GuiceSpi.resolveScope(binding);
81
82 if (scoping == null) {
83 return;
84 }
85
86 final Class<? extends Annotation> scopeAnnotation = scoping.getScopeAnnotation();
87
88 if (isSingletonScopeAnnotation(scopeAnnotation)) {
89 boolean isEagerSingleton = isEagerSingletonAnnotation(scopeAnnotation);
90 final UiContextAnnotation uiContextAnnotation = UiAnnotations.cast(binding.getKey().getAnnotation());
91 final Class<? extends Annotation> relatedScopeAnnotation = uiContextAnnotation.getRelatedScopeAnnotation(isEagerSingleton);
92
93 if (!Objects.equals(relatedScopeAnnotation, scopeAnnotation)) {
94 elementsToWrite.remove(binding);
95 final Key key = binding.getKey();
96 GuiceSpi.<ScopedBindingBuilder>inspect(binding)
97 .onLinkedBinding(linkedKeyBinding -> bind(key).to(linkedKeyBinding.getLinkedKey()))
98 .onProviderKeyBinding(providerBinding -> bind(key).toProvider(providerBinding.getProviderKey()))
99 .visit()
100 .ifPresent(scopedBindingBuilder -> scopedBindingBuilder.in(relatedScopeAnnotation));
101 }
102 }
103 });
104
105 elementsToWrite.forEach(element -> element.applyTo(binder()));
106 }
107
108 private boolean isEagerSingletonAnnotation(Class<? extends Annotation> scopeAnnotation) {
109 return scopeAnnotation.equals(Singleton.class) || scopeAnnotation.equals(com.google.inject.Singleton.class);
110 }
111
112 private boolean isSingletonScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
113 return Objects.equals(scopeAnnotation, Singleton.class) ||
114 Objects.equals(scopeAnnotation, com.google.inject.Singleton.class) ||
115 Objects.equals(scopeAnnotation, LazySingleton.class);
116 }
117 }
118