Skip to content

Package: AbstractJavaFXSpringApplication

AbstractJavaFXSpringApplication

nameinstructionbranchcomplexitylinemethod
AbstractJavaFXSpringApplication()
M: 0 C: 82
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 19
100%
M: 0 C: 1
100%
callAssemble(Object)
M: 0 C: 18
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 5
100%
M: 0 C: 1
100%
callPresentationAssemblers()
M: 0 C: 9
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 2
100%
M: 0 C: 1
100%
createParent()
M: 6 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
createScene(Parent)
M: 11 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 3 C: 0
0%
M: 1 C: 0
0%
exit()
M: 3 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 2 C: 0
0%
M: 1 C: 0
0%
getActualDelegate(Object)
M: 4 C: 5
56%
M: 1 C: 1
50%
M: 1 C: 1
50%
M: 0 C: 1
100%
M: 0 C: 1
100%
getBeans()
M: 3 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
initializeInBackground()
M: 6 C: 33
85%
M: 0 C: 2
100%
M: 0 C: 2
100%
M: 2 C: 9
82%
M: 0 C: 1
100%
invokeInjecting(Method, Object, Function)
M: 6 C: 25
81%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 2 C: 5
71%
M: 0 C: 1
100%
lambda$callAssemble$8(Method)
M: 0 C: 8
100%
M: 0 C: 2
100%
M: 0 C: 2
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
lambda$callAssemble$9(Object, Method)
M: 0 C: 7
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
lambda$createScene$2(Scene, Consumer)
M: 4 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
lambda$onClosing$5(MessageBus)
M: 0 C: 6
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
lambda$onClosing$6()
M: 0 C: 4
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 3
100%
M: 0 C: 1
100%
lambda$onClosing$7()
M: 0 C: 7
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 3
100%
M: 0 C: 1
100%
lambda$onStageCreated2$3(MessageBus)
M: 0 C: 6
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
lambda$onStageCreated2$4()
M: 0 C: 9
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 3
100%
M: 0 C: 1
100%
lambda$resolveBean$10(Class)
M: 0 C: 5
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
lambda$static$0(Scene)
M: 7 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
lambda$static$1(Scene)
M: 7 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
launch(Class, AbstractJavaFXSpringApplication.InitParameters)
M: 51 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 14 C: 0
0%
M: 1 C: 0
0%
logProperties()
M: 0 C: 24
100%
M: 0 C: 2
100%
M: 0 C: 2
100%
M: 0 C: 4
100%
M: 0 C: 1
100%
onClosing()
M: 0 C: 14
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 4
100%
M: 0 C: 1
100%
onStageCreated(ApplicationContext)
M: 0 C: 1
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
onStageCreated(Stage, NodeAndDelegate)
M: 15 C: 0
0%
M: 2 C: 0
0%
M: 2 C: 0
0%
M: 4 C: 0
0%
M: 1 C: 0
0%
onStageCreated2(NodeAndDelegate)
M: 0 C: 33
100%
M: 0 C: 2
100%
M: 0 C: 2
100%
M: 0 C: 9
100%
M: 0 C: 1
100%
params()
M: 11 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
resolveBean(Class)
M: 0 C: 11
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
static {...}
M: 0 C: 9
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 3
100%
M: 0 C: 1
100%

