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.framework.UiFrameworkView;
41  import info.magnolia.ui.framework.ViewContext;
42  import info.magnolia.ui.framework.ViewContextBase;
43  import info.magnolia.ui.framework.ViewContextProxy;
44  
45  import java.util.Arrays;
46  import java.util.Map;
47  import java.util.Objects;
48  import java.util.Optional;
49  import java.util.stream.Collectors;
50  
51  import javax.inject.Provider;
52  
53  /**
54   * Looks-up instances in {@link BeanStore session bean stores}. Search starts
55   * at the bean store linked to the current view and may propagate to all the parents.
56   *
57   * If the searched parameter type implements {@link ViewContext}, the resolved instance is
58   * wrapped into a memory-leak safe-guard proxy, which will unsubscribe all the context listeners
59   * once the current view is destroyed.
60   *
61   * @see UiFrameworkView
62   * @see ViewComponentProvider
63   * @see SessionStore
64   */
65  class ViewContextParameterResolver implements ParameterResolver {
66  
67      private final static Class[] BLACK_LIST = new Class[] { Provider.class, com.google.inject.Provider.class };
68  
69      private final UiContextReference uiContextReference;
70  
71      ViewContextParameterResolver(UiContextReference uiContextReference) {
72          this.uiContextReference = uiContextReference;
73      }
74  
75      @Override
76      @SuppressWarnings("unchecked")
77      public Object resolveParameter(ParameterInfo parameter) {
78          final Class<?> parameterType = parameter.getParameterType();
79  
80          // Check whether the type that is being resolved is not blacklisted. E.g. we blacklist the IoC provider objects,
81          // because they might end up in the bean store (via Guice scoping) and they might be accidentally accessed by this
82          // parameter resolver, but the wrong one might be chosen as suitable candidate (due to the erasure of the generic info) and
83          // it is generally better to let the Guice parameter resolver to take care of providers.
84          boolean isBlackListed = Arrays.stream(BLACK_LIST).anyMatch(blackListedType -> blackListedType.isAssignableFrom(parameterType));
85          if (isBlackListed) {
86              return ParameterResolver.UNRESOLVED;
87          }
88  
89          return lookup(parameterType);
90      }
91  
92      private Object lookup(Class<?> parameterType) {
93          final BeanStore beanStore = SessionStore.access().getBeanStore(uiContextReference);
94          final Optional<Object> valueFromCurrentStore = Optional.ofNullable(beanStore.getClosestInstance(parameterType));
95  
96          final Object param = valueFromCurrentStore.orElseGet(() -> uiContextReference.getParentReferences().stream()
97                  .map(parentRef -> SessionStore.access().getBeanStore(parentRef))
98                  .map(parentStore -> parentStore.getClosestInstance(parameterType))
99                  .filter(Objects::nonNull)
100                 .findFirst()
101                 .map(parameter -> parameter instanceof ViewContext ? wrapViewContext((ViewContext) parameter) : parameter)
102                 .orElse(ParameterResolver.UNRESOLVED));
103 
104         if ((param instanceof ViewContext) && !valueFromCurrentStore.isPresent()) {
105             final ViewContext wrappedViewContext = wrapViewContext((ViewContext) param);
106             beanStore.put(parameterType, wrappedViewContext);
107             return wrappedViewContext;
108         }
109 
110         return param;
111     }
112 
113     private ViewContext wrapViewContext(ViewContext viewContext) {
114         final ViewContextBase baseViewContext = (ViewContextBase) viewContext;
115         final Map<String, ContextProperty> properties = baseViewContext.properties();
116         final Map<String, ContextProperty> wrappedProperties =
117                         properties.entrySet()
118                         .stream()
119                         .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
120                             final ContextProperty<?> contextProperty = entry.getValue();
121                             return new LeakagePreventingWrapper<>(contextProperty);
122                         }));
123 
124         return new ViewContextProxy().createViewContext(baseViewContext.getViewContextType(), wrappedProperties);
125     }
126 }