001 /*
002 * Copyright 2008-2014 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 griffon.swing;
017
018 import griffon.core.*;
019 import griffon.core.addon.AddonManager;
020 import griffon.core.artifact.ArtifactManager;
021 import griffon.core.controller.ActionManager;
022 import griffon.core.env.ApplicationPhase;
023 import griffon.core.env.Lifecycle;
024 import griffon.core.event.EventRouter;
025 import griffon.core.i18n.MessageSource;
026 import griffon.core.injection.Injector;
027 import griffon.core.mvc.MVCGroupManager;
028 import griffon.core.resources.ResourceHandler;
029 import griffon.core.resources.ResourceInjector;
030 import griffon.core.resources.ResourceResolver;
031 import griffon.core.threading.UIThreadManager;
032 import griffon.core.view.WindowManager;
033 import org.codehaus.griffon.runtime.core.MVCGroupExceptionHandler;
034 import org.slf4j.Logger;
035 import org.slf4j.LoggerFactory;
036
037 import javax.annotation.Nonnull;
038 import javax.annotation.Nullable;
039 import javax.swing.JApplet;
040 import java.util.ArrayList;
041 import java.util.Arrays;
042 import java.util.List;
043 import java.util.Locale;
044 import java.util.concurrent.CountDownLatch;
045
046 import static griffon.util.AnnotationUtils.named;
047 import static griffon.util.GriffonApplicationUtils.parseLocale;
048 import static java.util.Arrays.asList;
049 import static java.util.Objects.requireNonNull;
050
051 /**
052 * Base implementation of {@code GriffonApplication} that runs in applet mode.
053 *
054 * @author Andres Almiray
055 * @since 2.0.0
056 */
057 public abstract class AbstractGriffonApplet extends JApplet implements GriffonApplication {
058 private static final long serialVersionUID = -3489610863053527695L;
059
060 private static final String ERROR_SHUTDOWN_HANDLER_NULL = "Argument 'shutdownHandler' must not be null";
061 private Locale locale = Locale.getDefault();
062 public static final String[] EMPTY_ARGS = new String[0];
063 protected final Object[] lock = new Object[0];
064 private ApplicationPhase phase = ApplicationPhase.INITIALIZE;
065
066 private final List<ShutdownHandler> shutdownHandlers = new ArrayList<>();
067 private final String[] startupArgs;
068 private final Object shutdownLock = new Object();
069 private final Logger log;
070 private Injector<?> injector;
071
072 public AbstractGriffonApplet() {
073 this(EMPTY_ARGS);
074 }
075
076 public AbstractGriffonApplet(@Nonnull String[] args) {
077 startupArgs = new String[args.length];
078 System.arraycopy(args, 0, startupArgs, 0, args.length);
079 log = LoggerFactory.getLogger(getClass());
080 }
081
082 // ------------------------------------------------------
083
084 public void init() {
085 initialize();
086 startup();
087 }
088
089 public void start() {
090 ready();
091 }
092
093 public void stop() {
094 event(ApplicationEvent.STOP_START, asList(this));
095 getApplicationConfigurer().runLifecycleHandler(Lifecycle.STOP);
096 event(ApplicationEvent.STOP_END, asList(this));
097 }
098
099 public void destroy() {
100 shutdown();
101 }
102
103 // ------------------------------------------------------
104
105 public void setInjector(@Nonnull Injector<?> injector) {
106 this.injector = requireNonNull(injector, "Argument 'injector' cannot be bull");
107 this.injector.injectMembers(this);
108 addShutdownHandler(getWindowManager());
109 MVCGroupExceptionHandler.registerWith(this);
110 }
111
112 @Nonnull
113 public Locale getLocale() {
114 return locale;
115 }
116
117 @Nonnull
118 public String[] getStartupArgs() {
119 return startupArgs;
120 }
121
122 @Nonnull
123 public Logger getLog() {
124 return log;
125 }
126
127 public void setLocaleAsString(@Nullable String locale) {
128 setLocale(parseLocale(locale));
129 }
130
131 public void setLocale(@Nonnull Locale locale) {
132 Locale oldValue = this.locale;
133 this.locale = locale;
134 Locale.setDefault(locale);
135 firePropertyChange(PROPERTY_LOCALE, oldValue, locale);
136 }
137
138 public void addShutdownHandler(@Nonnull ShutdownHandler handler) {
139 requireNonNull(handler, ERROR_SHUTDOWN_HANDLER_NULL);
140 if (!shutdownHandlers.contains(handler)) shutdownHandlers.add(handler);
141 }
142
143 public void removeShutdownHandler(@Nonnull ShutdownHandler handler) {
144 requireNonNull(handler, ERROR_SHUTDOWN_HANDLER_NULL);
145 shutdownHandlers.remove(handler);
146 }
147
148 @Nonnull
149 public ApplicationPhase getPhase() {
150 synchronized (lock) {
151 return this.phase;
152 }
153 }
154
155 protected void setPhase(@Nonnull ApplicationPhase phase) {
156 requireNonNull(phase, "Argument 'phase' must not be null");
157 synchronized (lock) {
158 firePropertyChange(PROPERTY_PHASE, this.phase, this.phase = phase);
159 }
160 }
161
162 @Nonnull
163 @Override
164 public ApplicationClassLoader getApplicationClassLoader() {
165 return injector.getInstance(ApplicationClassLoader.class);
166 }
167
168 @Nonnull
169 @Override
170 public Configuration getConfiguration() {
171 return injector.getInstance(Configuration.class);
172 }
173
174 @Nonnull
175 @Override
176 public UIThreadManager getUIThreadManager() {
177 return injector.getInstance(UIThreadManager.class);
178 }
179
180 @Nonnull
181 @Override
182 public EventRouter getEventRouter() {
183 return injector.getInstance(EventRouter.class, named("applicationEventRouter"));
184 }
185
186 @Nonnull
187 @Override
188 public ArtifactManager getArtifactManager() {
189 return injector.getInstance(ArtifactManager.class);
190 }
191
192 @Nonnull
193 @Override
194 public ActionManager getActionManager() {
195 return injector.getInstance(ActionManager.class);
196 }
197
198 @Nonnull
199 @Override
200 public AddonManager getAddonManager() {
201 return injector.getInstance(AddonManager.class);
202 }
203
204 @Nonnull
205 @Override
206 public MVCGroupManager getMvcGroupManager() {
207 return injector.getInstance(MVCGroupManager.class);
208 }
209
210 @Nonnull
211 @Override
212 public MessageSource getMessageSource() {
213 return injector.getInstance(MessageSource.class, named("applicationMessageSource"));
214 }
215
216 @Nonnull
217 @Override
218 public ResourceResolver getResourceResolver() {
219 return injector.getInstance(ResourceResolver.class, named("applicationResourceResolver"));
220 }
221
222 @Nonnull
223 @Override
224 public ResourceHandler getResourceHandler() {
225 return injector.getInstance(ResourceHandler.class);
226 }
227
228 @Nonnull
229 @Override
230 public ResourceInjector getResourceInjector() {
231 return injector.getInstance(ResourceInjector.class, named("applicationResourceInjector"));
232 }
233
234 @Nonnull
235 @Override
236 public Injector<?> getInjector() {
237 return injector;
238 }
239
240 @Nonnull
241 @Override
242 @SuppressWarnings("unchecked")
243 public <W> WindowManager<W> getWindowManager() {
244 return injector.getInstance(WindowManager.class);
245 }
246
247 protected ApplicationConfigurer getApplicationConfigurer() {
248 return injector.getInstance(ApplicationConfigurer.class);
249 }
250
251 public void initialize() {
252 if (getPhase() == ApplicationPhase.INITIALIZE) {
253 getApplicationConfigurer().init();
254 }
255 }
256
257 public void ready() {
258 if (getPhase() != ApplicationPhase.STARTUP) return;
259
260 showStartingWindow();
261
262 setPhase(ApplicationPhase.READY);
263 event(ApplicationEvent.READY_START, asList(this));
264
265 getApplicationConfigurer().runLifecycleHandler(Lifecycle.READY);
266 event(ApplicationEvent.READY_END, asList(this));
267 setPhase(ApplicationPhase.MAIN);
268 }
269
270 protected void showStartingWindow() {
271 Object startingWindow = getWindowManager().getStartingWindow();
272 if (startingWindow != null) {
273 getWindowManager().show(startingWindow);
274 }
275 }
276
277 public boolean canShutdown() {
278 event(ApplicationEvent.SHUTDOWN_REQUESTED, asList(this));
279 synchronized (shutdownLock) {
280 for (ShutdownHandler handler : shutdownHandlers) {
281 if (!handler.canShutdown(this)) {
282 event(ApplicationEvent.SHUTDOWN_ABORTED, asList(this));
283 if (log.isDebugEnabled()) {
284 try {
285 log.debug("Shutdown aborted by " + handler);
286 } catch (UnsupportedOperationException uoe) {
287 log.debug("Shutdown aborted by a handler");
288 }
289 }
290 return false;
291 }
292 }
293 }
294 return true;
295 }
296
297 public boolean shutdown() {
298 // avoids reentrant calls to shutdown()
299 // once permission to quit has been granted
300 if (getPhase() == ApplicationPhase.SHUTDOWN) return false;
301
302 if (!canShutdown()) return false;
303 log.info("Shutdown is in process");
304
305 // signal that shutdown is in process
306 setPhase(ApplicationPhase.SHUTDOWN);
307
308 // stage 1 - alert all app event handlers
309 // wait for all handlers to complete before proceeding
310 // with stage #2 if and only if the current thread is
311 // the ui thread
312 log.debug("Shutdown stage 1: notify all event listeners");
313 if (getEventRouter().isEventPublishingEnabled()) {
314 final CountDownLatch latch = new CountDownLatch(getUIThreadManager().isUIThread() ? 1 : 0);
315 getEventRouter().addEventListener(ApplicationEvent.SHUTDOWN_START.getName(), new CallableWithArgs<Void>() {
316 @Override
317 @Nullable
318 public Void call(@Nullable Object... args) {
319 latch.countDown();
320 return null;
321 }
322 });
323 event(ApplicationEvent.SHUTDOWN_START, asList(this));
324 try {
325 latch.await();
326 } catch (InterruptedException e) {
327 // ignore
328 }
329 }
330
331 // stage 2 - alert all shutdown handlers
332 log.debug("Shutdown stage 2: notify all shutdown handlers");
333 synchronized (shutdownLock) {
334 for (ShutdownHandler handler : shutdownHandlers) {
335 handler.onShutdown(this);
336 }
337 }
338
339 // stage 3 - destroy all mvc groups
340 log.debug("Shutdown stage 3: destroy all MVC groups");
341 List<String> mvcIds = new ArrayList<>();
342 mvcIds.addAll(getMvcGroupManager().getGroups().keySet());
343 for (String id : mvcIds) {
344 getMvcGroupManager().destroyMVCGroup(id);
345 }
346
347 // stage 4 - call shutdown script
348 log.debug("Shutdown stage 4: execute Shutdown script");
349 getApplicationConfigurer().runLifecycleHandler(Lifecycle.SHUTDOWN);
350
351 injector.getInstance(ExecutorServiceManager.class).shutdownAll();
352 injector.close();
353
354 return true;
355 }
356
357 @SuppressWarnings("unchecked")
358 public void startup() {
359 if (getPhase() != ApplicationPhase.INITIALIZE) return;
360
361 setPhase(ApplicationPhase.STARTUP);
362 event(ApplicationEvent.STARTUP_START, asList(this));
363
364 Object startupGroups = getConfiguration().get("application.startupGroups", null);
365 if (startupGroups instanceof List) {
366 log.info("Initializing all startup groups: {}", startupGroups);
367
368 for (String groupName : (List<String>) startupGroups) {
369 getMvcGroupManager().createMVCGroup(groupName.trim());
370 }
371 } else if (startupGroups != null && startupGroups.getClass().isArray()) {
372 Object[] groups = (Object[]) startupGroups;
373 log.info("Initializing all startup groups: {}", Arrays.toString(groups));
374
375 for (Object groupName : groups) {
376 getMvcGroupManager().createMVCGroup(String.valueOf(groupName).trim());
377 }
378 } else if (startupGroups != null && startupGroups instanceof String) {
379 String[] groups = ((String) startupGroups).split(",");
380 log.info("Initializing all startup groups: {}", Arrays.toString(groups));
381
382 for (String groupName : groups) {
383 getMvcGroupManager().createMVCGroup(groupName.trim());
384 }
385 }
386
387 getApplicationConfigurer().runLifecycleHandler(Lifecycle.STARTUP);
388
389 event(ApplicationEvent.STARTUP_END, asList(this));
390 }
391
392 protected void event(@Nonnull ApplicationEvent event, @Nullable List<?> args) {
393 getEventRouter().publishEvent(event.getName(), args);
394 }
395 }
|