DefaultApplicationConfigurer.java
001 /*
002  * Copyright 2008-2016 the original author or authors.
003  *
004  * Licensed under the Apache License, Version 2.0 (the "License");
005  * you may not use this file except in compliance with the License.
006  * You may obtain a copy of the License at
007  *
008  *     http://www.apache.org/licenses/LICENSE-2.0
009  *
010  * Unless required by applicable law or agreed to in writing, software
011  * distributed under the License is distributed on an "AS IS" BASIS,
012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013  * See the License for the specific language governing permissions and
014  * limitations under the License.
015  */
016 package org.codehaus.griffon.runtime.core;
017 
018 import griffon.core.ApplicationClassLoader;
019 import griffon.core.ApplicationConfigurer;
020 import griffon.core.ApplicationEvent;
021 import griffon.core.GriffonApplication;
022 import griffon.core.LifecycleHandler;
023 import griffon.core.PlatformHandler;
024 import griffon.core.RunnableWithArgs;
025 import griffon.core.artifact.ArtifactHandler;
026 import griffon.core.artifact.ArtifactManager;
027 import griffon.core.artifact.GriffonController;
028 import griffon.core.controller.ActionHandler;
029 import griffon.core.controller.ActionInterceptor;
030 import griffon.core.editors.PropertyEditorResolver;
031 import griffon.core.env.Lifecycle;
032 import griffon.core.event.EventHandler;
033 import griffon.core.injection.Injector;
034 import griffon.core.mvc.MVCGroupConfiguration;
035 import griffon.core.resources.ResourceInjector;
036 import griffon.util.ServiceLoaderUtils;
037 import org.codehaus.griffon.runtime.core.controller.NoopActionManager;
038 import org.slf4j.Logger;
039 import org.slf4j.LoggerFactory;
040 
041 import javax.annotation.Nonnull;
042 import javax.annotation.Nullable;
043 import javax.annotation.concurrent.GuardedBy;
044 import javax.inject.Inject;
045 import java.beans.PropertyEditor;
046 import java.util.Collection;
047 import java.util.Collections;
048 import java.util.LinkedHashMap;
049 import java.util.List;
050 import java.util.Map;
051 
052 import static griffon.core.GriffonExceptionHandler.sanitize;
053 import static griffon.util.AnnotationUtils.named;
054 import static griffon.util.AnnotationUtils.sortByDependencies;
055 import static java.util.Arrays.asList;
056 import static java.util.Objects.requireNonNull;
057 
058 /**
059  * Utility class for bootstrapping an application.
060  *
061  @author Danno Ferrin
062  @author Andres Almiray
063  */
064 public class DefaultApplicationConfigurer implements ApplicationConfigurer {
065     private static final Logger LOG = LoggerFactory.getLogger(DefaultApplicationConfigurer.class);
066 
067     private static final String ERROR_APPLICATION_NULL = "Argument 'application' must not be null";
068     private static final String KEY_APP_LIFECYCLE_HANDLER_DISABLE = "application.lifecycle.handler.disable";
069     private static final String KEY_GRIFFON_CONTROLLER_ACTION_HANDLER_ORDER = "griffon.controller.action.handler.order";
070 
071     private final Object lock = new Object();
072     private final GriffonApplication application;
073     @GuardedBy("lock")
074     private boolean initialized;
075 
076     @Inject
077     public DefaultApplicationConfigurer(@Nonnull GriffonApplication application) {
078         this.application = requireNonNull(application, ERROR_APPLICATION_NULL);
079     }
080 
081     @Override
082     public final void init() {
083         synchronized (lock) {
084             if (!initialized) {
085                 doInitialize();
086                 initialized = true;
087             }
088         }
089     }
090 
091     @Override
092     public void runLifecycleHandler(@Nonnull Lifecycle lifecycle) {
093         requireNonNull(lifecycle, "Argument 'lifecycle' must not be null");
094 
095         boolean skipHandler = application.getConfiguration().getAsBoolean(KEY_APP_LIFECYCLE_HANDLER_DISABLE, false);
096         if (skipHandler) {
097             LOG.info("Lifecycle handler '{}' has been disabled. SKIPPING.", lifecycle.getName());
098             return;
099         }
100 
101         LifecycleHandler handler;
102         try {
103             handler = application.getInjector().getInstance(LifecycleHandler.class, named(lifecycle.getName()));
104         catch (Exception e) {
105             // the script must not exist, do nothing
106             //LOGME - may be because of chained failures
107             return;
108         }
109 
110         handler.execute();
111     }
112 
113     protected void doInitialize() {
114         initializeEventHandler();
115 
116         event(ApplicationEvent.BOOTSTRAP_START, asList(application));
117 
118         initializePropertyEditors();
119         initializeResourcesInjector();
120         runLifecycleHandler(Lifecycle.INITIALIZE);
121         applyPlatformTweaks();
122         initializeAddonManager();
123         initializeMvcManager();
124         initializeActionManager();
125         initializeArtifactManager();
126 
127         event(ApplicationEvent.BOOTSTRAP_END, asList(application));
128     }
129 
130     protected void initializeEventHandler() {
131         Collection<EventHandler> handlerInstances =  application.getInjector().getInstances(EventHandler.class);
132         Map<String, EventHandler> sortedHandlers = sortByDependencies(handlerInstances, "EventHandler""handler");
133         for (EventHandler handler : sortedHandlers.values()) {
134             application.getEventRouter().addEventListener(handler);
135         }
136     }
137 
138     protected void event(@Nonnull ApplicationEvent event, @Nullable List<?> args) {
139         application.getEventRouter().publishEvent(event.getName(), args);
140     }
141 
142     protected void initializePropertyEditors() {
143         ServiceLoaderUtils.load(applicationClassLoader().get()"META-INF/editors/", PropertyEditor.class, new ServiceLoaderUtils.LineProcessor() {
144             @Override
145             @SuppressWarnings("unchecked")
146             public void process(@Nonnull ClassLoader classLoader, @Nonnull Class<?> type, @Nonnull String line) {
147                 try {
148                     String[] parts = line.trim().split("=");
149                     Class<?> targetType = loadClass(parts[0].trim(), classLoader);
150                     Class<? extends PropertyEditor> editorClass = (Class<? extends PropertyEditor>loadClass(parts[1].trim(), classLoader);
151 
152                     // Editor must have a no-args constructor
153                     // CCE means the class can not be used
154                     editorClass.newInstance();
155                     PropertyEditorResolver.registerEditor(targetType, editorClass);
156                     LOG.debug("Registering {} as editor for {}", editorClass.getName(), targetType.getName());
157                 catch (Exception e) {
158                     if (LOG.isWarnEnabled()) {
159                         LOG.warn("Could not load " + type.getName() " with " + line, sanitize(e));
160                     }
161                 }
162             }
163         });
164 
165         Class<?>[][] pairs = new Class<?>[][]{
166             new Class<?>[]{Boolean.class, Boolean.TYPE},
167             new Class<?>[]{Byte.class, Byte.TYPE},
168             new Class<?>[]{Short.class, Short.TYPE},
169             new Class<?>[]{Integer.class, Integer.TYPE},
170             new Class<?>[]{Long.class, Long.TYPE},
171             new Class<?>[]{Float.class, Float.TYPE},
172             new Class<?>[]{Double.class, Double.TYPE}
173         };
174 
175         for (Class<?>[] pair : pairs) {
176             PropertyEditor editor = PropertyEditorResolver.findEditor(pair[0]);
177             LOG.debug("Registering {} as editor for {}", editor.getClass().getName(), pair[1].getName());
178             PropertyEditorResolver.registerEditor(pair[1], editor.getClass());
179         }
180     }
181 
182     protected void initializeResourcesInjector() {
183         final ResourceInjector injector = application.getResourceInjector();
184         application.getEventRouter().addEventListener(ApplicationEvent.NEW_INSTANCE.getName()new RunnableWithArgs() {
185             public void run(@Nullable Object... args) {
186                 injector.injectResources(args[1]);
187             }
188         });
189     }
190 
191     protected void initializeArtifactManager() {
192         Injector<?> injector = application.getInjector();
193         ArtifactManager artifactManager = application.getArtifactManager();
194         for (ArtifactHandler<?> artifactHandler : injector.getInstances(ArtifactHandler.class)) {
195             artifactManager.registerArtifactHandler(artifactHandler);
196         }
197         artifactManager.loadArtifactMetadata();
198     }
199 
200     protected void applyPlatformTweaks() {
201         PlatformHandler platformHandler = application.getInjector().getInstance(PlatformHandler.class);
202         platformHandler.handle(application);
203     }
204 
205     protected void initializeAddonManager() {
206         application.getAddonManager().initialize();
207     }
208 
209     @SuppressWarnings("unchecked")
210     protected void initializeMvcManager() {
211         Map<String, MVCGroupConfiguration> configurations = new LinkedHashMap<>();
212         Map<String, Map<String, Object>> mvcGroups = application.getConfiguration().get("mvcGroups", Collections.<String, Map<String, Object>>emptyMap());
213         if (mvcGroups != null) {
214             for (Map.Entry<String, Map<String, Object>> groupEntry : mvcGroups.entrySet()) {
215                 String type = groupEntry.getKey();
216                 LOG.debug("Adding MVC group {}", type);
217                 Map<String, Object> members = groupEntry.getValue();
218                 Map<String, Object> configMap = new LinkedHashMap<>();
219                 Map<String, String> membersCopy = new LinkedHashMap<>();
220                 for (Map.Entry<String, Object> entry : members.entrySet()) {
221                     String key = String.valueOf(entry.getKey());
222                     if ("config".equals(key&& entry.getValue() instanceof Map) {
223                         configMap = (Map<String, Object>entry.getValue();
224                     else {
225                         membersCopy.put(key, String.valueOf(entry.getValue()));
226                     }
227                 }
228                 configurations.put(type, application.getMvcGroupManager().newMVCGroupConfiguration(type, membersCopy, configMap));
229             }
230         }
231 
232         application.getMvcGroupManager().initialize(configurations);
233     }
234 
235     protected void initializeActionManager() {
236         if (application.getActionManager() instanceof NoopActionManager) {
237             return;
238         }
239 
240         application.getEventRouter().addEventListener(ApplicationEvent.NEW_INSTANCE.getName()new RunnableWithArgs() {
241             public void run(@Nullable Object... args) {
242                 Class<?> klass = (Classargs[0];
243                 if (GriffonController.class.isAssignableFrom(klass)) {
244                     application.getActionManager().createActions((GriffonControllerargs[1]);
245                 }
246             }
247         });
248 
249         Injector<?> injector = application.getInjector();
250         Collection<ActionHandler> handlerInstances = injector.getInstances(ActionHandler.class);
251         List<String> handlerOrder = application.getConfiguration().get(KEY_GRIFFON_CONTROLLER_ACTION_HANDLER_ORDER, Collections.<String>emptyList());
252         Map<String, ActionHandler> sortedHandlers = sortByDependencies(handlerInstances, ActionHandler.SUFFIX, "handler", handlerOrder);
253 
254         for (ActionHandler handler : sortedHandlers.values()) {
255             application.getActionManager().addActionHandler(handler);
256         }
257 
258         Collection<ActionInterceptor> interceptorInstances = injector.getInstances(ActionInterceptor.class);
259         if (!interceptorInstances.isEmpty()) {
260             application.getLog().error(ActionInterceptor.class.getName() " has been deprecated and is no longer supported");
261             throw new UnsupportedOperationException(ActionInterceptor.class.getName() " has been deprecated and is no longer supported");
262         }
263     }
264 
265     protected Class<?> loadClass(@Nonnull String className, @Nonnull ClassLoader classLoaderthrows ClassNotFoundException {
266         ClassNotFoundException cnfe;
267 
268         ClassLoader cl = DefaultApplicationConfigurer.class.getClassLoader();
269         try {
270             return cl.loadClass(className);
271         catch (ClassNotFoundException e) {
272             cnfe = e;
273         }
274 
275         cl = classLoader;
276         try {
277             return cl.loadClass(className);
278         catch (ClassNotFoundException e) {
279             cnfe = e;
280         }
281 
282         throw cnfe;
283     }
284 
285     private ApplicationClassLoader applicationClassLoader() {
286         return application.getInjector().getInstance(ApplicationClassLoader.class);
287     }
288 }