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 static java.util.stream.Collectors.toList;
37  
38  import info.magnolia.event.EventBus;
39  import info.magnolia.event.SystemEventBus;
40  import info.magnolia.module.ModuleRegistry;
41  import info.magnolia.objectfactory.ComponentProvider;
42  import info.magnolia.objectfactory.Components;
43  import info.magnolia.objectfactory.configuration.ComponentConfigurer;
44  import info.magnolia.objectfactory.configuration.ComponentProviderConfiguration;
45  import info.magnolia.objectfactory.guice.GuiceComponentConfigurationModule;
46  import info.magnolia.objectfactory.guice.GuiceComponentProvider;
47  import info.magnolia.objectfactory.guice.GuiceComponentProviderBuilder;
48  import info.magnolia.objectfactory.guice.GuiceContextAndScopesConfigurer;
49  import info.magnolia.ui.api.app.AppDescriptor;
50  import info.magnolia.ui.api.app.registry.AppDescriptorRegistry;
51  
52  import java.util.List;
53  import java.util.function.Supplier;
54  
55  import javax.inject.Inject;
56  import javax.inject.Named;
57  import javax.inject.Singleton;
58  
59  import com.google.inject.Module;
60  import com.google.inject.util.Modules;
61  import com.vaadin.server.VaadinServlet;
62  
63  /**
64   * Decorates the {@link GuiceComponentConfigurationModule} with several necessary workarounds and adds {@link UiBaseModule}
65   * to the pile.
66   *
67   * Implementation note: this class takes measures to create only one instance of the UI Guice component provider. There should
68   * be only one such component provider by design, which be pushed into {@link Components} context when UI requests are handled.
69   *
70   * Having multiple built copies of UI component providers may lead to conflicts in their provisioning logic and some other quirky
71   * bugs. The weakest part is the presence of two UI servlets ({@link VaadinServlet} and legacy {@link AdmincentralServlet}
72   * until the latter is finally eliminated) which may end up with two different component provider instances. Besides, creating
73   * several instances of pretty much identical heavy component providers adds several seconds of build time overhead.
74   */
75  @Singleton
76  public class MagnoliaUiGuiceComponentProviderFactory {
77  
78      private final EventBus systemEventBus;
79      private final ModuleRegistry moduleRegistry;
80      private final Supplier<List<String>> appNameListSupplier;
81  
82      // see class JavaDoc for the reasoning behind having a single instance of the component provider
83      private GuiceComponentProvider instance;
84  
85      @Inject
86      MagnoliaUiGuiceComponentProviderFactory(@Named(SystemEventBus.NAME) EventBus systemEventBus, ModuleRegistry moduleRegistry, AppDescriptorRegistry appDescriptorRegistry) {
87          this(systemEventBus, moduleRegistry, () -> appDescriptorRegistry.getAllDefinitions().stream().map(AppDescriptor::getName).collect(toList()));
88      }
89  
90      public MagnoliaUiGuiceComponentProviderFactory(EventBus systemEventBus, ModuleRegistry moduleRegistry, Supplier<List<String>> appNameListSupplier) {
91          this.systemEventBus = systemEventBus;
92          this.moduleRegistry = moduleRegistry;
93          this.appNameListSupplier = appNameListSupplier;
94      }
95  
96      /**
97       * Populates all the UI-related components and type-mappings from all the modules,
98       * processes them and creates a {@link GuiceComponentProvider} out of them.
99       *
100      * @param
101      *      additionalModules mostly for test purposes, allow to supply the type bindings
102      *      programmatically instead of XML (see {@link info.magnolia.objectfactory.guice.AbstractGuiceComponentConfigurer})
103      * @return
104      *      all-in-one Guice component provider for UI
105      */
106     public GuiceComponentProvider create(ComponentConfigurer... additionalModules) {
107         if (instance != null) {
108             return instance;
109         }
110 
111         final ComponentProvider parentComponentProvider = Components.getComponentProvider();
112 
113         // This is a bit unfortunate workaround: we hijack an instance of ComponentProviderConfiguration to populate the
114         // component configs, but we don't use it to create a component provider as is, because the collected component
115         // configurations need to undergo certain processing (see logic below).
116         //
117         // We rather take all the collected component configs, process them and 'squash' into one Guice module.
118         final ComponentProviderConfiguration collectedComponentBindings =
119                 new UiComponentConfigurationAggregator(moduleRegistry.getModuleDefinitions(), appNameListSupplier.get()).aggregate();
120 
121         // Add implicit configurers
122         for (ComponentConfigurer configurer : additionalModules) {
123             collectedComponentBindings.addConfigurer(configurer);
124         }
125 
126         // Allow configurers to customize the configuration before we use it
127         for (ComponentConfigurer configurer : collectedComponentBindings.getConfigurers()) {
128             configurer.doWithConfiguration(parentComponentProvider, collectedComponentBindings);
129         }
130 
131         // Process the collected component bindings, add the UiBaseModule to the mix
132         final Module uiGuiceModule =
133                 Modules.combine(
134                         new UiBaseModule(systemEventBus),
135                         new DeflateUiContextDependentBindings(
136                                 new ProduceNewInstancesWithComponentProvider(
137                                         new EliminateRedundantSingletonAnnotations(
138                                                 new RebindUiComponentScopes(
139                                                         new GuiceComponentConfigurationModule(collectedComponentBindings))))));
140 
141         final GuiceComponentProviderBuilder guiceComponentProviderBuilder = new GuiceComponentProviderBuilder();
142 
143         if (parentComponentProvider instanceof GuiceComponentProvider) {
144             guiceComponentProviderBuilder.withParent((GuiceComponentProvider) parentComponentProvider);
145         }
146 
147         // Create an empty component provider configuration
148         final ComponentProviderConfiguration componentProviderConfig = new ComponentProviderConfiguration();
149 
150         // copy the type mappings over to the new configuration
151         collectedComponentBindings.getAnnotatedTypeMappings().forEach(componentProviderConfig::addTypeMapping);
152         guiceComponentProviderBuilder.withConfiguration(componentProviderConfig);
153 
154         // add the squashed UI components as an extra module
155         guiceComponentProviderBuilder.addModule(uiGuiceModule);
156 
157         this.instance = guiceComponentProviderBuilder.build(new GuiceContextAndScopesConfigurer());
158         
159         return instance;
160     }
161 }