Run Designer previews with application-owned DI adapters

This commit is contained in:
2026-11-26 16:01:19 +01:00
parent e49d586916
commit 6126967fdc
56 changed files with 2131 additions and 50 deletions
+79
View File
@@ -0,0 +1,79 @@
# Spring contact book
This Maven fixture runs as a JavaFX application and as a NeitzelFXDesigner
preview. It uses Spring Framework 6.2.11, the separated NeitzelLib `1.0.7-SNAPSHOT`,
JavaFX 27.0.1 in the target and JDK 25. Views use the same FXML and adapter
in both environments. Spring owns the application services. Each Controller
and Component is a prototype.
## Run it
Set `JAVA_HOME` to JDK 25 and use a separate local Maven repository to stage
the development artifacts. From the Designer checkout:
```sh
export DI_MAVEN_REPOSITORY="/absolute/path/to/di-repository"
export MAVEN_OPTS="-Dmaven.repo.local=$DI_MAVEN_REPOSITORY"
(cd ../NeitzelLib && ./mvnw -pl fx-test -am clean install)
./mvnw -B -ntp install
./mvnw -f integration-fixtures/spring-di/app/pom.xml javafx:run
```
Edit the book name to see the Spring-supplied Converter update the caption.
Closing the window first destroys its prototypes, then stops the shared
service. The [application bootstrap](app/src/main/java/fixture/spring/app/SpringBook.java)
uses the managed `ViewLoader`. The [Spring registration](app/src/main/java/fixture/spring/app/SpringBookContext.java)
assigns separate scopes to the view types and services.
## Open the previews
From the Designer checkout, set up the ignored local paths once:
```sh
python3 scripts/configure-library-example.py \
--project integration-fixtures/spring-di --target-java-home "$JAVA_HOME"
```
Use the same local Maven repository when starting the Designer or IntelliJ.
Open `app/src/main/resources/fixture/spring/ui/Book.fxml`, select
**Build and Refresh** and then **Form preview** or **Interactive preview**.
The preview starts with `Preview contact book`; changes to it belong to
that preview. **Stop preview** closes the session. Open `EntryCard.fxml`
and start its separate example to see that Component as a standalone root.
The [Book provider](preview/src/main/java/fixture/spring/preview/BookExamples.java)
creates a fresh Model and Spring context. The [Component provider](preview/src/main/java/fixture/spring/preview/CardExamples.java)
returns its own Model and context. Both provide the application
[adapter](app/src/main/java/fixture/spring/app/SpringViews.java).
FXML resources and fields in `fixture.spring.ui` are accessible in the
[application module](app/src/main/java/module-info.java). The
[preview module](preview/src/main/java/module-info.java) exposes its providers.
The package named by `componentPackage` stays closed to demonstrate that
the Spring worker uses FXML resource access and the registered Spring beans.
## Run the checks
From the Designer checkout, using the same JDK and local Maven repository:
```sh
python3 scripts/check-preview-fixtures.py --spring-di --target-java-home "$JAVA_HOME"
./designer-intellij/gradlew -p designer-intellij -PideaHome="$IDEA_HOME" \
-Dmaven.repo.local="$DI_MAVEN_REPOSITORY" buildPlugin
./mvnw -pl designer-standalone \
org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath \
-DincludeScope=test -Dmdep.outputFile=target/smoke-classpath.txt
python3 scripts/check-spring-hosts.py --java-home "$JAVA_HOME" \
--target-java-home "$JAVA_HOME" --idea-home "$IDEA_HOME"
```
The worker checks include two simultaneous Views, separate scopes, nested
Components, Repeat and Table release, cleanup after load/readiness failure
and cancellation, module resource diagnostics, and the required runtime
diagnostic against FX 1.0.6. The host checks use disposably copied project
files and exercise the canvas, form preview and interactive preview.
Each Spring context verifies that the running application or preview
cannot load Neitzel's `ApplicationContext` or Reflections and that
their JARs are absent from its classpath and module path. The test
runner separately verifies the normal Maven dependency trees. Its
missing-API check resolves FX 1.0.6 from a separate POM.
@@ -0,0 +1,45 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di</artifactId>
<version>1</version>
</parent>
<artifactId>spring-di-app</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${neitzellib.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>${jakarta-annotation.version}</version>
</dependency>
<dependency>
<groupId>jakarta.inject</groupId>
<artifactId>jakarta.inject-api</artifactId>
<version>${jakarta-inject.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>${javafx-maven-plugin.version}</version>
<configuration>
<mainClass>fixture.spring.app/fixture.spring.app.SpringBook</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,40 @@
package fixture.spring.app;
import jakarta.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
/** An in-memory service shared by all View objects in one Spring context. */
public final class FixtureService {
private final String label;
private final List<Object> live = new ArrayList<>();
private int released;
private int atShutdown = -1;
private int shutdowns;
public FixtureService(String label) { this.label = label; }
public String label() { return label; }
public void created(Object object) { live.add(object); }
public void release(Object object) {
if (!live.remove(object)) throw new IllegalStateException("Unknown View object: " + object);
released++;
}
public int liveCount() { return live.size(); }
public int releasedCount() { return released; }
public int liveAtShutdown() { return atShutdown; }
public int shutdownCount() { return shutdowns; }
@PreDestroy
public void shutdown() {
atShutdown = live.size();
shutdowns++;
System.out.println("SPRING CLOSED " + label + " live=" + atShutdown + " released=" + released);
}
}
@@ -0,0 +1,35 @@
package fixture.spring.app;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import fixture.spring.model.Book;
import fixture.spring.ui.BookController;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public final class SpringBook extends Application {
private SpringBookContext context;
private final ViewModelContext models = new ViewModelContext();
public static void main(String[] args) { launch(args); }
@Override
public void start(Stage stage) {
context = SpringBookContext.open("Application service");
var view = ViewLoader.loadWithDependencies(BookController.class.getResource("Book.fxml"),
Book.sample("Spring contact book"), context.dependencies(), models);
stage.setTitle("Spring contact book");
stage.setScene(new Scene(view.getRoot(), 660, 500));
stage.show();
}
@Override
public void stop() {
try {
models.close();
} finally {
if (context != null) context.close();
}
}
}
@@ -0,0 +1,46 @@
package fixture.spring.app;
import de.neitzel.fx.view.Converter;
import fixture.spring.ui.BookController;
import fixture.spring.ui.EntryCard;
import fixture.spring.ui.EntryPanel;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public record SpringBookContext(AnnotationConfigApplicationContext spring, SpringViews dependencies)
implements AutoCloseable {
private static final Map<Class<?>, String> VIEW_BEANS = Map.of(
BookController.class, "bookController", EntryCard.class, "entryCard", EntryPanel.class, "entryPanel");
public static SpringBookContext open(String serviceLabel) {
SpringRuntime.requireNoNeitzelDi(serviceLabel);
var spring = new AnnotationConfigApplicationContext();
try {
spring.registerBean(FixtureService.class, () -> new FixtureService(serviceLabel));
spring.registerBean(NameConverter.class);
VIEW_BEANS.forEach((type, name) -> spring.registerBean(name, type,
bean -> bean.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)));
spring.refresh();
return new SpringBookContext(spring,
new SpringViews(spring.getBeanFactory(), VIEW_BEANS, Set.of(EntryCard.class, EntryPanel.class)));
} catch (RuntimeException | Error failure) {
spring.close();
throw failure;
}
}
public FixtureService service() { return spring.getBean(FixtureService.class); }
@Override
public void close() { spring.close(); }
public static final class NameConverter implements Converter {
@Override
public Object toControlValue(Object value) { return "[" + value + "]"; }
@Override
public Object toAttributeValue(Object value) { return value; }
}
}
@@ -0,0 +1,35 @@
package fixture.spring.app;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Pattern;
/** Verifies the artifact isolation in both the fixture application and its preview process. */
final class SpringRuntime {
private static final Pattern NEITZEL_DI = Pattern.compile("(?:fx-injection|injection|reflections)-.*\\.jar");
private SpringRuntime() {}
static void requireNoNeitzelDi(String label) {
var loader = Thread.currentThread().getContextClassLoader();
for (String type : List.of("de.neitzel.injection.ApplicationContext", "org.reflections.Reflections")) {
try {
Class.forName(type, false, loader);
throw new IllegalStateException("Unexpected runtime type " + type);
} catch (ClassNotFoundException expected) {
// The fixture must be usable without either implementation.
}
}
for (String property : List.of("java.class.path", "jdk.module.path")) {
String path = System.getProperty(property, "");
if (path.isEmpty()) continue;
for (String entry : path.split(Pattern.quote(File.pathSeparator))) {
if (NEITZEL_DI.matcher(Path.of(entry).getFileName().toString()).matches())
throw new IllegalStateException("Unexpected DI artifact on " + property + ": " + entry);
}
}
var mode = SpringRuntime.class.getModule().isNamed() ? "module-path" : "classpath";
System.out.println("SPRING FX ISOLATION " + mode + " " + label);
}
}
@@ -0,0 +1,36 @@
package fixture.spring.app;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
public record SpringViews(ConfigurableBeanFactory beans, Map<Class<?>, String> viewBeans,
Set<Class<?>> components) implements ViewDependencies {
public SpringViews {
viewBeans = Map.copyOf(viewBeans);
components = Set.copyOf(components);
}
@Override
public boolean isComponent(Class<?> type) {
return components.contains(type);
}
@Override
public <T> Optional<T> findService(Class<T> type) {
return Optional.ofNullable(beans.getBeanProvider(type).getIfAvailable());
}
@Override
public <T> ViewObject<T> createViewObject(Class<T> type) {
String name = viewBeans.get(type);
if (name == null || !beans.isPrototype(name)) {
throw new IllegalArgumentException("Expected a prototype bean for " + type.getName());
}
T instance = beans.getBean(name, type);
return new ViewObject<>(instance, () -> beans.destroyBean(name, instance));
}
}
@@ -0,0 +1,33 @@
package fixture.spring.model;
import java.util.ArrayList;
import java.util.List;
public final class Book {
private String name;
private Entry featured;
private List<Entry> entries = new ArrayList<>();
public static Book sample(String name) {
var book = new Book();
book.setName(name);
var featured = new Entry("Featured");
featured.setDetail(new Entry("Nested entry"));
book.setFeatured(featured);
book.getEntries().add(new Entry("First entry"));
book.getEntries().add(new Entry("Second entry"));
return book;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Entry getFeatured() { return featured; }
public void setFeatured(Entry featured) { this.featured = featured; }
public List<Entry> getEntries() { return entries; }
public void setEntries(List<Entry> entries) { this.entries = entries; }
}
@@ -0,0 +1,18 @@
package fixture.spring.model;
public final class Entry {
private String name;
private Entry detail;
public Entry(String name) {
this.name = name;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Entry getDetail() { return detail; }
public void setDetail(Entry detail) { this.detail = detail; }
}
@@ -0,0 +1,31 @@
package fixture.spring.ui;
import fixture.spring.app.FixtureService;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public final class BookController {
private final FixtureService service;
@FXML
private TextField bookName;
@Inject
public BookController(FixtureService service) {
this.service = service;
service.created(this);
}
@FXML
private void initialize() {
bookName.setPromptText(service.label());
bookName.setUserData(this);
}
public FixtureService service() { return service; }
@PreDestroy
public void dispose() { service.release(this); }
}
@@ -0,0 +1,29 @@
package fixture.spring.ui;
import fixture.spring.app.FixtureService;
import fixture.spring.model.Entry;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
public final class EntryCard extends VBox {
private final FixtureService service;
private final ObjectProperty<Entry> model = new SimpleObjectProperty<>(this, "model");
@Inject
public EntryCard(FixtureService service) {
this.service = service;
service.created(this);
}
public ObjectProperty<Entry> modelProperty() { return model; }
public Entry getModel() { return model.get(); }
public void setModel(Entry entry) { model.set(entry); }
@PreDestroy
public void dispose() { service.release(this); }
}
@@ -0,0 +1,29 @@
package fixture.spring.ui;
import fixture.spring.app.FixtureService;
import fixture.spring.model.Entry;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
public final class EntryPanel extends VBox {
private final FixtureService service;
private final ObjectProperty<Entry> model = new SimpleObjectProperty<>(this, "model");
@Inject
public EntryPanel(FixtureService service) {
this.service = service;
service.created(this);
}
public ObjectProperty<Entry> modelProperty() { return model; }
public Entry getModel() { return model.get(); }
public void setModel(Entry entry) { model.set(entry); }
@PreDestroy
public void dispose() { service.release(this); }
}
@@ -0,0 +1,16 @@
module fixture.spring.app {
requires fx;
requires jakarta.annotation;
requires jakarta.inject;
requires javafx.controls;
requires javafx.fxml;
requires spring.beans;
requires spring.context;
exports fixture.spring.app;
exports fixture.spring.model;
exports fixture.spring.ui;
opens fixture.spring.model to fx;
opens fixture.spring.ui;
}
@@ -0,0 +1,2 @@
<?import javafx.scene.layout.VBox?>
<VBox/>
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model fixture.spring.model.Book?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.Column?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import de.neitzel.fx.view.Repeat?>
<?import de.neitzel.fx.view.Table?>
<?import fixture.spring.ui.EntryPanel?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="fixture.spring.ui.BookController" spacing="8">
<fx:define>
<BindingList>
<DirectBinding control="bookName" property="text" path="name" direction="both"/>
<DirectBinding control="convertedName" property="text" path="name" direction="view"
converter="fixture.spring.app.SpringBookContext$NameConverter"/>
<DirectBinding control="featured" property="model" path="featured" direction="both"/>
<Repeat pane="entries" component="fixture.spring.ui.EntryCard" collection="entries"/>
</BindingList>
</fx:define>
<TextField fx:id="bookName"/>
<Label fx:id="convertedName"/>
<EntryPanel fx:id="featured"/>
<VBox fx:id="entries"/>
<Table fx:id="entriesTable" collection="entries" row="fixture.spring.ui.EntryCard" prefHeight="120">
<Column header="Entry" attribute="name"/>
</Table>
</VBox>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model fixture.spring.model.Entry?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList>
<DirectBinding control="entryName" property="text" path="name" direction="both"/>
</BindingList>
</fx:define>
<TextField fx:id="entryName"/>
</fx:root>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model fixture.spring.model.Entry?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import fixture.spring.ui.EntryCard?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList>
<DirectBinding control="nested" property="model" path="detail" direction="both"/>
</BindingList>
</fx:define>
<EntryCard fx:id="nested"/>
</fx:root>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import fixture.spring.ui.EntryCard?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="fixture.spring.ui.BookController">
<TextField fx:id="bookName"/>
<EntryCard unknownProperty="fails after acquisition"/>
</VBox>
@@ -0,0 +1,54 @@
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import de.neitzel.fxdesigner.preview.ExampleDescriptor;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import java.util.Optional;
import de.neitzel.fxdesigner.target.PreviewFailure;
import de.neitzel.fxdesigner.target.TargetPreview;
import java.time.Duration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
/** Runs against FX 1.0.6 without linking the newer adapter types in the launcher. */
public final class CapabilityCheck {
public static void main(String[] args) throws Exception {
Platform.startup(() -> Platform.setImplicitExit(false));
try {
var descriptor = new ExampleDescriptor("book", "Missing adapter", "java.lang.String",
"CapabilityCheck$Provider", "Book.fxml", "fixture");
try (var target = TargetPreview.open(descriptor, CapabilityCheck.class.getClassLoader(), Duration.ofSeconds(20))) {
try {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
throw new AssertionError("Expected missing FX adapter API");
} catch (ExecutionException failure) {
var diagnostic = (PreviewFailure) failure.getCause();
if (diagnostic.code() != PreviewFailure.Code.CONTEXT_TYPE
|| !diagnostic.getMessage().contains("1.0.7")) throw new AssertionError(diagnostic);
}
target.cleanup().toCompletableFuture().get(5, TimeUnit.SECONDS);
System.out.println("PASS missing-capability 1");
}
} finally {
Platform.exit();
}
}
// Linking this Provider itself needs the new interface, before opening any preview session.
public static final class Provider implements PreviewProvider<String, ViewDependencies>, ViewDependencies {
public Class<String> modelType() { return String.class; }
public PreviewSession<String, ViewDependencies> open(String id) {
throw new AssertionError("Provider unexpectedly loaded with the old FX runtime");
}
public boolean isComponent(Class<?> type) { return false; }
public <T> Optional<T> findService(Class<T> type) { return Optional.empty(); }
public <T> ViewObject<T> createViewObject(Class<T> type) {
throw new UnsupportedOperationException();
}
}
}
@@ -0,0 +1,246 @@
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.fx.view.ViewObject;
import de.neitzel.fxdesigner.preview.ExampleDescriptor;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.fxdesigner.target.ExampleCatalog;
import de.neitzel.fxdesigner.target.PreviewFailure;
import de.neitzel.fxdesigner.target.TargetPreview;
import fixture.spring.app.FixtureService;
import fixture.spring.app.SpringBook;
import fixture.spring.app.SpringBookContext;
import fixture.spring.model.Book;
import fixture.spring.preview.BookExamples;
import fixture.spring.ui.BookController;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public final class SpringChecks {
private static final String UI = "fixture/spring/ui/";
private static int assertions;
public static void main(String[] args) throws Exception {
Platform.startup(() -> Platform.setImplicitExit(false));
try {
if (args[0].equals("application")) {
fx(() -> { application(); return null; });
} else {
preview(args[0]);
}
System.out.println("PASS " + args[0] + " " + assertions);
} finally {
Platform.exit();
}
}
private static void application() throws Exception {
var app = new SpringBook();
var stage = new Stage();
try {
app.start(stage);
check(stage.isShowing() && name(stage.getScene().getRoot()).getText().equals("Spring contact book"),
"normal application launch");
} finally {
stage.close();
app.stop();
}
FixtureService service;
try (var spring = SpringBookContext.open("Application check"); var models = new ViewModelContext()) {
service = spring.service();
var fxml = BookController.class.getResource("Book.fxml");
var model = Book.sample("Local contact book");
var first = ViewLoader.loadWithDependencies(fxml, model, spring.dependencies(), models);
var second = ViewLoader.loadWithDependencies(fxml, model, spring.dependencies(), models);
var firstRoot = first.getRoot();
var secondRoot = second.getRoot();
checkBook(firstRoot, "Local contact book", "Application check");
var firstController = (BookController) name(firstRoot).getUserData();
var otherController = (BookController) name(secondRoot).getUserData();
check(firstController != otherController && firstController.service() == otherController.service(),
"prototype controllers share one injected service");
check(firstRoot.lookup("#featured") != secondRoot.lookup("#featured"), "distinct embedded Components");
check(service.liveCount() == 14, "seven UI instances per view");
model.getEntries().removeFirst();
check(service.releasedCount() == 4 && service.liveCount() == 10, "Repeat and Table entries released");
first.close();
first.close();
check(service.releasedCount() == 9 && otherController.service() == spring.service(),
"one close preserves the other View and the service");
try {
ViewLoader.loadWithDependencies(BookController.class.getResource("Invalid.fxml"),
model, spring.dependencies(), models);
throw new AssertionError("Invalid child loaded");
} catch (IllegalStateException expected) {
check(service.releasedCount() == 11 && service.liveCount() == 5, "child and controller rollback");
}
}
checkClosed(service);
}
private static void preview(String mode) throws Exception {
var loader = SpringChecks.class.getClassLoader();
var descriptors = ExampleCatalog.discover(loader);
check(descriptors.size() == 2, "exact fixture descriptors");
var listed = descriptors.stream().filter(d -> d.id().equals(mode.equals("card") ? "card" : "book"))
.findFirst().orElseThrow();
check(BookExamples.lastService() == null, "discovery did not open provider");
var selected = switch (mode) {
case "invalid" -> with(listed, mode, listed.providerClass(), UI + "Invalid.fxml");
case "release-failure" -> with(listed, mode, FailingReleaseExample.class.getName(), listed.viewResource());
case "wrong-context" -> with(listed, mode, WrongExample.class.getName(), listed.viewResource());
case "missing-resource" -> with(listed, mode, listed.providerClass(), "missing/Book.fxml");
case "closed-resource" -> with(listed, mode, listed.providerClass(), "fixture/spring/app/Closed.fxml");
default -> with(listed, mode, listed.providerClass(), listed.viewResource());
};
try (var target = TargetPreview.open(selected, loader, Duration.ofSeconds(20))) {
if (mode.equals("cancel")) {
check(fx(() -> BookExamples.lastService().liveCount()) == 7, "waited for live View");
target.cancel();
}
switch (mode) {
case "release-failure" -> {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
target.close();
try {
target.cleanup().toCompletableFuture().get(5, TimeUnit.SECONDS);
throw new AssertionError("Expected View cleanup failure");
} catch (ExecutionException failure) {
check(((PreviewFailure) failure.getCause()).code() == PreviewFailure.Code.CLEANUP,
"failed release reported");
}
}
case "book", "card" -> {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
fx(() -> {
Parent root = target.loadedView().getRoot();
if (mode.equals("book")) {
checkBook(root, "Preview contact book", "Preview service");
name(root).setText("Edited in preview");
check(((Label) root.lookup("#convertedName")).getText().equals("[Edited in preview]"),
"live binding in preview");
} else {
check(((TextField) root.lookup("#entryName")).getText().equals("Preview entry"),
"standalone fx:root Component loaded");
}
check(target.render(420, 240).length == 420 * 240 * 4, "target rendered");
return null;
});
}
default -> expectFailure(target, mode);
}
}
// The call to close() from the test thread posts to FX. The next FX action follows it.
if (java.util.Set.of("book", "invalid", "readiness", "cancel", "missing-resource", "closed-resource",
"release-failure").contains(mode))
fx(() -> { checkClosed(BookExamples.lastService()); return null; });
}
private static ExampleDescriptor with(ExampleDescriptor d, String mode, String provider, String resource) {
return new ExampleDescriptor(mode, d.label(), d.modelType(), provider, resource, d.componentPackage());
}
private static void expectFailure(TargetPreview target, String mode) throws Exception {
var expected = switch (mode) {
case "cancel" -> PreviewFailure.Code.CANCELLED;
case "readiness" -> PreviewFailure.Code.READINESS;
case "invalid" -> PreviewFailure.Code.LOAD;
case "closed-resource" -> PreviewFailure.Code.MODULE_ACCESS;
case "missing-resource" -> PreviewFailure.Code.RESOURCE;
default -> PreviewFailure.Code.CONTEXT_TYPE;
};
try {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
throw new AssertionError("Expected " + expected);
} catch (ExecutionException failure) {
var diagnostic = (PreviewFailure) failure.getCause();
check(diagnostic.code() == expected, "expected " + expected + ", got " + diagnostic);
}
target.cleanup().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
private static void checkBook(Parent root, String text, String service) {
check(name(root).getText().equals(text) && name(root).getPromptText().equals(service), "FXML and injected service");
check(((Label) root.lookup("#convertedName")).getText().equals("[" + text + "]"), "Spring Converter");
var panel = (Parent) root.lookup("#featured");
check(((TextField) panel.lookup("#entryName")).getText().equals("Nested entry"), "nested Component");
check(((VBox) root.lookup("#entries")).getChildren().size() == 2, "Repeat children");
check(root.lookup("#entriesTable") != null, "Table loaded");
}
private static TextField name(Parent root) { return (TextField) root.lookup("#bookName"); }
private static void checkClosed(FixtureService service) {
check(service.liveAtShutdown() == 0 && service.shutdownCount() == 1,
"context closed once, after all View objects were destroyed");
}
private static <T> T fx(Callable<T> action) throws Exception {
var task = new FutureTask<T>(action);
Platform.runLater(task);
return task.get(20, TimeUnit.SECONDS);
}
private static void check(boolean ok, String message) {
if (!ok) throw new AssertionError(message);
assertions++;
}
public static final class FailingReleaseExample implements PreviewProvider<Book, ViewDependencies> {
@Override
public Class<Book> modelType() { return Book.class; }
@Override
public PreviewSession<Book, ViewDependencies> open(String id) {
var delegate = new BookExamples().open(id);
var dependencies = delegate.context();
return new PreviewSession<>() {
public Book model() { return delegate.model(); }
public ViewDependencies context() {
return new ViewDependencies() {
public boolean isComponent(Class<?> type) { return dependencies.isComponent(type); }
public <T> Optional<T> findService(Class<T> type) { return dependencies.findService(type); }
public <T> ViewObject<T> createViewObject(Class<T> type) {
var acquired = dependencies.createViewObject(type);
return new ViewObject<>(acquired.instance(), () -> {
acquired.release().run();
if (type == BookController.class) throw new IllegalStateException("release failed");
});
}
};
}
public void close() throws Exception { delegate.close(); }
};
}
}
public static final class WrongExample implements PreviewProvider<Book, Object> {
@Override
public Class<Book> modelType() { return Book.class; }
@Override
public PreviewSession<Book, Object> open(String id) {
return new PreviewSession<>() {
public Book model() { return new Book(); }
public Object context() { return new Object(); }
public void close() {}
};
}
}
}
@@ -0,0 +1,23 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di-legacy-runtime</artifactId>
<version>1</version>
<properties>
<neitzellib.version>1.0.6</neitzellib.version>
</properties>
<repositories>
<repository>
<id>gitea-neitzelfxdesigner</id>
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${neitzellib.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,22 @@
{
"schemaVersion": "1.0",
"contexts": {
"spring": {
"applicationModule": "app",
"launchMode": "module-path",
"buildRuntime": "java25",
"targetRuntime": "java25",
"buildJava": 25,
"targetJava": 25,
"preview": {
"sourceSet": "module",
"module": "preview",
"provider": "fixture.spring.preview.BookExamples",
"defaultExample": "book"
},
"modulePath": {
"entryModule": "fixture.spring.preview"
}
}
}
}
+38
View File
@@ -0,0 +1,38 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di</artifactId>
<version>1</version>
<packaging>pom</packaging>
<modules>
<module>app</module>
<module>preview</module>
</modules>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<designer.version>0.1.1-SNAPSHOT</designer.version>
<jakarta-annotation.version>2.1.1</jakarta-annotation.version>
<jakarta-inject.version>2.0.1</jakarta-inject.version>
<neitzellib.version>1.0.7-SNAPSHOT</neitzellib.version>
<spring.version>6.2.11</spring.version>
<javafx-maven-plugin.version>0.0.8</javafx-maven-plugin.version>
<maven-compiler-plugin.version>3.16.0</maven-compiler-plugin.version>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
@@ -0,0 +1,21 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di</artifactId>
<version>1</version>
</parent>
<artifactId>spring-di-preview</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di-app</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.fxdesigner</groupId>
<artifactId>designer-preview-api</artifactId>
<version>${designer.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,44 @@
package fixture.spring.preview;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import fixture.spring.app.FixtureService;
import fixture.spring.app.SpringBookContext;
import fixture.spring.model.Book;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
public final class BookExamples implements PreviewProvider<Book, ViewDependencies> {
private static FixtureService lastService;
public static FixtureService lastService() { return lastService; }
@Override
public Class<Book> modelType() { return Book.class; }
@Override
public PreviewSession<Book, ViewDependencies> open(String id) {
var book = Book.sample("Preview contact book");
var spring = SpringBookContext.open("Preview service");
lastService = spring.service();
return new PreviewSession<>() {
@Override
public Book model() { return book; }
@Override
public ViewDependencies context() { return spring.dependencies(); }
@Override
public CompletionStage<Void> ready() {
if (id.equals("cancel")) return new CompletableFuture<>();
if (id.equals("readiness")) return CompletableFuture.failedFuture(new IllegalStateException("Example failed"));
return PreviewSession.super.ready();
}
@Override
public void close() { spring.close(); }
};
}
}
@@ -0,0 +1,29 @@
package fixture.spring.preview;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import fixture.spring.app.SpringBookContext;
import fixture.spring.model.Entry;
public final class CardExamples implements PreviewProvider<Entry, ViewDependencies> {
@Override
public Class<Entry> modelType() { return Entry.class; }
@Override
public PreviewSession<Entry, ViewDependencies> open(String id) {
var model = new Entry("Preview entry");
var spring = SpringBookContext.open("Card preview service");
return new PreviewSession<>() {
@Override
public Entry model() { return model; }
@Override
public ViewDependencies context() { return spring.dependencies(); }
@Override
public void close() { spring.close(); }
};
}
}
@@ -0,0 +1,7 @@
module fixture.spring.preview {
requires de.neitzel.fxdesigner.preview;
requires fixture.spring.app;
requires fx;
exports fixture.spring.preview;
}
@@ -0,0 +1,14 @@
format=1
count=2
example.0.id=book
example.0.label=Spring contact book
example.0.modelType=fixture.spring.model.Book
example.0.providerClass=fixture.spring.preview.BookExamples
example.0.viewResource=fixture/spring/ui/Book.fxml
example.0.componentPackage=fixture.spring.app
example.1.id=card
example.1.label=Spring entry
example.1.modelType=fixture.spring.model.Entry
example.1.providerClass=fixture.spring.preview.CardExamples
example.1.viewResource=fixture/spring/ui/EntryCard.fxml
example.1.componentPackage=fixture.spring.app