Skip to content

Method: launch(Class, AbstractJavaFXSpringApplication.InitParameters)

1: /*
2: * *************************************************************************************************************************************************************
3: *
4: * SteelBlue: DCI User Interfaces
5: * http://tidalwave.it/projects/steelblue
6: *
7: * Copyright (C) 2015 - 2025 by Tidalwave s.a.s. (http://tidalwave.it)
8: *
9: * *************************************************************************************************************************************************************
10: *
11: * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
12: * You may obtain a copy of the License at
13: *
14: * http://www.apache.org/licenses/LICENSE-2.0
15: *
16: * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
17: * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
18: *
19: * *************************************************************************************************************************************************************
20: *
21: * git clone https://bitbucket.org/tidalwave/steelblue-src
22: * git clone https://github.com/tidalwave-it/steelblue-src
23: *
24: * *************************************************************************************************************************************************************
25: */
26: package it.tidalwave.ui.javafx.spi;
27:
28: import java.lang.reflect.InvocationTargetException;
29: import java.lang.reflect.Method;
30: import java.lang.reflect.Proxy;
31: import javax.annotation.CheckForNull;
32: import jakarta.annotation.Nonnull;
33: import java.util.Arrays;
34: import java.util.List;
35: import java.util.Objects;
36: import java.util.Optional;
37: import java.util.TreeMap;
38: import java.util.concurrent.ExecutorService;
39: import java.util.concurrent.Executors;
40: import java.util.function.Consumer;
41: import java.util.function.Function;
42: import java.io.IOException;
43: import javafx.scene.Parent;
44: import javafx.scene.Scene;
45: import javafx.stage.Stage;
46: import javafx.application.Application;
47: import javafx.application.Platform;
48: import org.springframework.context.ApplicationContext;
49: import org.springframework.context.ConfigurableApplicationContext;
50: import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
51: import it.tidalwave.ui.core.annotation.PresentationAssembler;
52: import it.tidalwave.ui.core.annotation.Assemble;
53: import it.tidalwave.ui.core.message.PowerOffEvent;
54: import it.tidalwave.ui.core.message.PowerOnEvent;
55: import it.tidalwave.ui.javafx.JavaFXApplicationWithSplash;
56: import it.tidalwave.ui.javafx.NodeAndDelegate;
57: import it.tidalwave.ui.javafx.impl.util.JavaFXSafeComponentBuilder;
58: import it.tidalwave.ui.javafx.impl.util.JavaFXSafeProxy;
59: import it.tidalwave.ui.javafx.impl.util.JavaFXSafeProxy.Proxied;
60: import jfxtras.styles.jmetro.JMetro;
61: import jfxtras.styles.jmetro.Style;
62: import org.slf4j.Logger;
63: import org.slf4j.LoggerFactory;
64: import it.tidalwave.util.Key;
65: import it.tidalwave.util.PreferencesHandler;
66: import it.tidalwave.util.TypeSafeMap;
67: import it.tidalwave.util.annotation.VisibleForTesting;
68: import it.tidalwave.messagebus.MessageBus;
69: import lombok.AccessLevel;
70: import lombok.Getter;
71: import lombok.RequiredArgsConstructor;
72: import lombok.With;
73: import static java.util.stream.Collectors.*;
74: import static it.tidalwave.util.CollectionUtils.concat;
75: import static it.tidalwave.util.FunctionalCheckedExceptionWrappers.*;
76: import static it.tidalwave.util.ShortNames.*;
77: import static lombok.AccessLevel.PRIVATE;
78:
79: /***************************************************************************************************************************************************************
80: *
81: * A base class for all variants of JavaFX applications with Spring.
82: *
83: * @author Fabrizio Giudici
84: *
85: **************************************************************************************************************************************************************/
86: public abstract class AbstractJavaFXSpringApplication extends JavaFXApplicationWithSplash
87: {
88: /** Configures the JMetro style, light mode. @since 2.0-ALPHA-6 */
89: public static final Consumer<Scene> STYLE_METRO_LIGHT = scene -> new JMetro(Style.LIGHT).setScene(scene);
90:
91: /** Configures the JMetro style, dark mode. @since 2.0-ALPHA-6 */
92: public static final Consumer<Scene> STYLE_METRO_DARK = scene -> new JMetro(Style.DARK).setScene(scene);
93:
94: /***********************************************************************************************************************************************************
95: * The initialisation parameters to pass to {@link #launch(Class, InitParameters)}.
96: * @since 1.1-ALPHA-6
97: **********************************************************************************************************************************************************/
98: @RequiredArgsConstructor(access = PRIVATE) @With
99: public static class InitParameters
100: {
101: @Nonnull
102: private final String[] args;
103:
104: @Nonnull
105: private final String applicationName;
106:
107: @Nonnull
108: private final String logFolderPropertyName;
109:
110: private final boolean implicitExit;
111:
112: @Nonnull
113: private final TypeSafeMap propertyMap;
114:
115: @Nonnull
116: private final List<Consumer<Scene>> sceneFinalizers;
117:
118: @Nonnull
119: public <T> InitParameters withProperty (@Nonnull final Key<T> key, @Nonnull final T value)
120: {
121: return new InitParameters(args, applicationName, logFolderPropertyName, implicitExit, propertyMap.with(key, value), sceneFinalizers);
122: }
123:
124: @Nonnull
125: public InitParameters withSceneFinalizer (@Nonnull final Consumer<Scene> stageFinalizer)
126: {
127: return new InitParameters(args, applicationName, logFolderPropertyName, implicitExit, propertyMap, concat(sceneFinalizers, stageFinalizer));
128: }
129:
130: public void validate()
131: {
132: requireNotEmpty(applicationName, "applicationName");
133: requireNotEmpty(logFolderPropertyName, "logFolderPropertyName");
134: }
135:
136: private void requireNotEmpty (@CheckForNull final String name, @Nonnull final String message)
137: {
138: if (name == null || name.isEmpty())
139: {
140: throw new IllegalArgumentException(message);
141: }
142: }
143: }
144:
145: public static final String APPLICATION_MESSAGE_BUS_BEAN_NAME = "applicationMessageBus";
146:
147: // Don't use Slf4j and its static logger - give Main a chance to initialize things
148: private final Logger log = LoggerFactory.getLogger(AbstractJavaFXSpringApplication.class);
149:
150: private ConfigurableApplicationContext applicationContext;
151:
152: private Optional<MessageBus> messageBus = Optional.empty();
153:
154: @Getter(AccessLevel.PACKAGE) @Nonnull
155: private final ExecutorService executorService = Executors.newSingleThreadExecutor();
156:
157: private static InitParameters initParameters;
158:
159: /***********************************************************************************************************************************************************
160: * Launches the application.
161: * @param appClass the class of the application to instantiate
162: * @param initParameters the initialisation parameters
163: **********************************************************************************************************************************************************/
164: @SuppressFBWarnings("DM_EXIT")
165: public static void launch (@Nonnull final Class<? extends Application> appClass, @Nonnull final InitParameters initParameters)
166: {
167: try
168: {
169: initParameters.validate();
170: System.setProperty(PreferencesHandler.PROP_APP_NAME, initParameters.applicationName);
171: Platform.setImplicitExit(initParameters.implicitExit);
172: final var preferencesHandler = PreferencesHandler.getInstance();
173: initParameters.propertyMap.forEach(preferencesHandler::setProperty);
174: System.setProperty(initParameters.logFolderPropertyName, preferencesHandler.getLogFolder().toAbsolutePath().toString());
175: JavaFXSafeProxy.setLogDelegateInvocations(initParameters.propertyMap.getOptional(K_LOG_DELEGATE_INVOCATIONS).orElse(false));
176: AbstractJavaFXSpringApplication.initParameters = initParameters;
177: Application.launch(appClass, initParameters.args);
178: }
179: catch (Throwable t)
180: {
181: // Don't use logging facilities here, they could be not initialized
182: t. printStackTrace();
183: System.exit(-1);
184: }
185: }
186:
187: /***********************************************************************************************************************************************************
188: * {@return an empty set of parameters} to populate and pass to {@link #launch(Class, InitParameters)}
189: * @since 1.1-ALPHA-6
190: **********************************************************************************************************************************************************/
191: @Nonnull
192: protected static InitParameters params()
193: {
194: return new InitParameters(new String[0], "", "", true, TypeSafeMap.newInstance(), List.of());
195: }
196:
197: /***********************************************************************************************************************************************************
198: *
199: **********************************************************************************************************************************************************/
200: @Override @Nonnull
201: protected NodeAndDelegate<?> createParent()
202: throws IOException
203: {
204: return NodeAndDelegate.load(getClass(), applicationFxml);
205: }
206:
207: /***********************************************************************************************************************************************************
208: *
209: **********************************************************************************************************************************************************/
210: @Override
211: protected void initializeInBackground()
212: {
213: log.info("initializeInBackground()");
214:
215: try
216: {
217: logProperties();
218: // TODO: workaround for NWRCA-41
219: System.setProperty("it.tidalwave.util.spring.ClassScanner.basePackages", "it");
220: applicationContext = createApplicationContext();
221: applicationContext.registerShutdownHook(); // this actually seems not working, onClosing() does
222:
223: if (applicationContext.containsBean(APPLICATION_MESSAGE_BUS_BEAN_NAME))
224: {
225: messageBus = Optional.of(applicationContext.getBean(APPLICATION_MESSAGE_BUS_BEAN_NAME, MessageBus.class));
226: }
227: }
228: catch (Throwable t)
229: {
230: log.error("", t);
231: }
232: }
233:
234: /***********************************************************************************************************************************************************
235: * {@return a created application context.}
236: **********************************************************************************************************************************************************/
237: @Nonnull
238: protected abstract ConfigurableApplicationContext createApplicationContext();
239:
240: /***********************************************************************************************************************************************************
241: *
242: **********************************************************************************************************************************************************/
243: @Override
244: protected Scene createScene (@Nonnull final Parent parent)
245: {
246: final var scene = super.createScene(parent);
247: initParameters.sceneFinalizers.forEach(f -> f.accept(scene));
248: return scene;
249: }
250:
251: /***********************************************************************************************************************************************************
252: * {@inheritDoc}
253: **********************************************************************************************************************************************************/
254: @Override
255: protected final void onStageCreated (@Nonnull final Stage stage, @Nonnull final NodeAndDelegate<?> applicationNad)
256: {
257: assert Platform.isFxApplicationThread();
258: JavaFXSafeComponentBuilder.getJavaFxBinder().setMainWindow(stage);
259: onStageCreated2(applicationNad);
260: }
261:
262: /***********************************************************************************************************************************************************
263: * This method is separated to make testing simpler (it does not depend on JavaFX stuff).
264: * @param applicationNad
265: **********************************************************************************************************************************************************/
266: @VisibleForTesting final void onStageCreated2 (@Nonnull final NodeAndDelegate<?> applicationNad)
267: {
268: Objects.requireNonNull(applicationContext, "applicationContext is null");
269: final var delegate = applicationNad.getDelegate();
270: final var actualClass = getActualClass(delegate);
271: log.info("Application presentation delegate: {}", delegate);
272:
273: if (!actualClass.equals(delegate.getClass()))
274: {
275: log.info(">>>> delegate class {} is a proxy of {}", delegate.getClass().getName(), actualClass.getName());
276: }
277:
278: if (actualClass.getAnnotation(PresentationAssembler.class) != null)
279: {
280: callAssemble(delegate);
281: }
282:
283: callPresentationAssemblers();
284: executorService.execute(() ->
285: {
286: onStageCreated(applicationContext);
287: messageBus.ifPresent(mb -> mb.publish(new PowerOnEvent()));
288: });
289: }
290:
291: /***********************************************************************************************************************************************************
292: * Invoked when the {@link Stage} is created and the {@link ApplicationContext} has been initialized. Typically, the main class overrides this, retrieves
293: * a reference to the main controller and boots it. This method is executed in a background thread.
294: * @param applicationContext the application context
295: **********************************************************************************************************************************************************/
296: protected void onStageCreated (@Nonnull final ApplicationContext applicationContext)
297: {
298: }
299:
300: /***********************************************************************************************************************************************************
301: * {@inheritDoc}
302: **********************************************************************************************************************************************************/
303: @Override
304: protected void onClosing()
305: {
306: messageBus.ifPresent(mb -> mb.publish(new PowerOffEvent()));
307: applicationContext.close();
308: }
309:
310: /***********************************************************************************************************************************************************
311: * Finds all classes annotated with {@link PresentationAssembler} and invokes methods annotated with {@link Assemble}.
312: **********************************************************************************************************************************************************/
313: private void callPresentationAssemblers()
314: {
315: applicationContext.getBeansWithAnnotation(PresentationAssembler.class).values().forEach(this::callAssemble);
316: }
317:
318: /***********************************************************************************************************************************************************
319: * Call a method annotated with {@link Assemble} in the given object. Since the object is likely to be a dynamic proxy, and proxies don't carry the
320: * annotation of proxied classes, the proxied class is the one being probed for the annotation.
321: * @param delegate the presentation delegate
322: **********************************************************************************************************************************************************/
323: private void callAssemble (@Nonnull final Object delegate)
324: {
325: log.info("Calling presentation assembler: {}", delegate);
326: final var actualClass = getActualClass(delegate);
327: Arrays.stream(actualClass.getDeclaredMethods())
328: .filter(_p(m -> m.getDeclaredAnnotation(Assemble.class) != null))
329: .forEach(_c(m -> invokeInjecting(delegate.getClass().getDeclaredMethod(m.getName(), m.getParameterTypes()), delegate, this::resolveBean)));
330: }
331:
332: /***********************************************************************************************************************************************************
333: * Instantiates an object of the given class performing dependency injections through the constructor.
334: * TODO: possibly replace with a Spring utility doing method injection.
335: * @throws RuntimeException if something fails
336: **********************************************************************************************************************************************************/
337: private void invokeInjecting (@Nonnull final Method method, @Nonnull final Object object, @Nonnull final Function<Class<?>, Object> beanFactory)
338: {
339: try
340: {
341: final var parameters = Arrays.stream(method.getParameterTypes()).map(beanFactory).collect(toList());
342: log.info(">>>> calling {}({})", method.getName(), shortIds(parameters));
343: method.invoke(object, parameters.toArray());
344: }
345: catch (IllegalAccessException | InvocationTargetException e)
346: {
347: throw new RuntimeException(e);
348: }
349: }
350:
351: /***********************************************************************************************************************************************************
352: *
353: **********************************************************************************************************************************************************/
354: @Nonnull
355: private <T> T resolveBean (@Nonnull final Class<T> type)
356: {
357: return type.cast(Optional.ofNullable(JavaFXSafeComponentBuilder.BEANS.get(type)).orElseGet(() -> applicationContext.getBean(type)));
358: }
359:
360: /***********************************************************************************************************************************************************
361: * {@return the class of the given object or its proxied class if it's a proxy}.
362: * @param object the object
363: **********************************************************************************************************************************************************/
364: @Nonnull
365: private Class<?> getActualClass (@Nonnull final Object object)
366: {
367: final var clazz = object.getClass();
368: return !Proxy.isProxyClass(clazz) ? clazz : ((Proxied)object).__getProxiedClass();
369: }
370:
371: /***********************************************************************************************************************************************************
372: * Logs all the system properties.
373: **********************************************************************************************************************************************************/
374: private void logProperties()
375: {
376: for (final var e : new TreeMap<>(System.getProperties()).entrySet())
377: {
378: log.debug("{}: {}", e.getKey(), e.getValue());
379: }
380: }
381: }