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