Skip to content

Method: static {...}

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