Content of file JavaFXSafeComponentBuilder.java.html

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>JavaFXSafeComponentBuilder.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">SteelBlue - JavaFX Bindings</a> &gt; <a href="index.source.html" class="el_package">it.tidalwave.role.ui.javafx.impl.util</a> &gt; <span class="el_source">JavaFXSafeComponentBuilder.java</span></div><h1>JavaFXSafeComponentBuilder.java</h1><pre class="source lang-java linenums">/*
 * *********************************************************************************************************************
 *
 * SteelBlue: DCI User Interfaces
 * http://tidalwave.it/projects/steelblue
 *
 * Copyright (C) 2015 - 2021 by Tidalwave s.a.s. (http://tidalwave.it)
 *
 * *********************************************************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations under the License.
 *
 * *********************************************************************************************************************
 *
 * git clone https://bitbucket.org/tidalwave/steelblue-src
 * git clone https://github.com/tidalwave-it/steelblue-src
 *
 * *********************************************************************************************************************
 */
package it.tidalwave.role.ui.javafx.impl.util;

import javax.annotation.Nonnull;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import javafx.application.Platform;
import javafx.fxml.FXML;
import it.tidalwave.ui.javafx.JavaFXSafeProxyCreator;
import javafx.fxml.FXMLLoader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import static lombok.AccessLevel.PRIVATE;

/***********************************************************************************************************************
 *
 * @stereotype Factory
 *
 * @author  Fabrizio Giudici
 *
 **********************************************************************************************************************/
<span class="nc bnc" id="L53" title="All 4 branches missed.">@RequiredArgsConstructor(access = PRIVATE) @Slf4j</span>
public final class JavaFXSafeComponentBuilder&lt;I, T extends I&gt;
  {
    @Nonnull
    private final Class&lt;T&gt; componentClass;

    @Nonnull
    private final Class&lt;I&gt; interfaceClass;

<span class="nc" id="L62">    private WeakReference&lt;T&gt; presentationRef = new WeakReference&lt;&gt;(null);</span>

    @Nonnull
    public static &lt;J, X extends J&gt; JavaFXSafeComponentBuilder&lt;J, X&gt; builderFor (@Nonnull final Class&lt;X&gt; componentClass)
      {
<span class="nc" id="L67">        final Class&lt;J&gt; interfaceClass = (Class&lt;J&gt;)componentClass.getInterfaces()[0]; // FIXME: guess</span>
guess
<span class="nc" id="L68"> return new JavaFXSafeComponentBuilder&lt;&gt;(componentClass, interfaceClass);</span> } @Nonnull public static &lt;J, X extends J&gt; JavaFXSafeComponentBuilder&lt;J, X&gt; builderFor (@Nonnull final Class&lt;J&gt; interfaceClass, @Nonnull final Class&lt;X&gt; componentClass) { <span class="nc" id="L75"> return new JavaFXSafeComponentBuilder&lt;&gt;(componentClass, interfaceClass);</span> } /******************************************************************************************************************* * * Creates an instance of a surrogate JavaFX delegate. JavaFX delegates (controllers in JavaFX jargon) are those * objects with fields annotated with {@link @FXML} that are created by the {@link FXMLLoader} starting from a * {@code .fxml} file. Sometimes a surrogate delegate is needed, that is a class that is not mapped to any * {@link @FXML} file, but whose fields are copied from another existing delegate. * * @param componentClass the class of the surrogate * @param fxmlFieldsSource the existing JavaFX delegate with {@code @FXML} annotated fields. * @return the new surrogate delegate * ******************************************************************************************************************/ @Nonnull public static &lt;J, X extends J&gt; X createInstance (@Nonnull final Class&lt;X&gt; componentClass, @Nonnull final Object fxmlFieldsSource) { <span class="nc" id="L94"> final JavaFXSafeComponentBuilder&lt;J, X&gt; builder = builderFor(componentClass);</span> <span class="nc" id="L95"> return builder.createInstance(fxmlFieldsSource);</span> } /******************************************************************************************************************* * * Creates an instance of a surrogate JavaFX delegate. JavaFX delegates (controllers in JavaFX jargon) are those * objects with fields annotated with {@link @FXML} that are created by the {@link FXMLLoader} starting from a * {@code .fxml} file. Sometimes a surrogate delegate is needed, that is a class that is not mapped to any * {@link @FXML} file, but whose fields are copied from another existing delegate. * * @param fxmlFieldsSource the existing JavaFX delegate with {@code @FXML} annotated fields. * @return the new surrogate delegate * ******************************************************************************************************************/ @Nonnull public synchronized T createInstance (@Nonnull final Object fxmlFieldsSource) { <span class="nc" id="L112"> log.trace(&quot;createInstance({})&quot;, fxmlFieldsSource);</span> <span class="nc" id="L113"> T presentation = presentationRef.get();</span> <span class="nc bnc" id="L115" title="All 2 branches missed."> if (presentation == null)</span> { <span class="nc bnc" id="L117" title="All 2 branches missed."> presentation = Platform.isFxApplicationThread() ? createComponentInstance() : createComponentInstanceInJAT();</span> <span class="nc" id="L118"> copyFxmlFields(presentation, fxmlFieldsSource); // FIXME: in JFX thread?</span> try // FIXME // FIXME: in JFX thread? { <span class="nc" id="L122"> presentation.getClass().getDeclaredMethod(&quot;initialize&quot;).invoke(presentation);</span> } <span class="nc" id="L124"> catch (NoSuchMethodException | SecurityException | IllegalAccessException</span> | InvocationTargetException e) { <span class="nc" id="L127"> log.warn(&quot;No postconstruct in {}&quot;, presentation);</span> <span class="nc" id="L128"> }</span> <span class="nc" id="L130"> presentation = (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),</span> new Class[] { interfaceClass }, new JavaFXSafeProxy&lt;&gt;(presentation)); <span class="nc" id="L133"> presentationRef = new WeakReference&lt;&gt;(presentation);</span> } <span class="nc" id="L136"> return presentation;</span> } /******************************************************************************************************************* * * * ******************************************************************************************************************/ @Nonnull protected T createComponentInstance() { <span class="nc" id="L147"> return ReflectionUtils.instantiateWithDependencies(componentClass, JavaFXSafeProxyCreator.BEANS);</span> } /******************************************************************************************************************* * * * ******************************************************************************************************************/ @Nonnull private T createComponentInstanceInJAT() { <span class="nc" id="L158"> final AtomicReference&lt;T&gt; reference = new AtomicReference&lt;&gt;();</span> <span class="nc" id="L159"> final CountDownLatch countDownLatch = new CountDownLatch(1);</span> <span class="nc" id="L161"> Platform.runLater(() -&gt;</span> { <span class="nc" id="L163"> reference.set(createComponentInstance());</span> <span class="nc" id="L164"> countDownLatch.countDown();</span> <span class="nc" id="L165"> });</span> try { <span class="nc" id="L169"> countDownLatch.await();</span> } <span class="nc" id="L171"> catch (InterruptedException e)</span> { <span class="nc" id="L173"> log.error(&quot;&quot;, e);</span> <span class="nc" id="L174"> throw new RuntimeException(e);</span> <span class="nc" id="L175"> }</span> <span class="nc" id="L177"> return reference.get();</span> } /******************************************************************************************************************* * * Inject fields annotated with {@link FXML} in {@code source} to {@code target}. * * @param target the target object * @param source the source object * ******************************************************************************************************************/ private void copyFxmlFields (@Nonnull final Object target, @Nonnull final Object source) { <span class="nc" id="L190"> log.debug(&quot;injecting {} with fields from {}&quot;, target, source);</span> <span class="nc" id="L191"> final Map&lt;String, Object&gt; valuesMapByFieldName = new HashMap&lt;&gt;();</span> <span class="nc bnc" id="L193" title="All 2 branches missed."> for (final Field field : source.getClass().getDeclaredFields())</span> { <span class="nc bnc" id="L195" title="All 2 branches missed."> if (field.getAnnotation(FXML.class) != null)</span> { <span class="nc" id="L197"> final String name = field.getName();</span> try { <span class="nc" id="L201"> field.setAccessible(true);</span> <span class="nc" id="L202"> final Object value = field.get(source);</span> <span class="nc" id="L203"> valuesMapByFieldName.put(name, value);</span> <span class="nc" id="L204"> log.trace(&quot;&gt;&gt;&gt;&gt; available field {}: {}&quot;, name, value);</span> } <span class="nc" id="L206"> catch (IllegalArgumentException | IllegalAccessException e)</span> { <span class="nc" id="L208"> throw new RuntimeException(&quot;Cannot read field &quot; + name + &quot; from &quot; + source, e);</span> <span class="nc" id="L209"> }</span> } } <span class="nc bnc" id="L213" title="All 2 branches missed."> for (final Field field : target.getClass().getDeclaredFields())</span> { <span class="nc" id="L215"> final FXML fxml = field.getAnnotation(FXML.class);</span> <span class="nc bnc" id="L217" title="All 2 branches missed."> if (fxml != null)</span> { <span class="nc" id="L219"> final String name = field.getName();</span> <span class="nc" id="L220"> final Object value = valuesMapByFieldName.get(name);</span> <span class="nc bnc" id="L222" title="All 2 branches missed."> if (value == null)</span> { <span class="nc" id="L224"> throw new RuntimeException(&quot;Can't inject &quot; + name + &quot;: available: &quot; + valuesMapByFieldName.keySet());</span> } <span class="nc" id="L227"> field.setAccessible(true);</span> try { <span class="nc" id="L231"> field.set(target, value);</span> } <span class="nc" id="L233"> catch (IllegalArgumentException | IllegalAccessException e)</span> { <span class="nc" id="L235"> throw new RuntimeException(&quot;Cannot inject field &quot; + name + &quot; to &quot; + target, e);</span> <span class="nc" id="L236"> }</span> } } <span class="nc" id="L240"> ReflectionUtils.injectDependencies(target, JavaFXSafeProxyCreator.BEANS);</span> <span class="nc" id="L241"> }</span> } </pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.7.202105040129</span></div></body></html>