Coverage

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 jakarta.annotation.Nonnull;
31: import jakarta.annotation.Nullable;
32: import java.util.Arrays;
33: import java.util.Collections;
34: import java.util.HashMap;
35: import java.util.List;
36: import java.util.Map;
37: import java.util.Objects;
38: import java.util.Optional;
39: import java.util.TreeMap;
40: import java.util.function.Consumer;
41: import java.util.function.Function;
42: import javafx.scene.Parent;
43: import javafx.scene.Scene;
44: import javafx.stage.Stage;
45: import javafx.application.Application;
46: import javafx.application.Platform;
47: import org.springframework.context.ApplicationContext;
48: import org.springframework.context.ConfigurableApplicationContext;
49: import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
50: import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
51: import it.tidalwave.ui.core.annotation.Assemble;
52: import it.tidalwave.ui.core.annotation.PresentationAssembler;
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.JavaFXBinder;
57: import it.tidalwave.ui.javafx.JavaFXMenuBarControl;
58: import it.tidalwave.ui.javafx.JavaFXToolBarControl;
59: import it.tidalwave.ui.javafx.NodeAndDelegate;
60: import it.tidalwave.ui.javafx.impl.DefaultJavaFXBinder;
61: import it.tidalwave.ui.javafx.impl.DefaultJavaFXMenuBarControl;
62: import it.tidalwave.ui.javafx.impl.DefaultJavaFXToolBarControl;
63: import it.tidalwave.ui.javafx.impl.util.JavaFXSafeProxy;
64: import it.tidalwave.ui.javafx.impl.util.JavaFXSafeProxy.Proxied;
65: import jfxtras.styles.jmetro.JMetro;
66: import jfxtras.styles.jmetro.Style;
67: import org.slf4j.Logger;
68: import org.slf4j.LoggerFactory;
69: import it.tidalwave.util.Key;
70: import it.tidalwave.util.PreferencesHandler;
71: import it.tidalwave.util.TypeSafeMap;
72: import it.tidalwave.util.annotation.VisibleForTesting;
73: import it.tidalwave.messagebus.MessageBus;
74: import lombok.RequiredArgsConstructor;
75: import lombok.With;
76: import static java.util.stream.Collectors.*;
77: import static it.tidalwave.util.CollectionUtils.concat;
78: import static it.tidalwave.util.FunctionalCheckedExceptionWrappers.*;
79: import static it.tidalwave.util.ShortNames.shortIds;
80: import static lombok.AccessLevel.PRIVATE;
81:
82: /***************************************************************************************************************************************************************
83: *
84: * A base class for all variants of JavaFX applications with Spring.
85: *
86: * @author Fabrizio Giudici
87: *
88: **************************************************************************************************************************************************************/
89: public abstract class AbstractJavaFXSpringApplication extends JavaFXApplicationWithSplash
90: {
91: /** Configures the JMetro style, light mode. @since 3.0-ALPHA-1 */
92: public static final Consumer<Scene> STYLE_METRO_LIGHT = scene -> new JMetro(Style.LIGHT).setScene(scene);
93:
94: /** Configures the JMetro style, dark mode. @since 3.0-ALPHA-1 */
95: public static final Consumer<Scene> STYLE_METRO_DARK = scene -> new JMetro(Style.DARK).setScene(scene);
96:
97: /***********************************************************************************************************************************************************
98: * The initialisation parameters to pass to {@link #launch(Class, InitParameters)}.
99: * @since 1.1-ALPHA-6
100: **********************************************************************************************************************************************************/
101: @RequiredArgsConstructor(access = PRIVATE) @With
102: public static class InitParameters
103: {
104: @Nonnull
105: private final String[] args;
106:
107: @Nonnull
108: private final String applicationName;
109:
110: @Nonnull
111: private final String logFolderPropertyName;
112:
113: private final boolean implicitExit;
114:
115: @Nonnull
116: private final TypeSafeMap propertyMap;
117:
118: @Nonnull
119: private final List<Consumer<Scene>> sceneFinalizers;
120:
121: @Nonnull
122: public <T> InitParameters withProperty (@Nonnull final Key<T> key, @Nonnull final T value)
123: {
124: return new InitParameters(args, applicationName, logFolderPropertyName, implicitExit, propertyMap.with(key, value), sceneFinalizers);
125: }
126:
127: @Nonnull
128: public InitParameters withSceneFinalizer (@Nonnull final Consumer<Scene> stageFinalizer)
129: {
130: return new InitParameters(args, applicationName, logFolderPropertyName, implicitExit, propertyMap, concat(sceneFinalizers, stageFinalizer));
131: }
132:
133: private void validate()
134: {
135: requireNotEmpty(applicationName, "applicationName");
136: requireNotEmpty(logFolderPropertyName, "logFolderPropertyName");
137: }
138:
139: private static void requireNotEmpty (@Nullable final String name, @Nonnull final String message)
140: {
141: if (name == null || name.isEmpty())
142: {
143: throw new IllegalArgumentException(message);
144: }
145: }
146: }
147:
148: public static final String APPLICATION_MESSAGE_BUS_BEAN_NAME = "applicationMessageBus";
149:
150: private static final Map<Class<?>, Object> BEANS = new HashMap<>();
151:
152: private static final int QUEUE_CAPACITY = 10000;
153:
154: private static InitParameters initParameters;
155:
156: protected final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
157:
158: protected final JavaFXBinder javaFxBinder = new DefaultJavaFXBinder(executor);
159:
160: protected final JavaFXToolBarControl toolBarControl = new DefaultJavaFXToolBarControl();
161:
162: protected final JavaFXMenuBarControl menuBarControl = new DefaultJavaFXMenuBarControl();
163:
164: // Don't use Slf4j and its static logger - give Main a chance to initialize things
165: private final Logger log = LoggerFactory.getLogger(AbstractJavaFXSpringApplication.class);
166:
167: private ConfigurableApplicationContext applicationContext;
168:
169: private Optional<MessageBus> messageBus = Optional.empty();
170:
171: /***********************************************************************************************************************************************************
172: * Launches the application.
173: * @param appClass the class of the application to instantiate
174: * @param initParameters the initialisation parameters
175: **********************************************************************************************************************************************************/
176: @SuppressFBWarnings("DM_EXIT")
177: public static void launch (@Nonnull final Class<? extends Application> appClass, @Nonnull final InitParameters initParameters)
178: {
179: try
180: {
181: initParameters.validate();
182: System.setProperty(PreferencesHandler.PROP_APP_NAME, initParameters.applicationName);
183: Platform.setImplicitExit(initParameters.implicitExit);
184: final var preferencesHandler = PreferencesHandler.getInstance();
185: initParameters.propertyMap.forEach(preferencesHandler::setProperty);
186: System.setProperty(initParameters.logFolderPropertyName, preferencesHandler.getLogFolder().toAbsolutePath().toString());
187: JavaFXSafeProxy.setLogDelegateInvocations(initParameters.propertyMap.getOptional(K_LOG_DELEGATE_INVOCATIONS).orElse(false));
188: AbstractJavaFXSpringApplication.initParameters = initParameters;
189: launch(appClass, initParameters.args);
190: }
191: catch (Throwable t)
192: {
193: // Don't use logging facilities here, they could be not initialized
194: t.printStackTrace();
195: System.exit(-1);
196: }
197: }
198:
199: /***********************************************************************************************************************************************************
200: *
201: **********************************************************************************************************************************************************/
202: @Nonnull
203: public static Map<Class<?>, Object> getBeans()
204: {
205: return Collections.unmodifiableMap(BEANS);
206: }
207:
208: /***********************************************************************************************************************************************************
209: *
210: **********************************************************************************************************************************************************/
211: protected AbstractJavaFXSpringApplication()
212: {
213: executor.setWaitForTasksToCompleteOnShutdown(false);
214: executor.setAwaitTerminationMillis(2000); // FIXME
215: executor.setThreadNamePrefix("ui-service-pool-");
216: // Fix for STB-26
217: executor.setCorePoolSize(1);
218: executor.setMaxPoolSize(1);
219: executor.setQueueCapacity(QUEUE_CAPACITY);
220: executor.initialize(); // it's used before Spring completes initialisation
221: BEANS.put(JavaFXBinder.class, javaFxBinder);
222: BEANS.put(JavaFXToolBarControl.class, toolBarControl);
223: BEANS.put(JavaFXMenuBarControl.class, menuBarControl);
224: BEANS.put(PreferencesHandler.class, PreferencesHandler.getInstance());
225: }
226:
227: /***********************************************************************************************************************************************************
228: * {@return an empty set of parameters} to populate and pass to {@link #launch(Class, InitParameters)}
229: * @since 1.1-ALPHA-6
230: **********************************************************************************************************************************************************/
231: @Nonnull
232: protected static InitParameters params()
233: {
234: return new InitParameters(new String[0], "", "", true, TypeSafeMap.newInstance(), List.of());
235: }
236:
237: /***********************************************************************************************************************************************************
238: *
239: **********************************************************************************************************************************************************/
240: @Override @Nonnull
241: protected NodeAndDelegate<?> createParent()
242: {
243: return NodeAndDelegate.of(getClass(), applicationFxml);
244: }
245:
246: /***********************************************************************************************************************************************************
247: *
248: **********************************************************************************************************************************************************/
249: @Override
250: protected void initializeInBackground()
251: {
252: log.info("initializeInBackground()");
253:
254: try
255: {
256: logProperties();
257: // TODO: workaround for NWRCA-41
258: System.setProperty("it.tidalwave.util.spring.ClassScanner.basePackages", "it");
259: applicationContext = createApplicationContext();
260: applicationContext.registerShutdownHook(); // this actually seems not working, onClosing() does
261:
262:• if (applicationContext.containsBean(APPLICATION_MESSAGE_BUS_BEAN_NAME))
263: {
264: messageBus = Optional.of(applicationContext.getBean(APPLICATION_MESSAGE_BUS_BEAN_NAME, MessageBus.class));
265: }
266: }
267: catch (Throwable t)
268: {
269: log.error("", t);
270: }
271: }
272:
273: /***********************************************************************************************************************************************************
274: * {@return a created application context.}
275: **********************************************************************************************************************************************************/
276: @Nonnull
277: protected abstract ConfigurableApplicationContext createApplicationContext();
278:
279: /***********************************************************************************************************************************************************
280: *
281: **********************************************************************************************************************************************************/
282: @Override
283: protected Scene createScene (@Nonnull final Parent parent)
284: {
285: final var scene = super.createScene(parent);
286: initParameters.sceneFinalizers.forEach(f -> f.accept(scene));
287: return scene;
288: }
289:
290: /***********************************************************************************************************************************************************
291: * {@inheritDoc}
292: **********************************************************************************************************************************************************/
293: @Override
294: protected final void onStageCreated (@Nonnull final Stage stage, @Nonnull final NodeAndDelegate<?> applicationNad)
295: {
296:• assert Platform.isFxApplicationThread();
297: javaFxBinder.setMainWindow(stage);
298: onStageCreated2(applicationNad);
299: }
300:
301: /***********************************************************************************************************************************************************
302: * This method is separated to make testing simpler (it does not depend on JavaFX stuff).
303: * @param applicationNad
304: **********************************************************************************************************************************************************/
305: @VisibleForTesting final void onStageCreated2 (@Nonnull final NodeAndDelegate<?> applicationNad)
306: {
307: Objects.requireNonNull(applicationContext, "applicationContext is null");
308: final var delegate = applicationNad.getDelegate();
309: final var actualDelegate = getActualDelegate(delegate);
310: log.info("Application presentation delegate: {} --- actual: {}", delegate, actualDelegate);
311:
312:• if (actualDelegate.getClass().getAnnotation(PresentationAssembler.class) != null)
313: {
314: callAssemble(actualDelegate);
315: }
316:
317: callPresentationAssemblers();
318: executor.execute(() ->
319: {
320: onStageCreated(applicationContext);
321: messageBus.ifPresent(mb -> mb.publish(new PowerOnEvent())); // must be after onStageCreated()
322: });
323: }
324:
325: /***********************************************************************************************************************************************************
326: * Invoked when the {@link Stage} is created and the {@link ApplicationContext} has been initialized. Typically, the main class overrides this, retrieves
327: * a reference to the main controller and boots it. This method is executed in a background thread.
328: * @param applicationContext the application context
329: **********************************************************************************************************************************************************/
330: protected void onStageCreated (@Nonnull final ApplicationContext applicationContext)
331: {
332: }
333:
334: /***********************************************************************************************************************************************************
335: * {@inheritDoc}
336: **********************************************************************************************************************************************************/
337: @Override
338: protected final void onClosing()
339: {
340: log.info("onClosing()");
341: messageBus.ifPresent(mb -> mb.publish(new PowerOffEvent()));
342: executor.execute(() ->
343: {
344: applicationContext.close();
345: Platform.runLater(() ->
346: {
347: Platform.exit();
348: exit();
349: });
350: });
351: }
352:
353: /***********************************************************************************************************************************************************
354: *
355: **********************************************************************************************************************************************************/
356: protected void exit()
357: {
358: System.exit(0);
359: }
360:
361: /***********************************************************************************************************************************************************
362: * Finds all classes annotated with {@link PresentationAssembler} and invokes methods annotated with {@link Assemble}.
363: **********************************************************************************************************************************************************/
364: private void callPresentationAssemblers()
365: {
366: applicationContext.getBeansWithAnnotation(PresentationAssembler.class).values().forEach(this::callAssemble);
367: }
368:
369: /***********************************************************************************************************************************************************
370: * Call a method annotated with {@link Assemble} in the given object.
371: * @param assembler the assembler
372: **********************************************************************************************************************************************************/
373: private void callAssemble (@Nonnull final Object assembler)
374: {
375: log.info("Calling presentation assembler: {}", assembler);
376: Arrays.stream(assembler.getClass().getDeclaredMethods())
377:• .filter(_p(m -> m.getDeclaredAnnotation(Assemble.class) != null))
378: .forEach(_c(m -> invokeInjecting(m, assembler, this::resolveBean)));
379: }
380:
381: /***********************************************************************************************************************************************************
382: * Instantiates an object of the given class performing dependency injections through the constructor.
383: * TODO: possibly replace with a Spring utility doing method injection.
384: * @throws RuntimeException if something fails
385: **********************************************************************************************************************************************************/
386: private void invokeInjecting (@Nonnull final Method method, @Nonnull final Object object, @Nonnull final Function<Class<?>, Object> beanFactory)
387: {
388: try
389: {
390: final var parameters = Arrays.stream(method.getParameterTypes()).map(beanFactory).collect(toList());
391: log.info(">>>> calling {}({})", method.getName(), shortIds(parameters));
392: method.invoke(object, parameters.toArray());
393: }
394: catch (IllegalAccessException | InvocationTargetException e)
395: {
396: throw new RuntimeException(e);
397: }
398: }
399:
400: /***********************************************************************************************************************************************************
401: *
402: **********************************************************************************************************************************************************/
403: @Nonnull
404: private <T> T resolveBean (@Nonnull final Class<T> type)
405: {
406: return type.cast(Optional.ofNullable(BEANS.get(type)).orElseGet(() -> applicationContext.getBean(type)));
407: }
408:
409: /***********************************************************************************************************************************************************
410: *
411: **********************************************************************************************************************************************************/
412: @Nonnull
413: private static Object getActualDelegate (@Nonnull final Object delegate)
414: {
415:• return delegate instanceof Proxied ? ((Proxied)delegate).__getProxiedObject() : delegate;
416: }
417:
418: /***********************************************************************************************************************************************************
419: * Logs all the system properties.
420: **********************************************************************************************************************************************************/
421: private void logProperties()
422: {
423:• for (final var e : new TreeMap<>(System.getProperties()).entrySet())
424: {
425: log.debug("{}: {}", e.getKey(), e.getValue());
426: }
427: }
428: }