Skip to content

Method: resolveBean(Class)

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