View Javadoc
1   /**
2    * This file Copyright (c) 2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.ui.framework.ioc;
35  
36  import info.magnolia.objectfactory.ParameterInfo;
37  import info.magnolia.objectfactory.ParameterResolver;
38  import info.magnolia.ui.framework.ContextProperty;
39  import info.magnolia.ui.framework.LeakagePreventingWrapper;
40  import info.magnolia.ui.UIComponent;
41  import info.magnolia.ui.framework.UiComponentContext;
42  import info.magnolia.ui.framework.UiComponentContextBase;
43  import info.magnolia.ui.framework.UiComponentContextProxy;
44  
45  import java.lang.annotation.Annotation;
46  import java.util.Arrays;
47  import java.util.Map;
48  import java.util.Objects;
49  import java.util.Optional;
50  import java.util.stream.Collectors;
51  
52  import javax.inject.Named;
53  import javax.inject.Provider;
54  
55  import com.google.inject.BindingAnnotation;
56  
57  /**
58   * Looks-up instances in {@link BeanStore session bean stores}. Search starts
59   * at the bean store linked to the current view and may propagate to all the parents.
60   *
61   * If the searched parameter type implements {@link UiComponentContext}, the resolved instance is
62   * wrapped into a memory-leak safe-guard proxy, which will unsubscribe all the context listeners
63   * once the current view is destroyed.
64   *
65   * @see UIComponent
66   * @see UiComponentProvider
67   * @see SessionStore
68   */
69  class UiComponentContextParameterResolver implements ParameterResolver {
70  
71      private final static Class[] BLACK_LIST = new Class[] { Provider.class, com.google.inject.Provider.class };
72  
73      private final UiContextReference uiContextReference;
74  
75      UiComponentContextParameterResolver(UiContextReference uiContextReference) {
76          this.uiContextReference = uiContextReference;
77      }
78  
79      @Override
80      @SuppressWarnings("unchecked")
81      public Object resolveParameter(ParameterInfo parameter) {
82          // If the parameter is annotated with a Guice binding annotation (or javax.inject.Named which is of the same sort - do not attempt to resolve it
83          // and let Guice param resolver handle the case. Most obvious case is the EventBus which is present in pretty much every view's store and would
84          // be resolved by this parameter, but it conflicts with our Named annotation based approach of "scoping" the event buses.
85          if (Arrays.stream(parameter.getParameterAnnotations()).anyMatch(this::isIocRelatedAnnotation)) {
86              return UNRESOLVED;
87          }
88  
89          final Class<?> parameterType = parameter.getParameterType();
90  
91          // Check whether the type that is being resolved is not blacklisted. E.g. we blacklist the IoC provider objects,
92          // because they might end up in the bean store (via Guice scoping) and they might be accidentally accessed by this
93          // parameter resolver, but the wrong one might be chosen as suitable candidate (due to the erasure of the generic info) and
94          // it is generally better to let the Guice parameter resolver to take care of providers.
95          boolean isBlackListed = Arrays.stream(BLACK_LIST).anyMatch(blackListedType -> blackListedType.isAssignableFrom(parameterType));
96          if (isBlackListed) {
97              return ParameterResolver.UNRESOLVED;
98          }
99  
100         return lookup(parameterType);
101     }
102 
103     private boolean isIocRelatedAnnotation(Annotation annotation) {
104         return annotation instanceof Named || Arrays.stream(annotation.annotationType().getAnnotations()).anyMatch(BindingAnnotation.class::isInstance);
105     }
106 
107     private Object lookup(Class<?> parameterType) {
108         final BeanStore beanStore = SessionStore.access().getBeanStore(uiContextReference);
109         final Optional<Object> valueFromCurrentStore = Optional.ofNullable(beanStore.getClosestInstance(parameterType));
110 
111         final Object param = valueFromCurrentStore.orElseGet(() -> resolveInstanceInParentBeanStores(parameterType).orElseGet(() -> {
112             if (UiComponentContext.class.isAssignableFrom(parameterType)) {
113                 return createNewContext((Class) parameterType);
114             }
115 
116             return UNRESOLVED;
117         }));
118 
119         if ((param instanceof UiComponentContext) && !valueFromCurrentStore.isPresent()) {
120             final UiComponentContextiComponentContext.html#UiComponentContext">UiComponentContext wrappedContext = wrapUiComponentContext((UiComponentContext) param);
121             beanStore.put(parameterType, wrappedContext);
122             return wrappedContext;
123         }
124 
125         return param;
126     }
127 
128     private <T extends UiComponentContext> T createNewContext(Class<T> contextType) {
129         final T context = new UiComponentContextProxy().createUiComponentContext(contextType);
130         SessionStore.access().getBeanStore(uiContextReference).put(contextType, context);
131         return context;
132     }
133 
134     private Optional<Object> resolveInstanceInParentBeanStores(Class<?> parameterType) {
135         return uiContextReference.getParentReferences().stream()
136                 .map(parentRef -> SessionStore.access().getBeanStore(parentRef))
137                 .filter(Objects::nonNull)
138                 .map(parentStore -> parentStore.getClosestInstance(parameterType))
139                 .filter(Objects::nonNull)
140                 .findFirst()
141                 .map(parameter -> parameter instanceof UiComponentContext/ui/framework/UiComponentContext.html#UiComponentContext">UiComponentContext ? wrapUiComponentContext((UiComponentContext) parameter) : parameter);
142     }
143 
144     private UiComponentContextlia/ui/framework/UiComponentContext.html#UiComponentContext">UiComponentContext wrapUiComponentContext(UiComponentContext uiComponentContext) {
145         final UiComponentContextBaseagnolia/ui/framework/UiComponentContextBase.html#UiComponentContextBase">UiComponentContextBase baseContext = (UiComponentContextBase) uiComponentContext;
146         final Map<String, ContextProperty> properties = baseContext.properties();
147         final Map<String, ContextProperty> wrappedProperties =
148                         properties.entrySet()
149                         .stream()
150                         .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
151                             final ContextProperty<?> contextProperty = entry.getValue();
152                             return new LeakagePreventingWrapper<>(contextProperty);
153                         }));
154 
155         return new UiComponentContextProxy().createUiComponentContext(baseContext.getUiComponentContextType(), wrappedProperties);
156     }
157 }