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