001 /*
002 * Copyright 2008-2015 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.env.Lifecycle;
031 import griffon.core.event.EventHandler;
032 import griffon.core.injection.Injector;
033 import griffon.core.mvc.MVCGroupConfiguration;
034 import griffon.core.resources.ResourceInjector;
035 import griffon.util.ServiceLoaderUtils;
036 import org.codehaus.griffon.runtime.core.controller.NoopActionManager;
037 import org.slf4j.Logger;
038 import org.slf4j.LoggerFactory;
039
040 import javax.annotation.Nonnull;
041 import javax.annotation.Nullable;
042 import javax.annotation.concurrent.GuardedBy;
043 import javax.inject.Inject;
044 import java.beans.PropertyEditor;
045 import java.beans.PropertyEditorManager;
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 EventHandler eventHandler = application.getInjector().getInstance(EventHandler.class);
132 application.getEventRouter().addEventListener(eventHandler);
133 }
134
135 protected void event(@Nonnull ApplicationEvent event, @Nullable List<?> args) {
136 application.getEventRouter().publishEvent(event.getName(), args);
137 }
138
139 protected void initializePropertyEditors() {
140 ServiceLoaderUtils.load(applicationClassLoader().get(), "META-INF/editors/", PropertyEditor.class, new ServiceLoaderUtils.LineProcessor() {
141 @Override
142 public void process(@Nonnull ClassLoader classLoader, @Nonnull Class<?> type, @Nonnull String line) {
143 try {
144 String[] parts = line.trim().split("=");
145 Class<?> targetType = loadClass(parts[0].trim(), classLoader);
146 Class<?> editorClass = loadClass(parts[1].trim(), classLoader);
147
148 // Editor must have a no-args constructor
149 // CCE means the class can not be used
150 editorClass.newInstance();
151 PropertyEditorManager.registerEditor(targetType, editorClass);
152 LOG.debug("Registering {} as editor for {}", editorClass.getName(), targetType.getName());
153 } catch (Exception e) {
154 if (LOG.isWarnEnabled()) {
155 LOG.warn("Could not load " + type.getName() + " with " + line, sanitize(e));
156 }
157 }
158 }
159 });
160
161 Class<?>[][] pairs = new Class<?>[][]{
162 new Class<?>[]{Boolean.class, Boolean.TYPE},
163 new Class<?>[]{Byte.class, Byte.TYPE},
164 new Class<?>[]{Short.class, Short.TYPE},
165 new Class<?>[]{Integer.class, Integer.TYPE},
166 new Class<?>[]{Long.class, Long.TYPE},
167 new Class<?>[]{Float.class, Float.TYPE},
168 new Class<?>[]{Double.class, Double.TYPE}
169 };
170
171 for (Class<?>[] pair : pairs) {
172 PropertyEditor editor = PropertyEditorManager.findEditor(pair[0]);
173 LOG.debug("Registering {} as editor for {}", editor.getClass().getName(), pair[1].getName());
174 PropertyEditorManager.registerEditor(pair[1], editor.getClass());
175 }
176 }
177
178 protected void initializeResourcesInjector() {
179 final ResourceInjector injector = application.getResourceInjector();
180 application.getEventRouter().addEventListener(ApplicationEvent.NEW_INSTANCE.getName(), new RunnableWithArgs() {
181 public void run(@Nullable Object... args) {
182 Object instance = args[1];
183 injector.injectResources(instance);
184 }
185 });
186 }
187
188 protected void initializeArtifactManager() {
189 Injector<?> injector = application.getInjector();
190 ArtifactManager artifactManager = application.getArtifactManager();
191 for (ArtifactHandler<?> artifactHandler : injector.getInstances(ArtifactHandler.class)) {
192 artifactManager.registerArtifactHandler(artifactHandler);
193 }
194 artifactManager.loadArtifactMetadata();
195 }
196
197 protected void applyPlatformTweaks() {
198 PlatformHandler platformHandler = application.getInjector().getInstance(PlatformHandler.class);
199 platformHandler.handle(application);
200 }
201
202 protected void initializeAddonManager() {
203 application.getAddonManager().initialize();
204 }
205
206 @SuppressWarnings("unchecked")
207 protected void initializeMvcManager() {
208 Map<String, MVCGroupConfiguration> configurations = new LinkedHashMap<>();
209 Map<String, Map<String, Object>> mvcGroups = application.getConfiguration().get("mvcGroups", Collections.<String, Map<String, Object>>emptyMap());
210 if (mvcGroups != null) {
211 for (Map.Entry<String, Map<String, Object>> groupEntry : mvcGroups.entrySet()) {
212 String type = groupEntry.getKey();
213 LOG.debug("Adding MVC group {}", type);
214 Map<String, Object> members = groupEntry.getValue();
215 Map<String, Object> configMap = new LinkedHashMap<>();
216 Map<String, String> membersCopy = new LinkedHashMap<>();
217 for (Map.Entry<String, Object> entry : members.entrySet()) {
218 String key = String.valueOf(entry.getKey());
219 if ("config".equals(key) && entry.getValue() instanceof Map) {
220 configMap = (Map<String, Object>) entry.getValue();
221 } else {
222 membersCopy.put(key, String.valueOf(entry.getValue()));
223 }
224 }
225 configurations.put(type, application.getMvcGroupManager().newMVCGroupConfiguration(type, membersCopy, configMap));
226 }
227 }
228
229 application.getMvcGroupManager().initialize(configurations);
230 }
231
232 protected void initializeActionManager() {
233 if (application.getActionManager() instanceof NoopActionManager) {
234 return;
235 }
236
237 application.getEventRouter().addEventListener(ApplicationEvent.NEW_INSTANCE.getName(), new RunnableWithArgs() {
238 public void run(@Nullable Object... args) {
239 Class<?> klass = (Class) args[0];
240 if (GriffonController.class.isAssignableFrom(klass)) {
241 GriffonController controller = (GriffonController) args[1];
242 application.getActionManager().createActions(controller);
243 }
244 }
245 });
246
247 Injector<?> injector = application.getInjector();
248 Collection<ActionHandler> handlerInstances = injector.getInstances(ActionHandler.class);
249 List<String> handlerOrder = application.getConfiguration().get(KEY_GRIFFON_CONTROLLER_ACTION_HANDLER_ORDER, Collections.<String>emptyList());
250 Map<String, ActionHandler> sortedHandlers = sortByDependencies(handlerInstances, ActionHandler.SUFFIX, "handler", handlerOrder);
251
252 for (ActionHandler handler : sortedHandlers.values()) {
253 application.getActionManager().addActionHandler(handler);
254 }
255
256 Collection<ActionInterceptor> interceptorInstances = injector.getInstances(ActionInterceptor.class);
257 if (!interceptorInstances.isEmpty()) {
258 application.getLog().error(ActionInterceptor.class.getName() + " have been deprecated and is no longer supported");
259 throw new UnsupportedOperationException(ActionInterceptor.class.getName() + " have been deprecated and is no longer supported");
260 }
261 }
262
263 protected Class<?> loadClass(@Nonnull String className, @Nonnull ClassLoader classLoader) throws ClassNotFoundException {
264 ClassNotFoundException cnfe;
265
266 ClassLoader cl = DefaultApplicationConfigurer.class.getClassLoader();
267 try {
268 return cl.loadClass(className);
269 } catch (ClassNotFoundException e) {
270 cnfe = e;
271 }
272
273 cl = classLoader;
274 try {
275 return cl.loadClass(className);
276 } catch (ClassNotFoundException e) {
277 cnfe = e;
278 }
279
280 throw cnfe;
281 }
282
283 private ApplicationClassLoader applicationClassLoader() {
284 return application.getInjector().getInstance(ApplicationClassLoader.class);
285 }
286 }
|