View Javadoc
1   /**
2    * This file Copyright (c) 2017-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.event.EventBus;
37  import info.magnolia.objectfactory.Components;
38  
39  import java.lang.annotation.Annotation;
40  import java.util.HashSet;
41  import java.util.List;
42  import java.util.Objects;
43  import java.util.Set;
44  
45  import com.google.inject.Key;
46  import com.google.inject.Provider;
47  import com.google.inject.Scope;
48  
49  /**
50   * Provides the support for eagerly created scoped instances.
51   * <p>
52   * Wraps another {@link SessionStoreScope} and when a {@link BeanStore} that corresponds to that scope is created
53   * all the instances regsitered for this scope will be created (and => cached in the parent scope).
54   * </p>
55   *
56   * @see BeanStoreLifecycleEvent.Create
57   */
58  class EagerSessionStoreScope extends SessionStoreScope {
59  
60      private final Set<Key> eagerSingletons = new HashSet<>();
61  
62      private final SessionStoreScope delegate;
63  
64      EagerSessionStoreScope(SessionStoreScope delegate, EventBus eventBus, UiScopes allUiScopes) {
65          this.delegate = delegate;
66  
67          eventBus.addHandler(BeanStoreLifecycleEvent.Create.class, event -> {
68              final UiContextReference relatedContextKey = event.getRelatedContextKey();
69              final Scope relatedScope = allUiScopes.getScope(relatedContextKey.getAnnotation().getRelatedScopeAnnotation(true));
70              if (Objects.equals(this, relatedScope)) {
71                  CurrentUiContextReference.get().executeInContext(this::createEagerSingletons, relatedContextKey);
72              }
73          });
74      }
75  
76      @Override
77      protected UiContextReference getCurrentContextKey() {
78          return this.delegate.getCurrentContextKey();
79      }
80  
81      @Override
82      public <T> Provider<T> scope(Key<T> key, Provider<T> creator) {
83          this.eagerSingletons.add(key);
84          return super.scope(key, creator);
85      }
86  
87      @Override
88      public boolean isEager() {
89          return true;
90      }
91  
92      private void createEagerSingletons() {
93          final List<UiContextReference> availableContextKeys = CurrentUiContextReference.get().getAvailableContextReferences();
94          for (final Key<?> singletonKey : eagerSingletons) {
95              // We need to ensure that the instance of the type actually needs to be eagerly initialised in _current_ context.
96              // Example of when we should _not_ try to create an instance:
97              // - current context is e.g. app 'FOO'
98              // - the key is bound with annotation relevant to app 'BAR'
99              // - the current scope may be the eager app scope, but the binding is not relevant in current context
100 
101             // If binding is not annotated with Ui context annotation - means that it is not picky about the
102             // current UI context and always needs to be initialised;
103             boolean isUiContextAgnostic = !(singletonKey.getAnnotation() instanceof UiContextAnnotation);
104             // Otherwise we make sure that the binding is relevant to the current context
105             boolean shouldEagerlyInitialise = isUiContextAgnostic || matchingUiContextKeyExists(availableContextKeys, singletonKey.getAnnotation());
106 
107             if (shouldEagerlyInitialise) {
108                 if (singletonKey.getAnnotation() == null) {
109                     Components.getComponent(singletonKey.getTypeLiteral().getRawType());
110                 } else {
111                     Components.getComponentWithAnnotation(singletonKey.getTypeLiteral().getRawType(), singletonKey.getAnnotation());
112                 }
113             }
114         }
115     }
116 
117     /**
118      * Goes over a list of the UI context keys and determines whether there is such a key, whose annotation
119      * is exactly the same as the one provided. E.g. the key might be bound to an {@link info.magnolia.ui.api.ioc.App @App}
120      * annotation and the provided sample annotation is also @App, but the App#name() values are different, then there is no
121      * match!
122      */
123     private boolean matchingUiContextKeyExists(List<UiContextReference> availableContextKeys, Annotation bindingAnnotation) {
124         return availableContextKeys.stream().anyMatch(uiContextKey -> Objects.equals(bindingAnnotation, uiContextKey.getAnnotation()));
125     }
126 
127     @Override
128     public String toString() {
129         return String.format("Eager %s", this.delegate.toString());
130     }
131 }