Complete the contact book example and Designer tutorial
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.fxdesigner.preview.PreviewProvider;
|
||||
import de.neitzel.fxdesigner.preview.PreviewSession;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
|
||||
public final class AddressPreviewProvider implements PreviewProvider<Address, ApplicationContext> {
|
||||
|
||||
@Override
|
||||
public Class<Address> modelType() {
|
||||
return Address.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreviewSession<Address, ApplicationContext> open(String exampleId) {
|
||||
if (!"address".equals(exampleId)) {
|
||||
throw new IllegalArgumentException("Unbekanntes Adressbeispiel: " + exampleId);
|
||||
}
|
||||
Address address = new Address("12 Analytical Engine Way", "4B", "00123", "London",
|
||||
"Vereinigtes Königreich", "Hinterhaus");
|
||||
return new AddressSession(address, new ApplicationContext(ContactBookApp.class));
|
||||
}
|
||||
|
||||
private record AddressSession(Address model, ApplicationContext context)
|
||||
implements PreviewSession<Address, ApplicationContext> {
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.contactbook.view.AddressEditor;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.fx.view.ViewLoader;
|
||||
import de.neitzel.fx.view.ViewModelContext;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.TextField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
|
||||
@FxTest
|
||||
class AddressPreviewProviderTest {
|
||||
|
||||
@Test
|
||||
void eachStandaloneAddressPreviewHasFreshModelAndContext(FxFixture fx) throws Exception {
|
||||
AddressPreviewProvider provider = new AddressPreviewProvider();
|
||||
var first = provider.open("address");
|
||||
var second = provider.open("address");
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
LoadedView loaded = fx.call(() -> ViewLoader.loadComponent(
|
||||
AddressEditor.class, first.model(), first.context(), models));
|
||||
|
||||
assertEquals(Address.class, provider.modelType());
|
||||
assertNotSame(first.model(), second.model());
|
||||
assertNotSame(first.context(), second.context());
|
||||
fx.run(() -> {
|
||||
AddressEditor editor = (AddressEditor) loaded.getRoot();
|
||||
assertEquals("00123", ((TextField) editor.lookup("#postalCodeField")).getText());
|
||||
((TextField) editor.lookup("#postalCodeField")).setText("00456");
|
||||
assertEquals("00456", first.model().getPostalCode());
|
||||
assertEquals("00123", second.model().getPostalCode());
|
||||
assertFalse(((Button) editor.lookup("#removeAddressButton")).isManaged());
|
||||
});
|
||||
|
||||
fx.run(() -> {
|
||||
loaded.close();
|
||||
models.close();
|
||||
});
|
||||
first.close();
|
||||
second.close();
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -2,6 +2,7 @@ package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.storage.ContactBookStorage;
|
||||
import de.neitzel.fxdesigner.preview.PreviewProvider;
|
||||
import de.neitzel.fxdesigner.preview.PreviewSession;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
@@ -18,7 +19,9 @@ public final class ContactBookPreviewProvider implements PreviewProvider<Contact
|
||||
if (!"contact-book".equals(exampleId)) {
|
||||
throw new IllegalArgumentException("Unbekanntes Kontaktbeispiel: " + exampleId);
|
||||
}
|
||||
return new ContactBookSession(ContactBookApp.sample(), new ApplicationContext(ContactBookApp.class));
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
context.getComponent(ContactBookStorage.class).useSnapshot();
|
||||
return new ContactBookSession(ContactBookApp.sample(), context);
|
||||
}
|
||||
|
||||
private record ContactBookSession(ContactBook model, ApplicationContext context)
|
||||
|
||||
+38
-4
@@ -1,14 +1,21 @@
|
||||
package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.view.ContactBookController;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.fxdesigner.preview.PreviewSession;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
import javafx.scene.Parent;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.TextField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
|
||||
@FxTest
|
||||
class ContactBookPreviewProviderTest {
|
||||
@@ -18,19 +25,46 @@ class ContactBookPreviewProviderTest {
|
||||
ContactBookPreviewProvider provider = new ContactBookPreviewProvider();
|
||||
var first = provider.open("contact-book");
|
||||
var second = provider.open("contact-book");
|
||||
LoadedView view = fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
first.model(), first.context());
|
||||
LoadedView view = load(fx, first);
|
||||
LoadedView secondView = load(fx, second);
|
||||
|
||||
assertNotSame(first.model(), second.model());
|
||||
assertNotSame(first.model().getContacts().getFirst(), second.model().getContacts().getFirst());
|
||||
assertNotSame(first.context(), second.context());
|
||||
fx.await("preview contact details", () -> hasNameField(fx, view));
|
||||
fx.run(() -> ((TextField) view.getRoot().lookup("#nameField")).setText("Preview-only name"));
|
||||
fx.await("second preview contact details", () -> hasNameField(fx, secondView));
|
||||
fx.run(() -> {
|
||||
((TextField) view.getRoot().lookup("#nameField")).setText("Preview-only name");
|
||||
((Button) view.getRoot().lookup("#saveContactBookButton")).fire();
|
||||
((TextField) view.getRoot().lookup("#nameField")).setText("Not yet saved");
|
||||
((Button) view.getRoot().lookup("#loadContactBookButton")).fire();
|
||||
((TextField) secondView.getRoot().lookup("#nameField")).setText("Unabhängige Session");
|
||||
((Button) secondView.getRoot().lookup("#loadContactBookButton")).fire();
|
||||
});
|
||||
assertEquals("Preview-only name", first.model().getContacts().getFirst().getName());
|
||||
assertEquals("Unabhängige Session", second.model().getSelectedContact().getName());
|
||||
assertEquals("Preview-only name", first.model().getSelectedContact().getName());
|
||||
assertEquals("Ada Lovelace", second.model().getSelectedContact().getName());
|
||||
assertSame(first.model().getContacts().getFirst(), first.model().getSelectedContact());
|
||||
|
||||
var restarted = provider.open("contact-book");
|
||||
LoadedView restartedView = load(fx, restarted);
|
||||
fx.await("restarted preview contact details", () -> hasNameField(fx, restartedView));
|
||||
assertEquals("Ada Lovelace", restarted.model().getContacts().getFirst().getName());
|
||||
|
||||
first.close();
|
||||
second.close();
|
||||
restarted.close();
|
||||
}
|
||||
|
||||
private static LoadedView load(FxFixture fx,
|
||||
PreviewSession<ContactBook, ApplicationContext> session) throws Exception {
|
||||
LoadedView view = fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
session.model(), session.context());
|
||||
fx.run(() -> {
|
||||
new Scene((Parent) view.getRoot());
|
||||
view.getRoot().applyCss();
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
private static boolean hasNameField(FxFixture fx, LoadedView view) {
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import de.neitzel.fxdesigner.preview.PreviewProvider;
|
||||
import de.neitzel.fxdesigner.preview.PreviewSession;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
|
||||
public final class PhoneNumberPreviewProvider implements PreviewProvider<PhoneNumber, ApplicationContext> {
|
||||
|
||||
@Override
|
||||
public Class<PhoneNumber> modelType() {
|
||||
return PhoneNumber.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreviewSession<PhoneNumber, ApplicationContext> open(String exampleId) {
|
||||
if (!"phone-number".equals(exampleId)) {
|
||||
throw new IllegalArgumentException("Unbekanntes Telefonbeispiel: " + exampleId);
|
||||
}
|
||||
return new PhoneNumberSession(new PhoneNumber("+49 301234567"),
|
||||
new ApplicationContext(ContactBookApp.class));
|
||||
}
|
||||
|
||||
private record PhoneNumberSession(PhoneNumber model, ApplicationContext context)
|
||||
implements PreviewSession<PhoneNumber, ApplicationContext> {
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import de.neitzel.contactbook.view.PhoneNumberEditor;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.fx.view.ViewLoader;
|
||||
import de.neitzel.fx.view.ViewModelContext;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.TextField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
|
||||
@FxTest
|
||||
class PhoneNumberPreviewProviderTest {
|
||||
|
||||
@Test
|
||||
void eachStandalonePhonePreviewHasFreshModelAndContext(FxFixture fx) throws Exception {
|
||||
PhoneNumberPreviewProvider provider = new PhoneNumberPreviewProvider();
|
||||
var first = provider.open("phone-number");
|
||||
var second = provider.open("phone-number");
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
LoadedView loaded = fx.call(() -> ViewLoader.loadComponent(
|
||||
PhoneNumberEditor.class, first.model(), first.context(), models));
|
||||
|
||||
assertEquals(PhoneNumber.class, provider.modelType());
|
||||
assertNotSame(first.model(), second.model());
|
||||
assertNotSame(first.context(), second.context());
|
||||
fx.run(() -> {
|
||||
PhoneNumberEditor editor = (PhoneNumberEditor) loaded.getRoot();
|
||||
((TextField) editor.lookup("#nationalNumberField")).setText("030 / 9876543");
|
||||
assertEquals("+49 309876543", first.model().getValue());
|
||||
assertEquals("+49 301234567", second.model().getValue());
|
||||
assertFalse(((Button) editor.lookup("#removePhoneNumberButton")).isManaged());
|
||||
});
|
||||
|
||||
fx.run(() -> {
|
||||
loaded.close();
|
||||
models.close();
|
||||
});
|
||||
first.close();
|
||||
second.close();
|
||||
}
|
||||
}
|
||||
+14
-2
@@ -1,8 +1,20 @@
|
||||
format=1
|
||||
count=1
|
||||
count=3
|
||||
example.0.id=contact-book
|
||||
example.0.label=Kontaktverwaltung · Beispieldaten
|
||||
example.0.modelType=de.neitzel.contactbook.model.ContactBook
|
||||
example.0.providerClass=de.neitzel.contactbook.preview.ContactBookPreviewProvider
|
||||
example.0.viewResource=de/neitzel/contactbook/view/ContactBook.fxml
|
||||
example.0.componentPackage=de.neitzel.contactbook.view
|
||||
example.0.componentPackage=de.neitzel.contactbook.view
|
||||
example.1.id=phone-number
|
||||
example.1.label=Telefonnummer · Beispieldaten
|
||||
example.1.modelType=de.neitzel.contactbook.model.PhoneNumber
|
||||
example.1.providerClass=de.neitzel.contactbook.preview.PhoneNumberPreviewProvider
|
||||
example.1.viewResource=de/neitzel/contactbook/view/PhoneNumberEditor.fxml
|
||||
example.1.componentPackage=de.neitzel.contactbook.view
|
||||
example.2.id=address
|
||||
example.2.label=Adresse · Beispieldaten
|
||||
example.2.modelType=de.neitzel.contactbook.model.Address
|
||||
example.2.providerClass=de.neitzel.contactbook.preview.AddressPreviewProvider
|
||||
example.2.viewResource=de/neitzel/contactbook/view/AddressEditor.fxml
|
||||
example.2.componentPackage=de.neitzel.contactbook.view
|
||||
@@ -1,7 +1,9 @@
|
||||
package de.neitzel.contactbook;
|
||||
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import de.neitzel.contactbook.view.ContactBookController;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.fx.view.ViewLoader;
|
||||
@@ -21,7 +23,15 @@ public class ContactBookApp extends Application {
|
||||
public static ContactBook sample() {
|
||||
ContactBook book = new ContactBook();
|
||||
Contact ada = new Contact("Ada Lovelace");
|
||||
book.setContacts(new ArrayList<>(List.of(ada, new Contact("Grace Hopper"))));
|
||||
ada.addPhoneNumber(new PhoneNumber("+49 301234567"));
|
||||
ada.addPhoneNumber(new PhoneNumber("+43 12345678"));
|
||||
ada.addAddress(new Address("12 Analytical Engine Way", "4B", "00123", "London",
|
||||
"Vereinigtes Königreich", "Hinterhaus"));
|
||||
ada.addAddress(new Address("Musterstraße", "22", "01234", "Dresden", "Deutschland", ""));
|
||||
Contact grace = new Contact("Grace Hopper");
|
||||
grace.addPhoneNumber(new PhoneNumber("+41 446681818"));
|
||||
grace.addAddress(new Address("1600 Amphitheatre Parkway", "1", "94043", "Mountain View", "USA", ""));
|
||||
book.setContacts(new ArrayList<>(List.of(ada, grace)));
|
||||
book.setSelectedContact(ada);
|
||||
return book;
|
||||
}
|
||||
@@ -31,7 +41,7 @@ public class ContactBookApp extends Application {
|
||||
ApplicationContext services = new ApplicationContext(ContactBookApp.class);
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
LoadedView view = ViewLoader.load(
|
||||
ContactBookController.class.getResource("ContactBook.fxml"), sample(), services, models);
|
||||
ContactBookController.class.getResource("ContactBook.fxml"), new ContactBook(), services, models);
|
||||
stage.setTitle("Kontaktverwaltung · NeitzelLib FX");
|
||||
stage.setMinWidth(680);
|
||||
stage.setMinHeight(420);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package de.neitzel.contactbook.model;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street = "";
|
||||
private String houseNumber = "";
|
||||
private String postalCode = "";
|
||||
private String city = "";
|
||||
private String country = "";
|
||||
private String additionalInfo = "";
|
||||
private transient Contact owner;
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public Address(String street, String houseNumber, String postalCode, String city,
|
||||
String country, String additionalInfo) {
|
||||
setStreet(street);
|
||||
setHouseNumber(houseNumber);
|
||||
setPostalCode(postalCode);
|
||||
setCity(city);
|
||||
setCountry(country);
|
||||
setAdditionalInfo(additionalInfo);
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street == null ? "" : street;
|
||||
}
|
||||
|
||||
public String getHouseNumber() {
|
||||
return houseNumber;
|
||||
}
|
||||
|
||||
public void setHouseNumber(String houseNumber) {
|
||||
this.houseNumber = houseNumber == null ? "" : houseNumber;
|
||||
}
|
||||
|
||||
public String getPostalCode() {
|
||||
return postalCode;
|
||||
}
|
||||
|
||||
public void setPostalCode(String postalCode) {
|
||||
this.postalCode = postalCode == null ? "" : postalCode;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city == null ? "" : city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country == null ? "" : country;
|
||||
}
|
||||
|
||||
public String getAdditionalInfo() {
|
||||
return additionalInfo;
|
||||
}
|
||||
|
||||
public void setAdditionalInfo(String additionalInfo) {
|
||||
this.additionalInfo = additionalInfo == null ? "" : additionalInfo;
|
||||
}
|
||||
|
||||
public Contact owner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void owner(Contact owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
package de.neitzel.contactbook.model;
|
||||
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ObservableList;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Contact {
|
||||
|
||||
private String name = "";
|
||||
private ObservableList<PhoneNumber> phoneNumbers = FXCollections.observableArrayList();
|
||||
private ObservableList<Address> addresses = FXCollections.observableArrayList();
|
||||
|
||||
public Contact() {
|
||||
}
|
||||
@@ -18,4 +26,64 @@ public class Contact {
|
||||
public void setName(String name) {
|
||||
this.name = name == null ? "" : name;
|
||||
}
|
||||
|
||||
public List<PhoneNumber> getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
|
||||
Objects.requireNonNull(phoneNumbers, "phoneNumbers");
|
||||
for (PhoneNumber number : this.phoneNumbers) {
|
||||
if (!phoneNumbers.contains(number) && number.owner() == this) {
|
||||
number.owner(null);
|
||||
}
|
||||
}
|
||||
this.phoneNumbers = phoneNumbers instanceof ObservableList<?> observable
|
||||
? (ObservableList<PhoneNumber>) observable
|
||||
: FXCollections.observableArrayList(phoneNumbers);
|
||||
this.phoneNumbers.forEach(number -> number.owner(this));
|
||||
}
|
||||
|
||||
public void addPhoneNumber(PhoneNumber number) {
|
||||
Objects.requireNonNull(number, "number");
|
||||
number.owner(this);
|
||||
phoneNumbers.add(number);
|
||||
}
|
||||
|
||||
public void removePhoneNumber(PhoneNumber number) {
|
||||
if (phoneNumbers.remove(number)) {
|
||||
number.owner(null);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Address> getAddresses() {
|
||||
return addresses;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setAddresses(List<Address> addresses) {
|
||||
Objects.requireNonNull(addresses, "addresses");
|
||||
for (Address address : this.addresses) {
|
||||
if (!addresses.contains(address) && address.owner() == this) {
|
||||
address.owner(null);
|
||||
}
|
||||
}
|
||||
this.addresses = addresses instanceof ObservableList<?> observable
|
||||
? (ObservableList<Address>) observable
|
||||
: FXCollections.observableArrayList(addresses);
|
||||
this.addresses.forEach(address -> address.owner(this));
|
||||
}
|
||||
|
||||
public void addAddress(Address address) {
|
||||
Objects.requireNonNull(address, "address");
|
||||
address.owner(this);
|
||||
addresses.add(address);
|
||||
}
|
||||
|
||||
public void removeAddress(Address address) {
|
||||
if (addresses.remove(address)) {
|
||||
address.owner(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package de.neitzel.contactbook.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public record PhoneCountry(String isoCode, String name, String callingCode, String flag,
|
||||
int minNationalDigits, int maxNationalDigits, boolean trunkPrefix) {
|
||||
|
||||
private static final List<PhoneCountry> COUNTRIES = List.of(
|
||||
new PhoneCountry("DE", "Deutschland", "49", "🇩🇪", 5, 13, true),
|
||||
new PhoneCountry("AT", "Österreich", "43", "🇦🇹", 4, 13, true),
|
||||
new PhoneCountry("CH", "Schweiz", "41", "🇨🇭", 6, 12, true));
|
||||
|
||||
public String label() {
|
||||
return flag + " " + name + " (+" + callingCode + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return label();
|
||||
}
|
||||
|
||||
public static List<PhoneCountry> countries() {
|
||||
return COUNTRIES;
|
||||
}
|
||||
|
||||
public static Optional<PhoneCountry> byIsoCode(String isoCode) {
|
||||
return COUNTRIES.stream().filter(country -> country.isoCode.equals(isoCode)).findFirst();
|
||||
}
|
||||
|
||||
public static Optional<PhoneCountry> byCallingCode(String callingCode) {
|
||||
return COUNTRIES.stream().filter(country -> country.callingCode.equals(callingCode)).findFirst();
|
||||
}
|
||||
|
||||
public boolean supportsCanonicalNationalNumber(String nationalNumber) {
|
||||
return nationalNumber != null
|
||||
&& nationalNumber.matches("[0-9]+")
|
||||
&& nationalNumber.length() >= minNationalDigits
|
||||
&& nationalNumber.length() <= maxNationalDigits
|
||||
&& (!trunkPrefix || !nationalNumber.startsWith("0"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package de.neitzel.contactbook.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class PhoneNumber {
|
||||
|
||||
private static final Pattern CANONICAL_NUMBER = Pattern.compile("\\+(\\d{1,3}) ([0-9]+)");
|
||||
|
||||
private String value = "";
|
||||
private transient String draftCountryCode = "DE";
|
||||
private transient String draftNumber = "";
|
||||
private transient String validationError = "";
|
||||
private transient Contact owner;
|
||||
private transient List<Runnable> validationListeners = new ArrayList<>();
|
||||
|
||||
public PhoneNumber() {
|
||||
}
|
||||
|
||||
public PhoneNumber(String value) {
|
||||
setValue(value);
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value == null ? "" : value;
|
||||
}
|
||||
|
||||
public static boolean isCanonical(String value) {
|
||||
Matcher matcher = value == null ? null : CANONICAL_NUMBER.matcher(value);
|
||||
if (matcher == null || !matcher.matches()) {
|
||||
return false;
|
||||
}
|
||||
return PhoneCountry.byCallingCode(matcher.group(1))
|
||||
.map(country -> country.supportsCanonicalNationalNumber(matcher.group(2)))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
public String draftCountryCode() {
|
||||
return draftCountryCode;
|
||||
}
|
||||
|
||||
public String draftNumber() {
|
||||
return draftNumber;
|
||||
}
|
||||
|
||||
public String validationError() {
|
||||
return validationError;
|
||||
}
|
||||
|
||||
public void rememberDraft(String countryCode, String number, String error) {
|
||||
draftCountryCode = countryCode;
|
||||
draftNumber = number;
|
||||
String oldError = validationError;
|
||||
validationError = error;
|
||||
if (!oldError.equals(error)) {
|
||||
for (Runnable listener : List.copyOf(validationListeners)) {
|
||||
listener.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Contact owner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void owner(Contact owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public void addValidationListener(Runnable listener) {
|
||||
validationListeners.add(listener);
|
||||
}
|
||||
|
||||
public void removeValidationListener(Runnable listener) {
|
||||
validationListeners.remove(listener);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package de.neitzel.contactbook.storage;
|
||||
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
|
||||
interface ContactBookBackend {
|
||||
|
||||
Optional<ContactBook> load() throws IOException;
|
||||
|
||||
void save(ContactBook book) throws IOException;
|
||||
|
||||
String description();
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package de.neitzel.contactbook.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.StreamReadFeature;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
final class ContactBookJsonCodec {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper(JsonFactory.builder()
|
||||
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
|
||||
.build())
|
||||
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
|
||||
.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
|
||||
String encode(ContactBook book) throws IOException {
|
||||
Objects.requireNonNull(book, "book");
|
||||
List<ContactDocument> contacts = new ArrayList<>();
|
||||
for (Contact contact : book.getContacts()) {
|
||||
if (contact == null) {
|
||||
throw new IOException("Das Kontaktbuch enthält einen leeren Kontakteintrag.");
|
||||
}
|
||||
List<String> phoneNumbers = new ArrayList<>();
|
||||
for (PhoneNumber phoneNumber : contact.getPhoneNumbers()) {
|
||||
if (phoneNumber == null || !PhoneNumber.isCanonical(phoneNumber.getValue())) {
|
||||
throw new IOException("Das Kontaktbuch enthält eine ungültige Telefonnummer.");
|
||||
}
|
||||
phoneNumbers.add(phoneNumber.getValue());
|
||||
}
|
||||
List<AddressDocument> addresses = new ArrayList<>();
|
||||
for (Address address : contact.getAddresses()) {
|
||||
if (address == null) {
|
||||
throw new IOException("Das Kontaktbuch enthält einen leeren Adresseintrag.");
|
||||
}
|
||||
addresses.add(new AddressDocument(
|
||||
required(address.getStreet(), "Straße"),
|
||||
required(address.getHouseNumber(), "Hausnummer"),
|
||||
required(address.getPostalCode(), "Postleitzahl"),
|
||||
required(address.getCity(), "Ort"),
|
||||
required(address.getCountry(), "Land"),
|
||||
required(address.getAdditionalInfo(), "Adresszusatz")));
|
||||
}
|
||||
contacts.add(new ContactDocument(
|
||||
required(contact.getName(), "Kontaktname"), phoneNumbers, addresses));
|
||||
}
|
||||
return mapper.writeValueAsString(new ContactBookDocument(contacts));
|
||||
}
|
||||
|
||||
ContactBook decode(String json) throws IOException {
|
||||
ContactBookDocument document = mapper.readValue(json, ContactBookDocument.class);
|
||||
if (document == null || document.contacts() == null) {
|
||||
throw new IOException("Im JSON fehlt die Kontaktliste.");
|
||||
}
|
||||
|
||||
List<Contact> contacts = new ArrayList<>();
|
||||
for (ContactDocument contactDocument : document.contacts()) {
|
||||
if (contactDocument == null) {
|
||||
throw new IOException("Das JSON enthält einen leeren Kontakteintrag.");
|
||||
}
|
||||
String name = required(contactDocument.name(), "Kontaktname");
|
||||
if (contactDocument.phoneNumbers() == null || contactDocument.addresses() == null) {
|
||||
throw new IOException("Für jeden Kontakt müssen Telefonnummern und Adressen Listen sein.");
|
||||
}
|
||||
Contact contact = new Contact(name);
|
||||
for (String value : contactDocument.phoneNumbers()) {
|
||||
if (!PhoneNumber.isCanonical(value)) {
|
||||
throw new IOException("Ungültige Telefonnummer oder unbekannte Ländervorwahl: " + value);
|
||||
}
|
||||
contact.addPhoneNumber(new PhoneNumber(value));
|
||||
}
|
||||
for (AddressDocument addressDocument : contactDocument.addresses()) {
|
||||
if (addressDocument == null) {
|
||||
throw new IOException("Das JSON enthält einen leeren Adresseintrag.");
|
||||
}
|
||||
contact.addAddress(new Address(
|
||||
required(addressDocument.street(), "Straße"),
|
||||
required(addressDocument.houseNumber(), "Hausnummer"),
|
||||
required(addressDocument.postalCode(), "Postleitzahl"),
|
||||
required(addressDocument.city(), "Ort"),
|
||||
required(addressDocument.country(), "Land"),
|
||||
required(addressDocument.additionalInfo(), "Adresszusatz")));
|
||||
}
|
||||
contacts.add(contact);
|
||||
}
|
||||
|
||||
ContactBook book = new ContactBook();
|
||||
book.setContacts(contacts);
|
||||
return book;
|
||||
}
|
||||
|
||||
private static String required(String value, String field) throws IOException {
|
||||
if (value == null) {
|
||||
throw new IOException("Im JSON fehlt das Feld „" + field + "“.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
record ContactBookDocument(List<ContactDocument> contacts) {
|
||||
}
|
||||
|
||||
record ContactDocument(String name, List<String> phoneNumbers, List<AddressDocument> addresses) {
|
||||
}
|
||||
|
||||
record AddressDocument(String street, String houseNumber, String postalCode, String city,
|
||||
String country, String additionalInfo) {
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package de.neitzel.contactbook.storage;
|
||||
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import jakarta.inject.Singleton;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
@Singleton
|
||||
public final class ContactBookStorage {
|
||||
|
||||
private ContactBookBackend backend = new JsonContactBookStore(defaultFile());
|
||||
|
||||
public Optional<ContactBook> load() throws IOException {
|
||||
return backend.load();
|
||||
}
|
||||
|
||||
public void save(ContactBook book) throws IOException {
|
||||
backend.save(book);
|
||||
}
|
||||
|
||||
public String description() {
|
||||
return backend.description();
|
||||
}
|
||||
|
||||
public void useFile(Path file) {
|
||||
backend = new JsonContactBookStore(file);
|
||||
}
|
||||
|
||||
public void useSnapshot() {
|
||||
backend = new SnapshotContactBookStore();
|
||||
}
|
||||
|
||||
public static Path defaultFile() {
|
||||
return Path.of(System.getProperty("user.home"), ".contact-book", "contacts.json");
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package de.neitzel.contactbook.storage;
|
||||
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class JsonContactBookStore implements ContactBookBackend {
|
||||
|
||||
private final Path file;
|
||||
private final ContactBookJsonCodec codec = new ContactBookJsonCodec();
|
||||
private final AtomicFileMover fileMover;
|
||||
|
||||
public JsonContactBookStore(Path file) {
|
||||
this(file, (source, target) -> Files.move(source, target,
|
||||
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
|
||||
}
|
||||
|
||||
JsonContactBookStore(Path file, AtomicFileMover fileMover) {
|
||||
this.file = Objects.requireNonNull(file, "file").toAbsolutePath();
|
||||
if (this.file.getFileName() == null) {
|
||||
throw new IllegalArgumentException("Der Speicherpfad muss eine Datei bezeichnen.");
|
||||
}
|
||||
this.fileMover = Objects.requireNonNull(fileMover, "fileMover");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ContactBook> load() throws IOException {
|
||||
if (Files.notExists(file)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(codec.decode(Files.readString(file, StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ContactBook book) throws IOException {
|
||||
String json = codec.encode(book);
|
||||
Files.createDirectories(file.getParent());
|
||||
String prefix = file.getFileName() + ".";
|
||||
if (prefix.length() < 3) {
|
||||
prefix = "contact";
|
||||
}
|
||||
Path temporaryFile = Files.createTempFile(file.getParent(), prefix, ".tmp");
|
||||
try {
|
||||
Files.writeString(temporaryFile, json, StandardCharsets.UTF_8);
|
||||
fileMover.move(temporaryFile, file);
|
||||
} finally {
|
||||
Files.deleteIfExists(temporaryFile);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return file.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface AtomicFileMover {
|
||||
|
||||
void move(Path source, Path target) throws IOException;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package de.neitzel.contactbook.storage;
|
||||
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
|
||||
final class SnapshotContactBookStore implements ContactBookBackend {
|
||||
|
||||
private final ContactBookJsonCodec codec = new ContactBookJsonCodec();
|
||||
private String snapshot;
|
||||
|
||||
@Override
|
||||
public Optional<ContactBook> load() throws IOException {
|
||||
return snapshot == null ? Optional.empty() : Optional.of(codec.decode(snapshot));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ContactBook book) throws IOException {
|
||||
snapshot = codec.encode(book);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "nur in dieser Vorschau-Session";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import jakarta.inject.Singleton;
|
||||
import javafx.beans.property.ObjectProperty;
|
||||
import javafx.beans.property.SimpleObjectProperty;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.layout.VBox;
|
||||
|
||||
@Singleton
|
||||
public class AddressEditor extends VBox {
|
||||
|
||||
private final ObjectProperty<Object> model = new SimpleObjectProperty<>(this, "model");
|
||||
|
||||
@FXML
|
||||
private Button removeAddressButton;
|
||||
|
||||
private Address address;
|
||||
|
||||
public AddressEditor() {
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void initialize() {
|
||||
removeAddressButton.setVisible(false);
|
||||
removeAddressButton.setManaged(false);
|
||||
model.addListener((observable, oldModel, newModel) -> {
|
||||
address = (Address) newModel;
|
||||
updateRemoveButton();
|
||||
});
|
||||
}
|
||||
|
||||
public ObjectProperty<Object> modelProperty() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public Object getModel() {
|
||||
return model.get();
|
||||
}
|
||||
|
||||
public void setModel(Object model) {
|
||||
this.model.set(model);
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void removeAddress() {
|
||||
Contact owner = address == null ? null : address.owner();
|
||||
if (owner != null) {
|
||||
owner.removeAddress(address);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateRemoveButton() {
|
||||
boolean canRemove = address != null && address.owner() != null;
|
||||
removeAddressButton.setVisible(canRemove);
|
||||
removeAddressButton.setManaged(canRemove);
|
||||
}
|
||||
}
|
||||
+165
@@ -2,16 +2,21 @@ package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import de.neitzel.contactbook.storage.ContactBookStorage;
|
||||
import de.neitzel.fx.view.HasViewModel;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.fx.view.ViewLoader;
|
||||
import de.neitzel.fx.view.ViewModel;
|
||||
import de.neitzel.fx.view.ViewModelContext;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.inject.Singleton;
|
||||
import javafx.application.Platform;
|
||||
import javafx.beans.property.Property;
|
||||
import javafx.beans.value.ChangeListener;
|
||||
import javafx.collections.ListChangeListener;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.control.Button;
|
||||
@@ -20,6 +25,15 @@ import javafx.scene.control.ListCell;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.layout.StackPane;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Singleton
|
||||
public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
|
||||
@@ -35,8 +49,21 @@ public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
@FXML
|
||||
private Label emptyState;
|
||||
|
||||
@FXML
|
||||
private Label phoneValidationSummary;
|
||||
|
||||
@FXML
|
||||
private Label storageStatus;
|
||||
|
||||
@Inject
|
||||
private ContactBookStorage storage;
|
||||
|
||||
private ViewModel viewModel;
|
||||
private Property<Object> selectedContactAttribute;
|
||||
private ObservableList<Contact> observedContacts;
|
||||
private final Map<Contact, ListChangeListener<PhoneNumber>> phoneListListeners = new IdentityHashMap<>();
|
||||
private final Map<PhoneNumber, Runnable> phoneValidationListeners = new IdentityHashMap<>();
|
||||
private final ListChangeListener<Contact> contactListListener = change -> refreshContactListeners();
|
||||
private Contact currentContact;
|
||||
private LoadedView detailView;
|
||||
private ViewModelContext detailModels;
|
||||
@@ -66,6 +93,12 @@ public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
public void setViewModel(ViewModel viewModel) {
|
||||
this.viewModel = viewModel;
|
||||
selectedContactAttribute = attribute("selectedContact");
|
||||
@SuppressWarnings("unchecked")
|
||||
ObservableList<Contact> contacts = (ObservableList<Contact>) viewModel.property("contacts").getValue();
|
||||
observedContacts = contacts;
|
||||
observedContacts.addListener(contactListListener);
|
||||
loadAtStartup();
|
||||
refreshContactListeners();
|
||||
Platform.runLater(this::selectInitialContact);
|
||||
}
|
||||
|
||||
@@ -93,9 +126,53 @@ public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void saveBook() {
|
||||
String invalidPhone = firstInvalidPhone();
|
||||
if (invalidPhone != null) {
|
||||
storageStatus.setText("Speichern nicht möglich: " + invalidPhone);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ContactBook book = new ContactBook();
|
||||
book.setContacts(new ArrayList<>(contacts()));
|
||||
storage.save(book);
|
||||
storageStatus.setText("Kontaktbuch gespeichert: " + storage.description());
|
||||
} catch (IOException failure) {
|
||||
storageStatus.setText("Kontaktbuch konnte nicht gespeichert werden: " + failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void loadBook() {
|
||||
try {
|
||||
Optional<ContactBook> loaded = storage.load();
|
||||
if (loaded.isEmpty()) {
|
||||
storageStatus.setText("Keine gespeicherte Datei gefunden; das Kontaktbuch blieb unverändert.");
|
||||
return;
|
||||
}
|
||||
replaceContacts(loaded.get().getContacts());
|
||||
storageStatus.setText("Kontaktbuch geladen: " + storage.description());
|
||||
} catch (IOException failure) {
|
||||
storageStatus.setText("Kontaktbuch konnte nicht geladen werden: " + failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closeDetail();
|
||||
if (observedContacts != null) {
|
||||
observedContacts.removeListener(contactListListener);
|
||||
observedContacts = null;
|
||||
}
|
||||
for (Map.Entry<Contact, ListChangeListener<PhoneNumber>> entry : phoneListListeners.entrySet()) {
|
||||
phoneNumbers(entry.getKey()).removeListener(entry.getValue());
|
||||
}
|
||||
phoneListListeners.clear();
|
||||
for (Map.Entry<PhoneNumber, Runnable> entry : phoneValidationListeners.entrySet()) {
|
||||
entry.getKey().removeValidationListener(entry.getValue());
|
||||
}
|
||||
phoneValidationListeners.clear();
|
||||
}
|
||||
|
||||
private void selectInitialContact() {
|
||||
@@ -109,6 +186,41 @@ public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
contactList.getSelectionModel().select(selected);
|
||||
}
|
||||
|
||||
private void loadAtStartup() {
|
||||
try {
|
||||
Optional<ContactBook> loaded = storage.load();
|
||||
if (loaded.isPresent()) {
|
||||
replaceContacts(loaded.get().getContacts());
|
||||
storageStatus.setText("Kontaktbuch geladen: " + storage.description());
|
||||
} else {
|
||||
storageStatus.setText("Noch keine gespeicherte Datei: " + storage.description());
|
||||
}
|
||||
} catch (IOException failure) {
|
||||
storageStatus.setText("Kontaktbuch konnte nicht geladen werden: " + failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void replaceContacts(List<Contact> replacements) {
|
||||
contacts().setAll(replacements);
|
||||
contactList.getSelectionModel().clearSelection();
|
||||
Contact selected = contacts().isEmpty() ? null : contacts().getFirst();
|
||||
selectedContactAttribute.setValue(selected);
|
||||
if (selected != null) {
|
||||
contactList.getSelectionModel().select(selected);
|
||||
}
|
||||
}
|
||||
|
||||
private String firstInvalidPhone() {
|
||||
for (Contact contact : contacts()) {
|
||||
for (PhoneNumber number : phoneNumbers(contact)) {
|
||||
if (!number.validationError().isBlank() || !PhoneNumber.isCanonical(number.getValue())) {
|
||||
return "Telefonnummer von " + displayName(contact) + " ist ungültig. Bitte korrigieren oder entfernen.";
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void showDetails(Contact selected) {
|
||||
if (selected == currentContact && (selected == null || detailView != null)) {
|
||||
return;
|
||||
@@ -130,6 +242,7 @@ public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
detailModels = models;
|
||||
detailView = loaded;
|
||||
detailContainer.getChildren().setAll(loaded.getRoot());
|
||||
detailContainer.applyCss();
|
||||
observeName(loaded);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
models.close();
|
||||
@@ -163,6 +276,58 @@ public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
private void refreshContactListeners() {
|
||||
Set<Contact> current = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
current.addAll(observedContacts);
|
||||
for (Contact contact : new ArrayList<>(phoneListListeners.keySet())) {
|
||||
if (!current.contains(contact)) {
|
||||
phoneNumbers(contact).removeListener(phoneListListeners.remove(contact));
|
||||
}
|
||||
}
|
||||
for (Contact contact : current) {
|
||||
phoneListListeners.computeIfAbsent(contact, item -> {
|
||||
ListChangeListener<PhoneNumber> listener = change -> refreshPhoneListeners();
|
||||
phoneNumbers(item).addListener(listener);
|
||||
return listener;
|
||||
});
|
||||
}
|
||||
refreshPhoneListeners();
|
||||
}
|
||||
|
||||
private void refreshPhoneListeners() {
|
||||
Set<PhoneNumber> current = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
for (Contact contact : observedContacts) {
|
||||
current.addAll(phoneNumbers(contact));
|
||||
}
|
||||
for (PhoneNumber number : new ArrayList<>(phoneValidationListeners.keySet())) {
|
||||
if (!current.contains(number)) {
|
||||
number.removeValidationListener(phoneValidationListeners.remove(number));
|
||||
}
|
||||
}
|
||||
for (PhoneNumber number : current) {
|
||||
phoneValidationListeners.computeIfAbsent(number, item -> {
|
||||
Runnable listener = this::updatePhoneValidationSummary;
|
||||
item.addValidationListener(listener);
|
||||
return listener;
|
||||
});
|
||||
}
|
||||
updatePhoneValidationSummary();
|
||||
}
|
||||
|
||||
private void updatePhoneValidationSummary() {
|
||||
long invalid = phoneValidationListeners.keySet().stream()
|
||||
.filter(number -> !number.validationError().isBlank())
|
||||
.count();
|
||||
phoneValidationSummary.setText(invalid == 0
|
||||
? "Alle Telefonnummern sind gültig."
|
||||
: "Telefonnummern prüfen: " + invalid + (invalid == 1 ? " Eintrag ungültig." : " Einträge ungültig."));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static ObservableList<PhoneNumber> phoneNumbers(Contact contact) {
|
||||
return (ObservableList<PhoneNumber>) contact.getPhoneNumbers();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Property<Object> attribute(String name) {
|
||||
return (Property<Object>) viewModel.property(name);
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import de.neitzel.fx.view.HasViewModel;
|
||||
import de.neitzel.fx.view.ViewModel;
|
||||
import de.neitzel.fx.view.ViewModelClass;
|
||||
import jakarta.inject.Singleton;
|
||||
import javafx.fxml.FXML;
|
||||
|
||||
@Singleton
|
||||
@ViewModelClass(ContactDetailsViewModel.class)
|
||||
public class ContactDetailsController implements HasViewModel {
|
||||
|
||||
private ContactDetailsViewModel viewModel;
|
||||
|
||||
@Override
|
||||
public void setViewModel(ViewModel viewModel) {
|
||||
this.viewModel = (ContactDetailsViewModel) viewModel;
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void addPhoneNumber() {
|
||||
viewModel.contact().addPhoneNumber(new PhoneNumber());
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void addAddress() {
|
||||
viewModel.contact().addAddress(new Address());
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.fx.view.ViewModel;
|
||||
|
||||
public class ContactDetailsViewModel extends ViewModel {
|
||||
|
||||
private final Contact contact;
|
||||
|
||||
public ContactDetailsViewModel(Object model) {
|
||||
super(model);
|
||||
contact = (Contact) model;
|
||||
}
|
||||
|
||||
public Contact contact() {
|
||||
return contact;
|
||||
}
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.PhoneCountry;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import de.neitzel.fx.view.HasViewModel;
|
||||
import de.neitzel.fx.view.ViewModel;
|
||||
import jakarta.inject.Singleton;
|
||||
import javafx.beans.property.ObjectProperty;
|
||||
import javafx.beans.property.Property;
|
||||
import javafx.beans.property.SimpleObjectProperty;
|
||||
import javafx.beans.value.ChangeListener;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ComboBox;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.ListCell;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.util.StringConverter;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Singleton
|
||||
public class PhoneNumberEditor extends VBox implements HasViewModel, AutoCloseable {
|
||||
|
||||
private static final Pattern CANONICAL_NUMBER = Pattern.compile("\\+(\\d{1,3}) ([0-9]+)");
|
||||
private static final Pattern NATIONAL_NUMBER = Pattern.compile("[0-9\\s/().-]+");
|
||||
|
||||
private final ObjectProperty<Object> model = new SimpleObjectProperty<>(this, "model");
|
||||
|
||||
@FXML
|
||||
private ComboBox<PhoneCountry> countryChoice;
|
||||
|
||||
@FXML
|
||||
private TextField nationalNumberField;
|
||||
|
||||
@FXML
|
||||
private Label validationLabel;
|
||||
|
||||
@FXML
|
||||
private Button removePhoneNumberButton;
|
||||
|
||||
private PhoneNumber phoneNumber;
|
||||
private Property<Object> valueAttribute;
|
||||
private ChangeListener<Object> valueListener;
|
||||
private boolean updatingControls;
|
||||
|
||||
public PhoneNumberEditor() {
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void initialize() {
|
||||
countryChoice.getItems().setAll(PhoneCountry.countries());
|
||||
StringConverter<PhoneCountry> labels = new StringConverter<>() {
|
||||
@Override
|
||||
public String toString(PhoneCountry country) {
|
||||
return country == null ? "" : country.label();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PhoneCountry fromString(String value) {
|
||||
return countryChoice.getItems().stream()
|
||||
.filter(country -> country.label().equals(value))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
};
|
||||
countryChoice.setConverter(labels);
|
||||
countryChoice.setCellFactory(list -> new ListCell<>() {
|
||||
@Override
|
||||
protected void updateItem(PhoneCountry country, boolean empty) {
|
||||
super.updateItem(country, empty);
|
||||
setText(empty || country == null ? null : country.label());
|
||||
}
|
||||
});
|
||||
countryChoice.setButtonCell(new ListCell<>() {
|
||||
@Override
|
||||
protected void updateItem(PhoneCountry country, boolean empty) {
|
||||
super.updateItem(country, empty);
|
||||
setText(empty || country == null ? null : country.label());
|
||||
}
|
||||
});
|
||||
countryChoice.valueProperty().addListener((observable, oldValue, newValue) -> {
|
||||
if (!updatingControls && newValue != null) {
|
||||
validateAndStore();
|
||||
}
|
||||
});
|
||||
nationalNumberField.textProperty().addListener((observable, oldValue, newValue) -> {
|
||||
if (!updatingControls) {
|
||||
validateAndStore();
|
||||
}
|
||||
});
|
||||
removePhoneNumberButton.setVisible(false);
|
||||
removePhoneNumberButton.setManaged(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setViewModel(ViewModel viewModel) {
|
||||
phoneNumber = (PhoneNumber) getModel();
|
||||
@SuppressWarnings("unchecked")
|
||||
Property<Object> value = (Property<Object>) viewModel.property("value");
|
||||
valueAttribute = value;
|
||||
valueListener = (observable, oldValue, newValue) -> showValue((String) newValue);
|
||||
valueAttribute.addListener(valueListener);
|
||||
updateRemoveButton();
|
||||
|
||||
if (!phoneNumber.validationError().isBlank() || phoneNumber.getValue().isBlank()) {
|
||||
showDraft();
|
||||
} else {
|
||||
showValue(phoneNumber.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public ObjectProperty<Object> modelProperty() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public Object getModel() {
|
||||
return model.get();
|
||||
}
|
||||
|
||||
public void setModel(Object model) {
|
||||
this.model.set(model);
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void removePhoneNumber() {
|
||||
Contact owner = phoneNumber.owner();
|
||||
if (owner != null) {
|
||||
owner.removePhoneNumber(phoneNumber);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (valueAttribute != null && valueListener != null) {
|
||||
valueAttribute.removeListener(valueListener);
|
||||
}
|
||||
}
|
||||
|
||||
private void showDraft() {
|
||||
PhoneCountry country = PhoneCountry.byIsoCode(phoneNumber.draftCountryCode())
|
||||
.orElse(PhoneCountry.countries().getFirst());
|
||||
updatingControls = true;
|
||||
try {
|
||||
countryChoice.setValue(country);
|
||||
nationalNumberField.setText(phoneNumber.draftNumber());
|
||||
validationLabel.setText(phoneNumber.validationError());
|
||||
} finally {
|
||||
updatingControls = false;
|
||||
}
|
||||
if (phoneNumber.validationError().isBlank()) {
|
||||
validateAndStore();
|
||||
}
|
||||
}
|
||||
|
||||
private void showValue(String value) {
|
||||
Matcher matcher = value == null ? null : CANONICAL_NUMBER.matcher(value);
|
||||
if (matcher == null || !matcher.matches()) {
|
||||
String error = "Die gespeicherte Nummer hat kein gültiges Format.";
|
||||
phoneNumber.rememberDraft(phoneNumber.draftCountryCode(), phoneNumber.draftNumber(), error);
|
||||
validationLabel.setText(error);
|
||||
return;
|
||||
}
|
||||
PhoneCountry country = PhoneCountry.byCallingCode(matcher.group(1)).orElse(null);
|
||||
if (country == null) {
|
||||
String error = "Diese Ländervorwahl ist in der Beispielauswahl nicht enthalten.";
|
||||
phoneNumber.rememberDraft(phoneNumber.draftCountryCode(), matcher.group(2), error);
|
||||
validationLabel.setText(error);
|
||||
return;
|
||||
}
|
||||
String national = matcher.group(2);
|
||||
String error = canonicalNumberError(country, national);
|
||||
if (error != null) {
|
||||
setControls(country, national, error);
|
||||
phoneNumber.rememberDraft(country.isoCode(), national, error);
|
||||
return;
|
||||
}
|
||||
setControls(country, national, "");
|
||||
phoneNumber.rememberDraft(country.isoCode(), national, "");
|
||||
}
|
||||
|
||||
private void validateAndStore() {
|
||||
PhoneCountry country = countryChoice.getValue();
|
||||
if (country == null) {
|
||||
return;
|
||||
}
|
||||
Validation validation = validate(country, nationalNumberField.getText());
|
||||
String error = validation.error() == null ? "" : validation.error();
|
||||
phoneNumber.rememberDraft(country.isoCode(), nationalNumberField.getText(), error);
|
||||
validationLabel.setText(error);
|
||||
if (error.isEmpty()) {
|
||||
valueAttribute.setValue("+" + country.callingCode() + " " + validation.nationalNumber());
|
||||
}
|
||||
}
|
||||
|
||||
private static Validation validate(PhoneCountry country, String input) {
|
||||
if (input == null || input.isBlank()) {
|
||||
return new Validation(null, "Bitte gib eine Telefonnummer ein.");
|
||||
}
|
||||
if (!NATIONAL_NUMBER.matcher(input).matches()) {
|
||||
return new Validation(null, "Verwende nur Ziffern, Leerzeichen, /, Klammern oder Bindestriche.");
|
||||
}
|
||||
String digits = input.replaceAll("[^0-9]", "");
|
||||
if (country.trunkPrefix() && digits.startsWith("0")) {
|
||||
digits = digits.substring(1);
|
||||
}
|
||||
if (digits.length() < country.minNationalDigits()) {
|
||||
return new Validation(null, "Die Telefonnummer ist zu kurz.");
|
||||
}
|
||||
if (digits.length() > country.maxNationalDigits()) {
|
||||
return new Validation(null, "Die Telefonnummer ist zu lang.");
|
||||
}
|
||||
return new Validation(digits, null);
|
||||
}
|
||||
|
||||
private static String canonicalNumberError(PhoneCountry country, String nationalNumber) {
|
||||
if (country.supportsCanonicalNationalNumber(nationalNumber)) {
|
||||
return null;
|
||||
}
|
||||
if (country.trunkPrefix() && nationalNumber.startsWith("0")) {
|
||||
return "Die gespeicherte Nummer darf keine nationale Amtsnull enthalten.";
|
||||
}
|
||||
if (nationalNumber.length() < country.minNationalDigits()) {
|
||||
return "Die gespeicherte Telefonnummer ist zu kurz.";
|
||||
}
|
||||
if (nationalNumber.length() > country.maxNationalDigits()) {
|
||||
return "Die gespeicherte Telefonnummer ist zu lang.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void setControls(PhoneCountry country, String national, String error) {
|
||||
updatingControls = true;
|
||||
try {
|
||||
countryChoice.setValue(country);
|
||||
nationalNumberField.setText(national);
|
||||
validationLabel.setText(error);
|
||||
} finally {
|
||||
updatingControls = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void updateRemoveButton() {
|
||||
boolean canRemove = phoneNumber != null && phoneNumber.owner() != null;
|
||||
removePhoneNumberButton.setVisible(canRemove);
|
||||
removePhoneNumberButton.setManaged(canRemove);
|
||||
}
|
||||
|
||||
private record Validation(String nationalNumber, String error) {
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?neitzel-model de.neitzel.contactbook.model.Address?>
|
||||
|
||||
<?import de.neitzel.fx.view.BindingList?>
|
||||
<?import de.neitzel.fx.view.DirectBinding?>
|
||||
<?import javafx.scene.control.Button?>
|
||||
<?import javafx.scene.control.Label?>
|
||||
<?import javafx.scene.control.TextField?>
|
||||
<?import javafx.scene.layout.VBox?>
|
||||
|
||||
<fx:root type="javafx.scene.layout.VBox" xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1"
|
||||
spacing="4" style="-fx-padding: 6 0 6 0;">
|
||||
<fx:define>
|
||||
<BindingList>
|
||||
<DirectBinding control="streetField" property="text" path="street" direction="both"/>
|
||||
<DirectBinding control="houseNumberField" property="text" path="houseNumber" direction="both"/>
|
||||
<DirectBinding control="postalCodeField" property="text" path="postalCode" direction="both"/>
|
||||
<DirectBinding control="cityField" property="text" path="city" direction="both"/>
|
||||
<DirectBinding control="countryField" property="text" path="country" direction="both"/>
|
||||
<DirectBinding control="additionalInfoField" property="text" path="additionalInfo" direction="both"/>
|
||||
</BindingList>
|
||||
</fx:define>
|
||||
<Label text="Straße"/>
|
||||
<TextField fx:id="streetField" id="streetField" promptText="Straße"/>
|
||||
<Label text="Hausnummer"/>
|
||||
<TextField fx:id="houseNumberField" id="houseNumberField" promptText="Hausnummer"/>
|
||||
<Label text="Postleitzahl"/>
|
||||
<TextField fx:id="postalCodeField" id="postalCodeField" promptText="Postleitzahl"/>
|
||||
<Label text="Ort"/>
|
||||
<TextField fx:id="cityField" id="cityField" promptText="Ort"/>
|
||||
<Label text="Land"/>
|
||||
<TextField fx:id="countryField" id="countryField" promptText="Land"/>
|
||||
<Label text="Adresszusatz (optional)"/>
|
||||
<TextField fx:id="additionalInfoField" id="additionalInfoField" promptText="Adresszusatz"/>
|
||||
<Button fx:id="removeAddressButton" id="removeAddressButton" text="Adresse entfernen"
|
||||
onAction="#removeAddress"/>
|
||||
</fx:root>
|
||||
@@ -30,7 +30,11 @@
|
||||
<Button id="addContactButton" text="Kontakt hinzufügen" onAction="#addContact"/>
|
||||
<Button fx:id="deleteContactButton" id="deleteContactButton" text="Ausgewählten Kontakt löschen"
|
||||
onAction="#deleteContact"/>
|
||||
<Button id="saveContactBookButton" text="Speichern" onAction="#saveBook"/>
|
||||
<Button id="loadContactBookButton" text="Laden" onAction="#loadBook"/>
|
||||
</HBox>
|
||||
<Label fx:id="phoneValidationSummary" id="phoneValidationSummary" text="Alle Telefonnummern sind gültig."/>
|
||||
<Label fx:id="storageStatus" id="storageStatus" wrapText="true"/>
|
||||
</VBox>
|
||||
</top>
|
||||
<left>
|
||||
|
||||
+32
-10
@@ -3,23 +3,45 @@
|
||||
|
||||
<?import de.neitzel.fx.view.BindingList?>
|
||||
<?import de.neitzel.fx.view.DirectBinding?>
|
||||
<?import de.neitzel.fx.view.Repeat?>
|
||||
<?import javafx.geometry.Insets?>
|
||||
<?import javafx.scene.control.Button?>
|
||||
<?import javafx.scene.control.Label?>
|
||||
<?import javafx.scene.control.ScrollPane?>
|
||||
<?import javafx.scene.control.TextField?>
|
||||
<?import javafx.scene.layout.HBox?>
|
||||
<?import javafx.scene.layout.VBox?>
|
||||
|
||||
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1" spacing="10"
|
||||
prefWidth="480" prefHeight="220" style="-fx-background-color: white;">
|
||||
<ScrollPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1"
|
||||
fx:controller="de.neitzel.contactbook.view.ContactDetailsController"
|
||||
fitToWidth="true" hbarPolicy="NEVER" prefWidth="560" prefHeight="480"
|
||||
style="-fx-background-color: white;">
|
||||
<fx:define>
|
||||
<BindingList>
|
||||
<DirectBinding control="nameField" property="text" path="name" direction="both"/>
|
||||
<Repeat pane="phonePane" component="de.neitzel.contactbook.view.PhoneNumberEditor"
|
||||
collection="phoneNumbers"/>
|
||||
<Repeat pane="addressPane" component="de.neitzel.contactbook.view.AddressEditor"
|
||||
collection="addresses"/>
|
||||
</BindingList>
|
||||
</fx:define>
|
||||
<padding>
|
||||
<Insets top="18" right="18" bottom="18" left="18"/>
|
||||
</padding>
|
||||
<Label text="Kontaktdetails" style="-fx-font-size: 18px; -fx-font-weight: bold;"/>
|
||||
<Label text="Name"/>
|
||||
<TextField fx:id="nameField" id="nameField" promptText="Name des Kontakts"/>
|
||||
<Label text="Der Name wird direkt im ausgewählten Model gespeichert." wrapText="true"/>
|
||||
</VBox>
|
||||
<content>
|
||||
<VBox spacing="10" style="-fx-background-color: white;">
|
||||
<padding>
|
||||
<Insets top="18" right="18" bottom="18" left="18"/>
|
||||
</padding>
|
||||
<Label text="Kontaktdetails" style="-fx-font-size: 18px; -fx-font-weight: bold;"/>
|
||||
<Label text="Name"/>
|
||||
<TextField fx:id="nameField" id="nameField" promptText="Name des Kontakts"/>
|
||||
<Label text="Der Name wird direkt im ausgewählten Model gespeichert." wrapText="true"/>
|
||||
<Label text="Telefonnummern" style="-fx-font-size: 15px; -fx-font-weight: bold;"/>
|
||||
<HBox spacing="8">
|
||||
<Button id="addPhoneNumberButton" text="Telefonnummer hinzufügen" onAction="#addPhoneNumber"/>
|
||||
</HBox>
|
||||
<VBox fx:id="phonePane" id="phonePane" spacing="6"/>
|
||||
<Label text="Adressen" style="-fx-font-size: 15px; -fx-font-weight: bold;"/>
|
||||
<Button id="addAddressButton" text="Adresse hinzufügen" onAction="#addAddress"/>
|
||||
<VBox fx:id="addressPane" id="addressPane" spacing="6"/>
|
||||
</VBox>
|
||||
</content>
|
||||
</ScrollPane>
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?neitzel-model de.neitzel.contactbook.model.PhoneNumber?>
|
||||
|
||||
<?import javafx.scene.control.Button?>
|
||||
<?import javafx.scene.control.ComboBox?>
|
||||
<?import javafx.scene.control.Label?>
|
||||
<?import javafx.scene.control.TextField?>
|
||||
<?import javafx.scene.layout.HBox?>
|
||||
<?import javafx.scene.layout.VBox?>
|
||||
|
||||
<fx:root type="javafx.scene.layout.VBox" xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1"
|
||||
spacing="4" style="-fx-padding: 4 0 4 0;">
|
||||
<HBox spacing="8" alignment="CENTER_LEFT">
|
||||
<ComboBox fx:id="countryChoice" id="countryChoice" prefWidth="210" promptText="Land"/>
|
||||
<TextField fx:id="nationalNumberField" id="nationalNumberField" promptText="Nationale Telefonnummer"
|
||||
HBox.hgrow="ALWAYS"/>
|
||||
<Button fx:id="removePhoneNumberButton" id="removePhoneNumberButton" text="Entfernen"
|
||||
onAction="#removePhoneNumber"/>
|
||||
</HBox>
|
||||
<Label fx:id="validationLabel" id="validationLabel" wrapText="true"
|
||||
style="-fx-text-fill: #a61b1b;"/>
|
||||
</fx:root>
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package de.neitzel.contactbook.storage;
|
||||
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class JsonContactBookStoreTest {
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@Test
|
||||
void savesAndLoadsUtf8ContactDataWithoutUiState() throws Exception {
|
||||
Path file = directory.resolve("contacts.json");
|
||||
ContactBook source = new ContactBook();
|
||||
Contact ada = new Contact("Ada Lovelace – München");
|
||||
PhoneNumber firstNumber = new PhoneNumber("+49 301234567");
|
||||
firstNumber.rememberDraft("DE", "bad draft", "Ungültige Eingabe");
|
||||
ada.addPhoneNumber(firstNumber);
|
||||
ada.addPhoneNumber(new PhoneNumber("+43 12345678"));
|
||||
ada.addAddress(new Address("Musterstraße", "4B", "00123", "München", "Deutschland", "Hinterhaus"));
|
||||
ada.addAddress(new Address("Nebenweg", "2", "00456", "Wien", "Österreich", ""));
|
||||
Contact grace = new Contact("Grace Hopper");
|
||||
source.setContacts(List.of(ada, grace));
|
||||
source.setSelectedContact(ada);
|
||||
|
||||
JsonContactBookStore store = new JsonContactBookStore(file);
|
||||
store.save(source);
|
||||
String json = Files.readString(file, StandardCharsets.UTF_8);
|
||||
ContactBook loaded = store.load().orElseThrow();
|
||||
|
||||
assertTrue(json.contains("München"));
|
||||
assertTrue(json.contains("00123"));
|
||||
assertTrue(json.contains("\"phoneNumbers\""));
|
||||
assertTrue(json.contains("\"+49 301234567\""));
|
||||
assertTrue(json.contains("\"+43 12345678\""));
|
||||
assertFalse(json.contains("selectedContact"));
|
||||
assertFalse(json.contains("validationError"));
|
||||
assertFalse(json.contains("owner"));
|
||||
assertEquals(List.of("Ada Lovelace – München", "Grace Hopper"),
|
||||
loaded.getContacts().stream().map(Contact::getName).toList());
|
||||
assertEquals(List.of("+49 301234567", "+43 12345678"),
|
||||
loaded.getContacts().getFirst().getPhoneNumbers().stream().map(PhoneNumber::getValue).toList());
|
||||
assertEquals(List.of("00123", "00456"),
|
||||
loaded.getContacts().getFirst().getAddresses().stream().map(Address::getPostalCode).toList());
|
||||
assertTrue(loaded.getContacts().getLast().getPhoneNumbers().isEmpty());
|
||||
assertTrue(loaded.getContacts().getLast().getAddresses().isEmpty());
|
||||
assertNull(loaded.getSelectedContact());
|
||||
assertEquals(loaded.getContacts().getFirst(),
|
||||
loaded.getContacts().getFirst().getPhoneNumbers().getFirst().owner());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingFileIsAnEmptyResult() throws Exception {
|
||||
assertTrue(new JsonContactBookStore(directory.resolve("missing.json")).load().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMalformedUnknownAndNonCanonicalPhoneData() throws Exception {
|
||||
JsonContactBookStore store = new JsonContactBookStore(directory.resolve("contacts.json"));
|
||||
for (String json : List.of(
|
||||
"{not-json}",
|
||||
"{\"contacts\":[],\"selectedContact\":null}",
|
||||
"{\"contacts\":[{\"name\":\"A\",\"phoneNumbers\":[\"+99 12345678\"],\"addresses\":[]}]}",
|
||||
"{\"contacts\":[{\"name\":\"A\",\"phoneNumbers\":[\"+49 0123456\"],\"addresses\":[]}]}",
|
||||
"{\"contacts\":[],\"contacts\":[]}")) {
|
||||
Files.writeString(directory.resolve("contacts.json"), json, StandardCharsets.UTF_8);
|
||||
assertThrows(IOException.class, store::load, json);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedAtomicReplacementKeepsThePreviousFileIntact() throws Exception {
|
||||
Path file = directory.resolve("contacts.json");
|
||||
JsonContactBookStore workingStore = new JsonContactBookStore(file);
|
||||
workingStore.save(bookWithContact("Gespeicherter Stand"));
|
||||
byte[] previousContents = Files.readAllBytes(file);
|
||||
JsonContactBookStore failingStore = new JsonContactBookStore(file,
|
||||
(source, target) -> { throw new AtomicMoveNotSupportedException(source.toString(), target.toString(),
|
||||
"Test failure"); });
|
||||
|
||||
assertThrows(AtomicMoveNotSupportedException.class,
|
||||
() -> failingStore.save(bookWithContact("Neuer Stand")));
|
||||
|
||||
assertTrue(java.util.Arrays.equals(previousContents, Files.readAllBytes(file)));
|
||||
assertEquals("Gespeicherter Stand", workingStore.load().orElseThrow().getContacts().getFirst().getName());
|
||||
try (var files = Files.list(directory)) {
|
||||
assertEquals(List.of(file), files.toList());
|
||||
}
|
||||
}
|
||||
|
||||
private static ContactBook bookWithContact(String name) {
|
||||
ContactBook book = new ContactBook();
|
||||
book.setContacts(List.of(new Contact(name)));
|
||||
return book;
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Address;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.storage.ContactBookStorage;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
import javafx.scene.Parent;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.VBox;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@FxTest
|
||||
class AddressEditorTest {
|
||||
|
||||
@Test
|
||||
void realComponentDisplaysAndWritesEveryAddressFieldAsText(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
fx.await("initial address details", () -> addressEditors(fx, view).size() == 2);
|
||||
Contact contact = book.getContacts().getFirst();
|
||||
Address address = contact.getAddresses().getFirst();
|
||||
|
||||
fx.run(() -> {
|
||||
AddressEditor editor = addressEditors(view).getFirst();
|
||||
assertEquals("12 Analytical Engine Way", field(editor, "streetField").getText());
|
||||
assertEquals("4B", field(editor, "houseNumberField").getText());
|
||||
assertEquals("00123", field(editor, "postalCodeField").getText());
|
||||
assertEquals("London", field(editor, "cityField").getText());
|
||||
assertEquals("Vereinigtes Königreich", field(editor, "countryField").getText());
|
||||
assertEquals("Hinterhaus", field(editor, "additionalInfoField").getText());
|
||||
|
||||
field(editor, "streetField").setText("Neue Straße");
|
||||
field(editor, "houseNumberField").setText("7A");
|
||||
field(editor, "postalCodeField").setText("00456");
|
||||
field(editor, "cityField").setText("Neustadt");
|
||||
field(editor, "countryField").setText("Deutschland");
|
||||
field(editor, "additionalInfoField").setText("Hinterhaus links");
|
||||
|
||||
assertEquals("Neue Straße", address.getStreet());
|
||||
assertEquals("7A", address.getHouseNumber());
|
||||
assertEquals("00456", address.getPostalCode());
|
||||
assertEquals("Neustadt", address.getCity());
|
||||
assertEquals("Deutschland", address.getCountry());
|
||||
assertEquals("Hinterhaus links", address.getAdditionalInfo());
|
||||
assertEquals("Musterstraße", book.getContacts().getFirst().getAddresses().get(1).getStreet());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void addressRowsCanBeAddedRemovedIndividuallyAndDetachAfterRemoval(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
fx.await("initial address details", () -> addressEditors(fx, view).size() == 2);
|
||||
Contact contact = book.getContacts().getFirst();
|
||||
Address removed = contact.getAddresses().getFirst();
|
||||
Address kept = contact.getAddresses().get(1);
|
||||
|
||||
fx.run(() -> {
|
||||
AddressEditor removedEditor = addressEditors(view).getFirst();
|
||||
TextField removedField = field(removedEditor, "streetField");
|
||||
((Button) removedEditor.lookup("#removeAddressButton")).fire();
|
||||
assertEquals(List.of(kept), contact.getAddresses());
|
||||
assertEquals(1, addressEditors(view).size());
|
||||
removedField.setText("Detached edit");
|
||||
assertEquals("12 Analytical Engine Way", removed.getStreet());
|
||||
|
||||
addAddressButton(view).fire();
|
||||
assertEquals(2, contact.getAddresses().size());
|
||||
assertEquals(2, addressEditors(view).size());
|
||||
Address added = contact.getAddresses().getLast();
|
||||
AddressEditor addedEditor = addressEditors(view).getLast();
|
||||
assertEquals("", field(addedEditor, "postalCodeField").getText());
|
||||
field(addedEditor, "postalCodeField").setText("00007");
|
||||
assertEquals("00007", added.getPostalCode());
|
||||
|
||||
((Button) addedEditor.lookup("#removeAddressButton")).fire();
|
||||
assertEquals(List.of(kept), contact.getAddresses());
|
||||
((Button) addressEditors(view).getFirst().lookup("#removeAddressButton")).fire();
|
||||
assertTrue(contact.getAddresses().isEmpty());
|
||||
assertTrue(addressEditors(view).isEmpty());
|
||||
assertFalse(addressEditors(view).contains(removedEditor));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void selectingAnotherContactLoadsItsAddressesAndDetachesThePreviousView(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
fx.await("initial address details", () -> addressEditors(fx, view).size() == 2);
|
||||
Contact ada = book.getContacts().getFirst();
|
||||
Contact grace = book.getContacts().get(1);
|
||||
TextField oldField = fx.call(() -> field(addressEditors(view).getFirst(), "streetField"));
|
||||
|
||||
fx.run(() -> {
|
||||
((ListView<?>) view.getRoot().lookup("#contactList")).getSelectionModel().select(1);
|
||||
assertSame(grace, book.getSelectedContact());
|
||||
assertEquals(1, addressEditors(view).size());
|
||||
assertEquals("1600 Amphitheatre Parkway", field(addressEditors(view).getFirst(), "streetField").getText());
|
||||
oldField.setText("Detached contact edit");
|
||||
assertEquals("12 Analytical Engine Way", ada.getAddresses().getFirst().getStreet());
|
||||
assertEquals("1600 Amphitheatre Parkway", grace.getAddresses().getFirst().getStreet());
|
||||
});
|
||||
}
|
||||
|
||||
private static LoadedView load(FxFixture fx, ContactBook book) throws Exception {
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
context.getComponent(ContactBookStorage.class).useSnapshot();
|
||||
LoadedView view = fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
book, context);
|
||||
fx.run(() -> {
|
||||
new Scene((Parent) view.getRoot());
|
||||
view.getRoot().applyCss();
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
private static List<AddressEditor> addressEditors(FxFixture fx, LoadedView view) {
|
||||
try {
|
||||
return fx.call(() -> addressEditors(view));
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<AddressEditor> addressEditors(LoadedView view) {
|
||||
VBox pane = (VBox) view.getRoot().lookup("#addressPane");
|
||||
return pane.getChildren().stream().map(AddressEditor.class::cast).toList();
|
||||
}
|
||||
|
||||
private static TextField field(AddressEditor editor, String id) {
|
||||
return (TextField) editor.lookup("#" + id);
|
||||
}
|
||||
|
||||
private static Button addAddressButton(LoadedView view) {
|
||||
return (Button) view.getRoot().lookup("#addAddressButton");
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -3,6 +3,7 @@ package de.neitzel.contactbook.view;
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.storage.ContactBookStorage;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
@@ -10,6 +11,8 @@ import de.neitzel.injection.ApplicationContext;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.Parent;
|
||||
import javafx.scene.Scene;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -81,8 +84,15 @@ class ContactBookLoadsTest {
|
||||
}
|
||||
|
||||
private static LoadedView load(FxFixture fx, ContactBook book) throws Exception {
|
||||
return fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
book, new ApplicationContext(ContactBookApp.class));
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
context.getComponent(ContactBookStorage.class).useSnapshot();
|
||||
LoadedView view = fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
book, context);
|
||||
fx.run(() -> {
|
||||
new Scene((Parent) view.getRoot());
|
||||
view.getRoot().applyCss();
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
private static boolean hasNameField(FxFixture fx, LoadedView view) {
|
||||
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.storage.ContactBookStorage;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
import javafx.scene.Parent;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.VBox;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@FxTest
|
||||
class ContactBookPersistenceTest {
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@Test
|
||||
void missingFileStartsEmptyAndSaveThenLoadRestoresTheWholeBook(FxFixture fx) throws Exception {
|
||||
Path file = directory.resolve("contacts.json");
|
||||
ContactBook initial = new ContactBook();
|
||||
LoadedView emptyView = load(fx, initial, file);
|
||||
fx.run(() -> {
|
||||
assertTrue(((ListView<?>) emptyView.getRoot().lookup("#contactList")).getItems().isEmpty());
|
||||
assertTrue(emptyView.getRoot().lookup("#emptyState").isVisible());
|
||||
assertTrue(label(emptyView, "storageStatus").getText().contains("Noch keine gespeicherte Datei"));
|
||||
});
|
||||
|
||||
ContactBook source = ContactBookApp.sample();
|
||||
Contact grace = source.getContacts().getLast();
|
||||
grace.setPhoneNumbers(List.of());
|
||||
grace.setAddresses(List.of());
|
||||
LoadedView sourceView = load(fx, source, file);
|
||||
fx.await("contact details for saving", () -> hasNameField(fx, sourceView));
|
||||
fx.run(() -> {
|
||||
nameField(sourceView).setText("Ada Byron");
|
||||
((Button) sourceView.getRoot().lookup("#saveContactBookButton")).fire();
|
||||
assertTrue(label(sourceView, "storageStatus").getText().contains("Kontaktbuch gespeichert"));
|
||||
});
|
||||
assertTrue(Files.readString(file, StandardCharsets.UTF_8).contains("Ada Byron"));
|
||||
|
||||
ContactBook restored = new ContactBook();
|
||||
LoadedView restoredView = load(fx, restored, file);
|
||||
fx.await("restored contact details", () -> hasNameField(fx, restoredView));
|
||||
fx.run(() -> {
|
||||
assertEquals(2, restored.getContacts().size());
|
||||
assertEquals("Ada Byron", restored.getContacts().getFirst().getName());
|
||||
assertEquals(2, restored.getContacts().getFirst().getPhoneNumbers().size());
|
||||
assertEquals(2, restored.getContacts().getFirst().getAddresses().size());
|
||||
assertEquals("00123", restored.getContacts().getFirst().getAddresses().getFirst().getPostalCode());
|
||||
assertTrue(restored.getContacts().get(1).getPhoneNumbers().isEmpty());
|
||||
assertTrue(restored.getContacts().get(1).getAddresses().isEmpty());
|
||||
|
||||
nameField(restoredView).setText("Ungespeicherte Änderung");
|
||||
((Button) restoredView.getRoot().lookup("#loadContactBookButton")).fire();
|
||||
assertEquals("Ada Byron", restored.getContacts().getFirst().getName());
|
||||
assertSame(restored.getContacts().getFirst(), restored.getSelectedContact());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidLoadKeepsTheOpenedContactBookUnchanged(FxFixture fx) throws Exception {
|
||||
Path file = directory.resolve("contacts.json");
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book, file);
|
||||
fx.await("contact details", () -> hasNameField(fx, view));
|
||||
fx.run(() -> ((Button) view.getRoot().lookup("#saveContactBookButton")).fire());
|
||||
Contact firstContact = book.getContacts().getFirst();
|
||||
String oldName = firstContact.getName();
|
||||
Files.writeString(file, "{invalid", StandardCharsets.UTF_8);
|
||||
|
||||
fx.run(() -> ((Button) view.getRoot().lookup("#loadContactBookButton")).fire());
|
||||
|
||||
assertSame(firstContact, book.getContacts().getFirst());
|
||||
assertEquals(oldName, firstContact.getName());
|
||||
assertTrue(fx.call(() -> label(view, "storageStatus").getText())
|
||||
.contains("Kontaktbuch konnte nicht geladen werden"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeFailureIsShownWithoutReplacingAnExistingTarget(FxFixture fx) throws Exception {
|
||||
Path file = directory.resolve("contacts.json");
|
||||
Files.createDirectory(file);
|
||||
Path marker = file.resolve("keep.txt");
|
||||
Files.writeString(marker, "untouched", StandardCharsets.UTF_8);
|
||||
LoadedView view = load(fx, ContactBookApp.sample(), file);
|
||||
fx.await("contact details", () -> hasNameField(fx, view));
|
||||
|
||||
fx.run(() -> ((Button) view.getRoot().lookup("#saveContactBookButton")).fire());
|
||||
|
||||
assertTrue(fx.call(() -> label(view, "storageStatus").getText())
|
||||
.contains("Kontaktbuch konnte nicht gespeichert werden"));
|
||||
assertTrue(Files.isDirectory(file));
|
||||
assertEquals("untouched", Files.readString(marker, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidDraftOnAnotherContactBlocksSavingUntilCorrected(FxFixture fx) throws Exception {
|
||||
Path file = directory.resolve("contacts.json");
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book, file);
|
||||
fx.await("initial contact details", () -> phoneEditorCount(fx, view) == 2);
|
||||
|
||||
fx.run(() -> ((ListView<?>) view.getRoot().lookup("#contactList")).getSelectionModel().select(1));
|
||||
fx.await("second contact phone editor", () -> phoneEditorCount(fx, view) == 1);
|
||||
fx.run(() -> ((Button) view.getRoot().lookup("#addPhoneNumberButton")).fire());
|
||||
fx.await("new phone editor", () -> phoneEditorCount(fx, view) == 2);
|
||||
fx.run(() -> ((TextField) phoneEditors(view).getLast().lookup("#nationalNumberField")).setText("12"));
|
||||
|
||||
fx.run(() -> {
|
||||
((ListView<?>) view.getRoot().lookup("#contactList")).getSelectionModel().select(0);
|
||||
((Button) view.getRoot().lookup("#saveContactBookButton")).fire();
|
||||
assertTrue(label(view, "storageStatus").getText().contains("Telefonnummer von Grace Hopper ist ungültig"));
|
||||
});
|
||||
assertFalse(Files.exists(file));
|
||||
|
||||
fx.run(() -> ((ListView<?>) view.getRoot().lookup("#contactList")).getSelectionModel().select(1));
|
||||
fx.await("return to invalid draft", () -> phoneEditorCount(fx, view) == 2);
|
||||
fx.run(() -> ((TextField) phoneEditors(view).getLast().lookup("#nationalNumberField")).setText("12345678"));
|
||||
fx.run(() -> {
|
||||
((ListView<?>) view.getRoot().lookup("#contactList")).getSelectionModel().select(0);
|
||||
((Button) view.getRoot().lookup("#saveContactBookButton")).fire();
|
||||
});
|
||||
|
||||
assertTrue(Files.exists(file));
|
||||
assertTrue(fx.call(() -> label(view, "storageStatus").getText()).contains("Kontaktbuch gespeichert"));
|
||||
}
|
||||
|
||||
private LoadedView load(FxFixture fx, ContactBook book, Path file) throws Exception {
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
context.getComponent(ContactBookStorage.class).useFile(file);
|
||||
LoadedView view = fx.load(ContactBookController.class.getResource("ContactBook.fxml"), book, context);
|
||||
fx.run(() -> {
|
||||
new Scene((Parent) view.getRoot());
|
||||
view.getRoot().applyCss();
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
private static boolean hasNameField(FxFixture fx, LoadedView view) {
|
||||
try {
|
||||
return fx.call(() -> view.getRoot().lookup("#nameField") instanceof TextField);
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static int phoneEditorCount(FxFixture fx, LoadedView view) {
|
||||
try {
|
||||
return fx.call(() -> phoneEditors(view).size());
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<PhoneNumberEditor> phoneEditors(LoadedView view) {
|
||||
VBox pane = (VBox) view.getRoot().lookup("#phonePane");
|
||||
return pane.getChildren().stream().map(PhoneNumberEditor.class::cast).toList();
|
||||
}
|
||||
|
||||
private static TextField nameField(LoadedView view) {
|
||||
return (TextField) view.getRoot().lookup("#nameField");
|
||||
}
|
||||
|
||||
private static javafx.scene.control.Label label(LoadedView view, String id) {
|
||||
return (javafx.scene.control.Label) view.getRoot().lookup("#" + id);
|
||||
}
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.model.PhoneCountry;
|
||||
import de.neitzel.contactbook.model.PhoneNumber;
|
||||
import de.neitzel.contactbook.storage.ContactBookStorage;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.fx.view.ViewLoader;
|
||||
import de.neitzel.fx.view.ViewModelContext;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
import javafx.beans.property.Property;
|
||||
import javafx.scene.Parent;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ComboBox;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.VBox;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@FxTest
|
||||
class PhoneNumberEditorTest {
|
||||
|
||||
@Test
|
||||
void realDetailsFxmlRepeatsIndependentEditorsAndNormalizesNationalInput(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
fx.await("contact phone editors", () -> hasPhonePane(fx, view));
|
||||
Contact ada = book.getContacts().getFirst();
|
||||
Contact grace = book.getContacts().get(1);
|
||||
|
||||
fx.run(() -> {
|
||||
VBox pane = phonePane(view);
|
||||
assertEquals(2, pane.getChildren().size());
|
||||
PhoneNumberEditor first = (PhoneNumberEditor) pane.getChildren().getFirst();
|
||||
PhoneNumberEditor second = (PhoneNumberEditor) pane.getChildren().get(1);
|
||||
assertNotSame(first, second);
|
||||
assertSame(ada.getPhoneNumbers().getFirst(), first.getModel());
|
||||
assertSame(ada.getPhoneNumbers().get(1), second.getModel());
|
||||
assertEquals("AT", selectedCountry(second).isoCode());
|
||||
assertEquals("+49 301234567", ada.getPhoneNumbers().getFirst().getValue());
|
||||
assertEquals("301234567", numberField(first).getText());
|
||||
assertEquals("DE", selectedCountry(first).isoCode());
|
||||
assertEquals("🇩🇪 Deutschland (+49)", countryChoice(first).getConverter().toString(selectedCountry(first)));
|
||||
assertEquals(List.of("🇩🇪 Deutschland (+49)", "🇦🇹 Österreich (+43)", "🇨🇭 Schweiz (+41)"),
|
||||
PhoneCountry.countries().stream().map(PhoneCountry::label).toList());
|
||||
|
||||
numberField(first).setText("030 / 7654321");
|
||||
assertEquals("+49 307654321", ada.getPhoneNumbers().getFirst().getValue());
|
||||
assertEquals("+43 12345678", ada.getPhoneNumbers().get(1).getValue());
|
||||
|
||||
countryChoice(second).setValue(PhoneCountry.countries().getLast());
|
||||
assertEquals("+41 12345678", ada.getPhoneNumbers().get(1).getValue());
|
||||
assertEquals("CH", selectedCountry(second).isoCode());
|
||||
numberField(second).setText("044 / 6681819");
|
||||
assertEquals("+41 446681819", ada.getPhoneNumbers().get(1).getValue(),
|
||||
errorLabel(second).getText() + " / " + numberField(second).getText());
|
||||
assertEquals("+41 446681818", grace.getPhoneNumbers().getFirst().getValue());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidDraftSurvivesContactSwitchAndCanBeCorrected(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
fx.await("contact phone editors", () -> hasPhonePane(fx, view));
|
||||
Contact ada = book.getContacts().getFirst();
|
||||
PhoneNumber edited = ada.getPhoneNumbers().getFirst();
|
||||
|
||||
fx.run(() -> {
|
||||
PhoneNumberEditor editor = (PhoneNumberEditor) phonePane(view).getChildren().getFirst();
|
||||
numberField(editor).setText("12x");
|
||||
assertEquals("+49 301234567", edited.getValue());
|
||||
assertFalse(errorLabel(editor).getText().isBlank());
|
||||
assertTrue(summary(view).getText().contains("1"), summary(view).getText());
|
||||
|
||||
numberField(editor).setText("12");
|
||||
assertTrue(errorLabel(editor).getText().contains("zu kurz"));
|
||||
numberField(editor).setText("+41 446681818");
|
||||
assertEquals("DE", selectedCountry(editor).isoCode());
|
||||
assertTrue(errorLabel(editor).getText().contains("nur Ziffern"));
|
||||
numberField(editor).setText("");
|
||||
assertTrue(errorLabel(editor).getText().contains("Bitte gib"));
|
||||
numberField(editor).setText("12x");
|
||||
|
||||
contacts(view).getSelectionModel().select(1);
|
||||
assertTrue(summary(view).getText().contains("1"));
|
||||
contacts(view).getSelectionModel().select(0);
|
||||
PhoneNumberEditor restored = (PhoneNumberEditor) phonePane(view).getChildren().getFirst();
|
||||
assertEquals("12x", numberField(restored).getText());
|
||||
assertFalse(errorLabel(restored).getText().isBlank());
|
||||
|
||||
numberField(restored).setText("030 / 9876543");
|
||||
assertEquals("+49 309876543", edited.getValue());
|
||||
assertTrue(errorLabel(restored).getText().isBlank());
|
||||
assertTrue(summary(view).getText().contains("Alle Telefonnummern sind gültig"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void anObservedCanonicalValueUpdatesBothControlsWithoutPublishingAnIntermediateValue(FxFixture fx)
|
||||
throws Exception {
|
||||
PhoneNumber phone = new PhoneNumber("+49 301234567");
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
LoadedView loaded = fx.call(() -> ViewLoader.loadComponent(PhoneNumberEditor.class, phone, context, models));
|
||||
List<Object> observed = new ArrayList<>();
|
||||
|
||||
fx.run(() -> {
|
||||
PhoneNumberEditor editor = (PhoneNumberEditor) loaded.getRoot();
|
||||
@SuppressWarnings("unchecked")
|
||||
Property<Object> value = (Property<Object>) loaded.property("value");
|
||||
value.addListener((observable, oldValue, newValue) -> observed.add(newValue));
|
||||
value.setValue("+41 446681818");
|
||||
|
||||
assertEquals("CH", selectedCountry(editor).isoCode());
|
||||
assertEquals("446681818", numberField(editor).getText());
|
||||
assertEquals(List.of("+41 446681818"), observed);
|
||||
assertTrue(errorLabel(editor).getText().isBlank());
|
||||
assertFalse(removeButton(editor).isVisible());
|
||||
assertFalse(removeButton(editor).isManaged());
|
||||
});
|
||||
|
||||
fx.run(() -> {
|
||||
loaded.close();
|
||||
models.close();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void addingAndRemovingARepeatedPhoneKeepsOtherRowsIndependent(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
fx.await("contact phone editors", () -> hasPhonePane(fx, view));
|
||||
Contact ada = book.getContacts().getFirst();
|
||||
|
||||
fx.run(() -> {
|
||||
addPhoneButton(view).fire();
|
||||
assertEquals(3, ada.getPhoneNumbers().size());
|
||||
assertEquals(3, phonePane(view).getChildren().size());
|
||||
PhoneNumberEditor added = (PhoneNumberEditor) phonePane(view).getChildren().getLast();
|
||||
assertFalse(errorLabel(added).getText().isBlank());
|
||||
assertTrue(summary(view).getText().contains("1"));
|
||||
numberField(added).setText("5551234");
|
||||
assertEquals("+49 5551234", ada.getPhoneNumbers().getLast().getValue());
|
||||
assertTrue(summary(view).getText().contains("Alle Telefonnummern sind gültig"));
|
||||
|
||||
addPhoneButton(view).fire();
|
||||
PhoneNumberEditor invalid = (PhoneNumberEditor) phonePane(view).getChildren().getLast();
|
||||
assertTrue(summary(view).getText().contains("1"));
|
||||
removeButton(invalid).fire();
|
||||
assertEquals(3, ada.getPhoneNumbers().size());
|
||||
assertTrue(summary(view).getText().contains("Alle Telefonnummern sind gültig"));
|
||||
|
||||
PhoneNumberEditor first = (PhoneNumberEditor) phonePane(view).getChildren().getFirst();
|
||||
removeButton(first).fire();
|
||||
assertEquals(2, ada.getPhoneNumbers().size());
|
||||
assertEquals("+43 12345678", ada.getPhoneNumbers().getFirst().getValue());
|
||||
assertEquals("+49 5551234", ada.getPhoneNumbers().getLast().getValue());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void standaloneEditorShowsTheSupportedFlaggedCountryChoices(FxFixture fx) throws Exception {
|
||||
PhoneNumber phone = new PhoneNumber("+49 301234567");
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
LoadedView loaded = fx.call(() -> ViewLoader.loadComponent(PhoneNumberEditor.class, phone, context, models));
|
||||
|
||||
fx.run(() -> {
|
||||
PhoneNumberEditor editor = (PhoneNumberEditor) loaded.getRoot();
|
||||
ComboBox<?> countries = (ComboBox<?>) editor.lookup("#countryChoice");
|
||||
assertEquals(3, countries.getItems().size());
|
||||
assertEquals("🇩🇪 Deutschland (+49)", PhoneCountry.countries().getFirst().label());
|
||||
assertEquals("🇦🇹 Österreich (+43)", PhoneCountry.countries().get(1).label());
|
||||
assertEquals("🇨🇭 Schweiz (+41)", PhoneCountry.countries().getLast().label());
|
||||
assertFalse(removeButton(editor).isVisible());
|
||||
assertNotNull(editor.lookup("#nationalNumberField"));
|
||||
});
|
||||
|
||||
fx.run(() -> {
|
||||
loaded.close();
|
||||
models.close();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void canonicalValueIsNotReformattedByRemovingItsNationalPrefixAgain(FxFixture fx) throws Exception {
|
||||
PhoneNumber phone = new PhoneNumber("+49 03012345");
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
LoadedView loaded = fx.call(() -> ViewLoader.loadComponent(PhoneNumberEditor.class, phone, context, models));
|
||||
|
||||
fx.run(() -> {
|
||||
PhoneNumberEditor editor = (PhoneNumberEditor) loaded.getRoot();
|
||||
assertEquals("03012345", numberField(editor).getText());
|
||||
assertTrue(errorLabel(editor).getText().contains("Amtsnull"));
|
||||
assertEquals("+49 03012345", phone.getValue());
|
||||
loaded.close();
|
||||
models.close();
|
||||
});
|
||||
}
|
||||
|
||||
private static LoadedView load(FxFixture fx, ContactBook book) throws Exception {
|
||||
ApplicationContext context = new ApplicationContext(ContactBookApp.class);
|
||||
context.getComponent(ContactBookStorage.class).useSnapshot();
|
||||
LoadedView view = fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
book, context);
|
||||
fx.run(() -> {
|
||||
new Scene((Parent) view.getRoot());
|
||||
view.getRoot().applyCss();
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
private static boolean hasPhonePane(FxFixture fx, LoadedView view) {
|
||||
try {
|
||||
return fx.call(() -> view.getRoot().lookup("#phonePane") instanceof VBox);
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static VBox phonePane(LoadedView view) {
|
||||
return (VBox) view.getRoot().lookup("#phonePane");
|
||||
}
|
||||
|
||||
private static ListView<?> contacts(LoadedView view) {
|
||||
return (ListView<?>) view.getRoot().lookup("#contactList");
|
||||
}
|
||||
|
||||
private static TextField numberField(PhoneNumberEditor editor) {
|
||||
return (TextField) editor.lookup("#nationalNumberField");
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static ComboBox<PhoneCountry> countryChoice(PhoneNumberEditor editor) {
|
||||
return (ComboBox<PhoneCountry>) editor.lookup("#countryChoice");
|
||||
}
|
||||
|
||||
private static PhoneCountry selectedCountry(PhoneNumberEditor editor) {
|
||||
return (PhoneCountry) countryChoice(editor).getValue();
|
||||
}
|
||||
|
||||
private static Label errorLabel(PhoneNumberEditor editor) {
|
||||
return (Label) editor.lookup("#validationLabel");
|
||||
}
|
||||
|
||||
private static Label summary(LoadedView view) {
|
||||
return (Label) view.getRoot().lookup("#phoneValidationSummary");
|
||||
}
|
||||
|
||||
private static Button addPhoneButton(LoadedView view) {
|
||||
return (Button) view.getRoot().lookup("#addPhoneNumberButton");
|
||||
}
|
||||
|
||||
private static Button removeButton(PhoneNumberEditor editor) {
|
||||
return (Button) editor.lookup("#removePhoneNumberButton");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user