io.github.openhtmltopdf
diff --git a/src/main/java/com/knowledgepixels/nanodash/component/PublishForm.java b/src/main/java/com/knowledgepixels/nanodash/component/PublishForm.java
index 5267da37..c37d25b5 100644
--- a/src/main/java/com/knowledgepixels/nanodash/component/PublishForm.java
+++ b/src/main/java/com/knowledgepixels/nanodash/component/PublishForm.java
@@ -9,6 +9,7 @@
import com.knowledgepixels.nanodash.page.NanodashPage;
import com.knowledgepixels.nanodash.page.PreviewPage;
import com.knowledgepixels.nanodash.template.*;
+import org.nanopub.templates.FillRequest;
import org.nanopub.templates.Template;
import com.knowledgepixels.nanodash.vocabulary.KPXL_TERMS;
import org.apache.commons.lang3.Strings;
@@ -755,6 +756,8 @@ protected void onSubmit() {
if (!areNewUrisUnused() || !noReservedIdentifiers()) {
return;
}
+ // Only logs what it finds; see TemplateFillGuard.
+ TemplateFillGuard.check(np, PublishForm.this::toFillRequest);
TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
signedNp = SignNanopub.signAndTransform(np, tc);
logger.info("Nanopublication signed: {}", signedNp.getUri());
@@ -1687,6 +1690,8 @@ private Nanopub signForPreview(PageParameters pageParams) {
if (!areNewUrisUnused() || !noReservedIdentifiers()) {
return null;
}
+ // Only logs what it finds; see TemplateFillGuard.
+ TemplateFillGuard.check(np, this::toFillRequest);
TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
Nanopub signedNp = SignNanopub.signAndTransform(np, tc);
// Only logs what it finds; see TemplateComplianceGuard. Here and not on the
@@ -1764,6 +1769,18 @@ private static void collectTemplateErrors(String part, TemplateContext context,
}
}
+ /**
+ * Returns what is filled in on this form as a request for the filler of nanopub-java, which
+ * {@link TemplateFillGuard} makes the nanopublication a second time from (#936).
+ *
+ * @return the request
+ */
+ FillRequest toFillRequest() {
+ IRI userIri = NanodashSession.get().getUserIri();
+ return FormRequest.of(assertionContext, provenanceContext, pubInfoContexts, targetNamespace, userIri,
+ User.getName(userIri), NanodashPreferences.get().getWebsiteUrl());
+ }
+
private synchronized Nanopub createNanopub() throws MalformedNanopubException, NanopubAlreadyFinalizedException {
assertionContext.getIntroducedIris().clear();
assertionContext.getNewUriIris().clear();
diff --git a/src/main/java/com/knowledgepixels/nanodash/template/FormRequest.java b/src/main/java/com/knowledgepixels/nanodash/template/FormRequest.java
new file mode 100644
index 00000000..aa44db29
--- /dev/null
+++ b/src/main/java/com/knowledgepixels/nanodash/template/FormRequest.java
@@ -0,0 +1,180 @@
+package com.knowledgepixels.nanodash.template;
+
+import com.knowledgepixels.nanodash.DynamicPrefix;
+import com.knowledgepixels.nanodash.LocalUri;
+import com.knowledgepixels.nanodash.Utils;
+import com.knowledgepixels.nanodash.component.GuidedChoiceItem;
+import com.knowledgepixels.nanodash.component.LiteralDateItem;
+import com.knowledgepixels.nanodash.component.LiteralDateTimeItem;
+import com.knowledgepixels.nanodash.component.PublishForm.FillMode;
+import com.knowledgepixels.nanodash.domain.User;
+import org.apache.wicket.model.IModel;
+import org.eclipse.rdf4j.model.IRI;
+import org.eclipse.rdf4j.model.Value;
+import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
+import org.nanopub.Nanopub;
+import org.nanopub.templates.FillRequest;
+import org.nanopub.templates.RawValue;
+import org.nanopub.templates.Template;
+import org.nanopub.templates.TemplateValues;
+import org.nanopub.vocabulary.NTEMPLATE;
+
+import java.time.ZonedDateTime;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Turns what is filled in on a publishing form into a request for the filler of nanopub-java
+ * ({@link org.nanopub.templates.TemplateFiller}).
+ *
+ * The form keeps the value of each placeholder in a model, under the placeholder's IRI with a
+ * {@code __N} suffix for a repetition. The last part of that key is the name the value has in a
+ * request, the same name as in the {@code param_} parameter that fills the form from a link. A
+ * model holds the text as it is entered, which is what a request takes: a local name, a name
+ * after the prefix of the placeholder, or a full IRI. An empty model says that the placeholder
+ * has no value, the default of the template included, as a field that was cleared does.
+ *
+ * What follows from the nanopublication rather than from a field is left to the filler: the
+ * creator, the positions in a sequence, and the root definition where the form has none of its
+ * own. The labels the form looked up, and the names of agents, go into the request as labels.
+ */
+public final class FormRequest {
+
+ private static final String ARTIFACT_CODE_MARKER = "~~~ARTIFACTCODE~~~/";
+ private static final String ROOT_IS_SOURCE = LocalUri.of("nanopub").stringValue();
+
+ private FormRequest() {
+ }
+
+ /**
+ * Builds the request for what a publishing form has filled in.
+ *
+ * @param assertion the context of the assertion template
+ * @param provenance the context of the provenance template
+ * @param pubinfo the contexts of the publication info templates
+ * @param targetNamespace the namespace the form makes the nanopublication in, with or
+ * without the artifact-code marker after it
+ * @param creator the IRI of the person filling in the form
+ * @param creatorName their name, or null
+ * @param creationSite the address of this Nanodash instance, or null
+ * @return the request
+ */
+ public static FillRequest of(TemplateContext assertion, TemplateContext provenance, List pubinfo,
+ String targetNamespace, IRI creator, String creatorName, String creationSite) {
+ FillRequest request = new FillRequest(assertion.getTemplate().getId());
+ copyValues(assertion, request.getValues(), request);
+ request.setProvenanceTemplate(provenance.getTemplate().getId());
+ copyValues(provenance, request.getProvenanceValues(), request);
+ for (TemplateContext context : pubinfo) {
+ copyValues(context, request.addPubinfoTemplate(context.getTemplate().getId()), request);
+ }
+ if (targetNamespace != null) {
+ String namespace = targetNamespace.endsWith(ARTIFACT_CODE_MARKER)
+ ? targetNamespace.substring(0, targetNamespace.length() - ARTIFACT_CODE_MARKER.length()) : targetNamespace;
+ request.setTargetNamespace(namespace);
+ }
+ FillRequest.Mode mode = getMode(assertion.getFillMode());
+ Nanopub source = assertion.getFillSource();
+ if (mode != null && source != null) request.setSource(mode, source.getUri().stringValue());
+ request.setSpace(assertion.getPrefixBase(DynamicPrefix.SPACE_TOKEN));
+ request.setNamespace(assertion.getPrefixBase(DynamicPrefix.NAMESPACE_TOKEN));
+ request.setCreator(creator);
+ request.setCreatorName(creatorName);
+ request.setCreationSite(creationSite);
+ return request;
+ }
+
+ /**
+ * Returns the mode of a request for a fill mode of the form. Using a nanopublication, in
+ * full or in part, only takes values from it, which the request has already.
+ *
+ * @param fillMode the fill mode of the form, or null
+ * @return the mode, or null if the nanopublication made does not relate to the source
+ */
+ static FillRequest.Mode getMode(FillMode fillMode) {
+ if (fillMode == null) return null;
+ return switch (fillMode) {
+ case SUPERSEDE -> FillRequest.Mode.SUPERSEDE;
+ case OVERRIDE -> FillRequest.Mode.OVERRIDE;
+ case DERIVE -> FillRequest.Mode.DERIVE;
+ case USE, PARTIAL -> null;
+ };
+ }
+
+ private static void copyValues(TemplateContext context, TemplateValues values, FillRequest request) {
+ Template template = context.getTemplate();
+ for (Map.Entry> e : context.getComponentModels().entrySet()) {
+ IRI key = e.getKey();
+ String keyString = key.stringValue();
+ // The creator and the other values the nanopublication itself gives, and the
+ // models that only go with a value: its language, its prefix, its source spelling.
+ if (keyString.startsWith(NTEMPLATE.NAMESPACE) || keyString.startsWith(LocalUri.PREFIX)) continue;
+ if (keyString.endsWith(TemplateContext.LANGUAGE_SUFFIX) || keyString.endsWith(TemplateContext.AUTO_ESCAPE_SOURCE_SUFFIX)) continue;
+ IRI templateIri = template.getTemplateIri(key);
+ if (!template.isPlaceholder(templateIri) || template.isSequenceElementPlaceholder(templateIri)) continue;
+ String text = toText(e.getValue() == null ? null : e.getValue().getObject());
+ if (template.isRootNanopubPlaceholder(templateIri) && (text.isEmpty() || text.equals(ROOT_IS_SOURCE))) continue;
+ // The form puts the default of the template into a field. Left as it is, it is not
+ // a value the person gave: the filler takes the default by itself, and leaves it out
+ // with its statement where that statement lacks other values, as the form does.
+ if (isDefault(context, key, text)) continue;
+ String languageTag = null;
+ IModel> languageModel = context.getComponentModels().get(TemplateContext.getLanguageModelKey(key));
+ if (languageModel != null && template.isLanguageTagSelectable(templateIri)) {
+ languageTag = toText(languageModel.getObject());
+ }
+ values.set(TemplateValues.getName(key), new RawValue(text, languageTag));
+ if (!text.isEmpty() && template.isUriPlaceholder(templateIri)) addLabels(context, key, templateIri, text, request);
+ }
+ }
+
+ // Whether a field holds the default value of its placeholder, in one of the ways the form
+ // writes it: a literal by its text, an IRI within the template by its local name, and any
+ // other IRI in full or after the prefix of the placeholder.
+ static boolean isDefault(TemplateContext context, IRI key, String text) {
+ if (text.isEmpty()) return false;
+ Template template = context.getTemplate();
+ Value value = template.getDefault(key);
+ if (value == null) return false;
+ if (!(value instanceof IRI)) return text.equals(value.stringValue());
+ String iri = value.stringValue();
+ if (text.equals(iri)) return true;
+ String templateUri = template.getNanopub().getUri().stringValue();
+ if (iri.startsWith(templateUri) && !iri.equals(templateUri) && text.equals(Utils.getUriPostfix(iri))) return true;
+ String prefix = context.getPrefix(key);
+ return prefix != null && !prefix.isEmpty() && iri.startsWith(prefix) && text.equals(iri.substring(prefix.length()));
+ }
+
+ // The labels the form knows for the IRI a field holds: those looked up for a value chosen
+ // from a list, which the form keeps whatever kind of field the value is in, and the names
+ // of people.
+ private static void addLabels(TemplateContext context, IRI key, IRI templateIri, String text, FillRequest request) {
+ String iri = text;
+ if (!Utils.isUriValue(iri)) {
+ String prefix = context.getPrefix(key);
+ if (prefix == null || prefix.isEmpty()) return;
+ iri = prefix + text;
+ }
+ String label = GuidedChoiceItem.getLabel(iri);
+ if (label == null) label = GuidedChoiceItem.getLabel(text);
+ if (label != null) request.setLabelFromApi(iri, label);
+ if (context.getTemplate().isAgentPlaceholder(templateIri) && Utils.isUriValue(iri)) {
+ String name = User.getName(SimpleValueFactory.getInstance().createIRI(iri));
+ if (name != null) request.setLabel(iri, name);
+ }
+ }
+
+ // The text a model holds, as the form writes it into a nanopublication.
+ private static String toText(Object object) {
+ if (object == null) return "";
+ if (object instanceof ZonedDateTime dateTime) return LiteralDateTimeItem.format.format(dateTime);
+ if (object instanceof Date date) {
+ synchronized (LiteralDateItem.format) {
+ return LiteralDateItem.format.format(date);
+ }
+ }
+ return object.toString();
+ }
+
+}
diff --git a/src/main/java/com/knowledgepixels/nanodash/template/TemplateContext.java b/src/main/java/com/knowledgepixels/nanodash/template/TemplateContext.java
index 0bbd8c33..c0db28d3 100644
--- a/src/main/java/com/knowledgepixels/nanodash/template/TemplateContext.java
+++ b/src/main/java/com/knowledgepixels/nanodash/template/TemplateContext.java
@@ -585,6 +585,17 @@ public boolean isToBeMinted(IRI iri, String value) {
return prefix == null || prefix.isEmpty();
}
+ /**
+ * Returns the base that a space-/namespace-dependent prefix token stands for here: the one
+ * the navigation context determines, or else the one the user picked.
+ *
+ * @param token the token, {@link DynamicPrefix#SPACE_TOKEN} or {@link DynamicPrefix#NAMESPACE_TOKEN}
+ * @return the base, or null if it is not determined
+ */
+ public String getPrefixBase(String token) {
+ return resolvePrefixBase(token);
+ }
+
private String resolvePrefixBase(String token) {
String base = DynamicPrefix.resolveFromContext(token, navigationContextId);
if (base != null && !base.isEmpty()) return base;
diff --git a/src/main/java/com/knowledgepixels/nanodash/template/TemplateFillGuard.java b/src/main/java/com/knowledgepixels/nanodash/template/TemplateFillGuard.java
new file mode 100644
index 00000000..0df53867
--- /dev/null
+++ b/src/main/java/com/knowledgepixels/nanodash/template/TemplateFillGuard.java
@@ -0,0 +1,159 @@
+package com.knowledgepixels.nanodash.template;
+
+import org.eclipse.rdf4j.model.IRI;
+import org.eclipse.rdf4j.model.Statement;
+import org.eclipse.rdf4j.model.Value;
+import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
+import org.nanopub.Nanopub;
+import org.nanopub.templates.FillRequest;
+import org.nanopub.templates.NanopubResolver;
+import org.nanopub.templates.TemplateFillException;
+import org.nanopub.templates.TemplateFiller;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.Supplier;
+
+/**
+ * Makes each nanopublication the publishing form makes a second time, with the filler of
+ * nanopub-java and from what is filled in on the form, and logs where the two differ.
+ *
+ * This is the step before the form makes its nanopublications with the library (#936): the log
+ * shows where the two would come out differently, on what people actually fill in. It decides
+ * nothing: the form's own nanopublication is the one that is signed and published, and a
+ * failure here is only logged. Look for {@code Template fill:} in the log.
+ *
+ * The two are compared triple by triple in each graph, with the URI of each nanopublication and
+ * what lies within it written relative to it. The head, the creation time and the signature are
+ * left out, as they differ anyway.
+ */
+public class TemplateFillGuard {
+
+ private static final Logger logger = LoggerFactory.getLogger(TemplateFillGuard.class);
+
+ // So that one odd nanopublication cannot fill the log.
+ private static final int MAX_TRIPLES_LOGGED = 20;
+
+ private TemplateFillGuard() {
+ }
+
+ /**
+ * The outcome of a comparison.
+ *
+ * @param onlyFromForm the triples only the form's nanopublication has
+ * @param onlyFromLibrary the triples only the library's nanopublication has
+ * @param problems why the library could not fill the request, if it could not;
+ * empty otherwise
+ */
+ public record Comparison(Set onlyFromForm, Set onlyFromLibrary, List problems) {
+
+ /**
+ * @return true if the library made the same nanopublication
+ */
+ public boolean isSame() {
+ return onlyFromForm.isEmpty() && onlyFromLibrary.isEmpty() && problems.isEmpty();
+ }
+
+ }
+
+ /**
+ * Fills the request the form gives with the library, compares the result with the form's
+ * nanopublication, and logs what differs.
+ *
+ * @param formNanopub the nanopublication the form made, before it is signed
+ * @param request gives the request for what is filled in on the form
+ * @return the comparison, or null if it could not be made
+ */
+ public static Comparison check(Nanopub formNanopub, Supplier request) {
+ return check(formNanopub, request, TemplateData.RESOLVER);
+ }
+
+ static Comparison check(Nanopub formNanopub, Supplier requestSupplier, NanopubResolver resolver) {
+ String template = null;
+ try {
+ long start = System.currentTimeMillis();
+ FillRequest request = requestSupplier.get();
+ template = request.getTemplate();
+ Comparison comparison;
+ try {
+ Nanopub libraryNanopub = new TemplateFiller(resolver).fill(request);
+ comparison = new Comparison(subtract(triples(formNanopub), triples(libraryNanopub)),
+ subtract(triples(libraryNanopub), triples(formNanopub)), List.of());
+ } catch (TemplateFillException ex) {
+ comparison = new Comparison(Set.of(), Set.of(), ex.getProblems());
+ }
+ long time = System.currentTimeMillis() - start;
+ if (comparison.isSame()) {
+ logger.info("Template fill: the library makes the same nanopublication from template {} ({} ms)", template, time);
+ } else if (!comparison.problems().isEmpty()) {
+ logger.warn("Template fill: the library cannot fill template {} with what the form has: {}", template, String.join("; ", comparison.problems()));
+ logger.info("Template fill: the request was {}", request.toParams());
+ } else {
+ logger.warn("Template fill: the library makes another nanopublication from template {}: {} triple(s) only from the form, {} only from the library ({} ms)",
+ template, comparison.onlyFromForm().size(), comparison.onlyFromLibrary().size(), time);
+ log("only from the form", comparison.onlyFromForm());
+ log("only from the library", comparison.onlyFromLibrary());
+ logger.info("Template fill: the request was {}", request.toParams());
+ }
+ return comparison;
+ } catch (Exception | LinkageError ex) {
+ logger.warn("Template fill: could not compare the nanopublication made from template {}: {}", template, ex.toString());
+ return null;
+ }
+ }
+
+ private static void log(String side, Set triples) {
+ int n = 0;
+ for (String triple : triples) {
+ if (++n > MAX_TRIPLES_LOGGED) {
+ logger.warn("Template fill: ... and {} more {}", triples.size() - MAX_TRIPLES_LOGGED, side);
+ return;
+ }
+ logger.warn("Template fill: {}: {}", side, triple);
+ }
+ }
+
+ private static Set subtract(Set a, Set b) {
+ Set result = new TreeSet<>(a);
+ result.removeAll(b);
+ return result;
+ }
+
+ /**
+ * Returns the triples of a nanopublication's assertion, provenance and publication info,
+ * written relative to the nanopublication, without its creation time.
+ *
+ * @param nanopub the nanopublication
+ * @return the triples, each as "graph: subject predicate object"
+ */
+ static Set triples(Nanopub nanopub) {
+ String base = nanopub.getUri().stringValue().replaceFirst("[/#]$", "");
+ Set triples = new TreeSet<>();
+ add(triples, "assertion", nanopub.getAssertion(), base);
+ add(triples, "provenance", nanopub.getProvenance(), base);
+ for (Statement st : nanopub.getPubinfo()) {
+ if (st.getPredicate().equals(DCTERMS.CREATED) && st.getSubject().equals(nanopub.getUri())) continue;
+ triples.add("pubinfo: " + str(st.getSubject(), base) + " " + str(st.getPredicate(), base) + " " + str(st.getObject(), base));
+ }
+ return triples;
+ }
+
+ private static void add(Set triples, String graph, Collection statements, String base) {
+ for (Statement st : statements) {
+ triples.add(graph + ": " + str(st.getSubject(), base) + " " + str(st.getPredicate(), base) + " " + str(st.getObject(), base));
+ }
+ }
+
+ private static String str(Value value, String base) {
+ if (!(value instanceof IRI)) return value.toString();
+ String s = value.stringValue();
+ if (s.equals(base) || s.equals(base + "/") || s.equals(base + "#")) return "this:";
+ if (s.startsWith(base + "/") || s.startsWith(base + "#")) return "sub:" + s.substring(base.length() + 1);
+ return "<" + s + ">";
+ }
+
+}
diff --git a/src/test/java/com/knowledgepixels/nanodash/component/PublishFormFillGuardTest.java b/src/test/java/com/knowledgepixels/nanodash/component/PublishFormFillGuardTest.java
new file mode 100644
index 00000000..f5aacdd8
--- /dev/null
+++ b/src/test/java/com/knowledgepixels/nanodash/component/PublishFormFillGuardTest.java
@@ -0,0 +1,189 @@
+package com.knowledgepixels.nanodash.component;
+
+import com.knowledgepixels.nanodash.NanodashSession;
+import com.knowledgepixels.nanodash.Utils;
+import com.knowledgepixels.nanodash.WicketApplication;
+import com.knowledgepixels.nanodash.page.PublishPage;
+import com.knowledgepixels.nanodash.template.TemplateData;
+import com.knowledgepixels.nanodash.template.TemplateFillGuard;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.util.tester.WicketTester;
+import org.eclipse.rdf4j.model.IRI;
+import org.eclipse.rdf4j.model.ValueFactory;
+import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
+import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
+import org.eclipse.rdf4j.model.vocabulary.RDF;
+import org.eclipse.rdf4j.model.vocabulary.RDFS;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.nanopub.Nanopub;
+import org.nanopub.NanopubCreator;
+import org.nanopub.templates.FillRequest;
+import org.nanopub.templates.TemplateFiller;
+import org.nanopub.trusty.MakeTrustyNanopub;
+import org.nanopub.vocabulary.NPX;
+import org.nanopub.vocabulary.NTEMPLATE;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Tests that the filler of nanopub-java makes the same nanopublication as the publishing form,
+ * from what is filled in on the form ({@link TemplateFillGuard}, #936). The default provenance
+ * and publication info templates are retrieved from the network, as the form does.
+ */
+class PublishFormFillGuardTest {
+
+ private static final ValueFactory vf = SimpleValueFactory.getInstance();
+
+ private static final String TEMPLATE = "https://w3id.org/np/RAFillGuardFillGuardFillGuardFillGuardFillGua";
+ private static final IRI ME = vf.createIRI("https://orcid.org/0000-0002-1267-0234");
+
+ private WicketTester tester;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ tester = new WicketTester(new WicketApplication());
+ registerTemplate();
+ Field f = NanodashSession.class.getDeclaredField("userIri");
+ f.setAccessible(true);
+ f.set(NanodashSession.get(), ME);
+ }
+
+ // A template for a thing minted in the nanopublication, which introduces it:
+ // ?thing rdfs:label ?name .
+ // ?thing rdfs:comment ?comment . (optional; the language is chosen)
+ // ?thing dct:subject ?keyword . (optional, repeatable)
+ private static void registerTemplate() throws Exception {
+ NanopubCreator creator = new NanopubCreator(TEMPLATE);
+ IRI node = creator.getAssertionUri();
+ IRI thing = vf.createIRI(TEMPLATE + "/thing");
+ IRI name = vf.createIRI(TEMPLATE + "/name");
+ IRI comment = vf.createIRI(TEMPLATE + "/comment");
+ IRI keyword = vf.createIRI(TEMPLATE + "/keyword");
+ creator.addAssertionStatement(node, RDF.TYPE, NTEMPLATE.ASSERTION_TEMPLATE);
+ creator.addAssertionStatement(node, RDFS.LABEL, vf.createLiteral("Fill guard test template"));
+ creator.addAssertionStatement(node, NTEMPLATE.HAS_NANOPUB_LABEL_PATTERN, vf.createLiteral("Thing: ${name}"));
+ addStatement(creator, node, "st1", thing, RDFS.LABEL, name);
+ addStatement(creator, node, "st2", thing, RDFS.COMMENT, comment, NTEMPLATE.OPTIONAL_STATEMENT);
+ addStatement(creator, node, "st3", thing, DCTERMS.SUBJECT, keyword, NTEMPLATE.OPTIONAL_STATEMENT, NTEMPLATE.REPEATABLE_STATEMENT);
+ // An optional group whose status has a default, which the form fills in: left
+ // untouched, the group is left out, default and all.
+ IRI group = vf.createIRI(TEMPLATE + "/st4");
+ IRI status = vf.createIRI(TEMPLATE + "/status");
+ IRI link = vf.createIRI(TEMPLATE + "/link");
+ creator.addAssertionStatement(node, NTEMPLATE.HAS_STATEMENT, group);
+ creator.addAssertionStatement(group, RDF.TYPE, NTEMPLATE.GROUPED_STATEMENT);
+ creator.addAssertionStatement(group, RDF.TYPE, NTEMPLATE.OPTIONAL_STATEMENT);
+ IRI st4a = vf.createIRI(TEMPLATE + "/st4a");
+ IRI st4b = vf.createIRI(TEMPLATE + "/st4b");
+ creator.addAssertionStatement(group, NTEMPLATE.HAS_STATEMENT, st4a);
+ creator.addAssertionStatement(group, NTEMPLATE.HAS_STATEMENT, st4b);
+ creator.addAssertionStatement(st4a, RDF.SUBJECT, thing);
+ creator.addAssertionStatement(st4a, RDF.PREDICATE, DCTERMS.SOURCE);
+ creator.addAssertionStatement(st4a, RDF.OBJECT, link);
+ creator.addAssertionStatement(st4b, RDF.SUBJECT, link);
+ creator.addAssertionStatement(st4b, RDF.PREDICATE, RDFS.COMMENT);
+ creator.addAssertionStatement(st4b, RDF.OBJECT, status);
+ creator.addAssertionStatement(link, RDF.TYPE, NTEMPLATE.EXTERNAL_URI_PLACEHOLDER);
+ creator.addAssertionStatement(link, RDFS.LABEL, vf.createLiteral("a source"));
+ creator.addAssertionStatement(status, RDF.TYPE, NTEMPLATE.LITERAL_PLACEHOLDER);
+ creator.addAssertionStatement(status, RDFS.LABEL, vf.createLiteral("its status"));
+ creator.addAssertionStatement(status, NTEMPLATE.HAS_DEFAULT_VALUE, vf.createLiteral("checked"));
+ creator.addAssertionStatement(thing, RDF.TYPE, NTEMPLATE.URI_PLACEHOLDER);
+ creator.addAssertionStatement(thing, RDF.TYPE, NTEMPLATE.LOCAL_RESOURCE);
+ creator.addAssertionStatement(thing, RDF.TYPE, NTEMPLATE.INTRODUCED_RESOURCE);
+ creator.addAssertionStatement(thing, RDFS.LABEL, vf.createLiteral("the thing"));
+ creator.addAssertionStatement(name, RDF.TYPE, NTEMPLATE.LITERAL_PLACEHOLDER);
+ creator.addAssertionStatement(name, RDFS.LABEL, vf.createLiteral("the name"));
+ creator.addAssertionStatement(comment, RDF.TYPE, NTEMPLATE.LITERAL_PLACEHOLDER);
+ creator.addAssertionStatement(comment, RDF.TYPE, NTEMPLATE.LANGUAGE_TAGGED_LITERAL_PLACEHOLDER);
+ creator.addAssertionStatement(comment, RDFS.LABEL, vf.createLiteral("a comment"));
+ creator.addAssertionStatement(keyword, RDF.TYPE, NTEMPLATE.LITERAL_PLACEHOLDER);
+ creator.addAssertionStatement(keyword, RDFS.LABEL, vf.createLiteral("a keyword"));
+ creator.addProvenanceStatement(creator.getAssertionUri(), RDFS.SEEALSO, creator.getAssertionUri());
+ creator.addPubinfoStatement(RDFS.SEEALSO, creator.getNanopubUri());
+ Nanopub np = creator.finalizeNanopub();
+ assertNotNull(TemplateData.get().registerTemplate(np));
+ // For the library, which retrieves templates through Nanodash's cache:
+ Utils.cacheNanopub(np);
+ }
+
+ private static void addStatement(NanopubCreator creator, IRI node, String id, IRI subject, IRI predicate, IRI object, IRI... types) throws Exception {
+ IRI st = vf.createIRI(TEMPLATE + "/" + id);
+ creator.addAssertionStatement(node, NTEMPLATE.HAS_STATEMENT, st);
+ creator.addAssertionStatement(st, RDF.SUBJECT, subject);
+ creator.addAssertionStatement(st, RDF.PREDICATE, predicate);
+ creator.addAssertionStatement(st, RDF.OBJECT, object);
+ for (IRI type : types) creator.addAssertionStatement(st, RDF.TYPE, type);
+ }
+
+ private PublishForm openForm(PageParameters params) {
+ PublishForm form = new PublishForm("panel", params.add("template", TEMPLATE), PublishPage.class, null);
+ tester.startComponentInPage(form);
+ return form;
+ }
+
+ private static Nanopub createNanopub(PublishForm form) throws Exception {
+ Method createNanopub = PublishForm.class.getDeclaredMethod("createNanopub");
+ createNanopub.setAccessible(true);
+ return (Nanopub) createNanopub.invoke(form);
+ }
+
+ private static void assertSame(PublishForm form) throws Exception {
+ Nanopub np = createNanopub(form);
+ TemplateFillGuard.Comparison comparison = TemplateFillGuard.check(np, form::toFillRequest);
+ assertNotNull(comparison);
+ assertTrue(comparison.isSame(), comparison + "\nrequest: " + form.toFillRequest().toParams());
+ }
+
+ @Test
+ void newNanopublication() throws Exception {
+ PublishForm form = openForm(new PageParameters().add("param_thing", "apple").add("param_name", "Apple")
+ .add("param_comment", "Ein Apfel").add("param_comment__lang", "de")
+ .add("param_keyword", "red").add("param_keyword__1", "green"));
+ assertSame(form);
+ FillRequest request = form.toFillRequest();
+ assertEquals("apple", request.getValues().get("thing").text());
+ assertEquals("de", request.getValues().get("comment").languageTag());
+ assertEquals("green", request.getValues().get("keyword__1").text());
+ }
+
+ @Test
+ void newNanopublicationWithoutTheOptionalStatements() throws Exception {
+ PublishForm form = openForm(new PageParameters().add("param_thing", "apple").add("param_name", "Apple"));
+ assertSame(form);
+ // The default the form filled in is not passed on as a value given, which the library
+ // would refuse to leave out with its statement.
+ assertFalse(form.toFillRequest().getValues().has("status"), form.toFillRequest().toParams().toString());
+ }
+
+ @Test
+ void defaultInAGroupThatIsFilledIn() throws Exception {
+ PublishForm form = openForm(new PageParameters().add("param_thing", "apple").add("param_name", "Apple")
+ .add("param_link", "https://example.org/apple-source"));
+ assertSame(form);
+ Nanopub np = createNanopub(form);
+ assertTrue(np.getAssertion().stream().anyMatch(st -> st.getPredicate().equals(RDFS.COMMENT)
+ && st.getObject().stringValue().equals("checked")), np.getAssertion().toString());
+ }
+
+ @Test
+ void newVersion() throws Exception {
+ // The version before, as the library makes it, made trusty and cached so that the
+ // form finds it without the network.
+ Nanopub before = MakeTrustyNanopub.transform(new TemplateFiller(TemplateData.RESOLVER).fill(new FillRequest(TEMPLATE)
+ .set("thing", "apple").set("name", "Apple").set("keyword", "red").setCreator(ME)));
+ Utils.cacheNanopub(before);
+
+ PublishForm form = openForm(new PageParameters().add("supersede", before.getUri().stringValue()).add("param_name", "Apple tree"));
+ assertSame(form);
+ // The new version keeps the IRI of what it introduces.
+ Nanopub np = createNanopub(form);
+ assertTrue(np.getPubinfo().stream().anyMatch(st -> st.getPredicate().equals(NPX.INTRODUCES)
+ && st.getObject().stringValue().equals(before.getUri().stringValue() + "/apple")), np.getPubinfo().toString());
+ }
+
+}
diff --git a/src/test/java/com/knowledgepixels/nanodash/template/TemplateFillGuardTest.java b/src/test/java/com/knowledgepixels/nanodash/template/TemplateFillGuardTest.java
new file mode 100644
index 00000000..1ed34331
--- /dev/null
+++ b/src/test/java/com/knowledgepixels/nanodash/template/TemplateFillGuardTest.java
@@ -0,0 +1,79 @@
+package com.knowledgepixels.nanodash.template;
+
+import org.eclipse.rdf4j.model.IRI;
+import org.eclipse.rdf4j.model.ValueFactory;
+import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
+import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
+import org.eclipse.rdf4j.model.vocabulary.RDFS;
+import org.junit.jupiter.api.Test;
+import org.nanopub.Nanopub;
+import org.nanopub.NanopubCreator;
+import org.nanopub.templates.FillRequest;
+import org.nanopub.templates.NanopubResolver;
+
+import java.util.Date;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Tests for {@link TemplateFillGuard}: how it compares, and that it never gets in the way. That
+ * the form and the library make the same nanopublication is tested in
+ * {@code PublishFormFillGuardTest}.
+ */
+class TemplateFillGuardTest {
+
+ private static final ValueFactory vf = SimpleValueFactory.getInstance();
+
+ private static final String TEMPLATE = "https://w3id.org/np/RAFillGuardFillGuardFillGuardFillGuardFillGua";
+ private static final IRI ME = vf.createIRI("https://orcid.org/0000-0000-0000-0001");
+
+ private static Nanopub nanopub(String uri, String name, Date created) throws Exception {
+ NanopubCreator creator = new NanopubCreator(uri);
+ creator.addAssertionStatement(vf.createIRI(uri + "apple"), RDFS.LABEL, vf.createLiteral(name));
+ creator.addProvenanceStatement(vf.createIRI("http://www.w3.org/ns/prov#wasAttributedTo"), ME);
+ creator.addPubinfoStatement(DCTERMS.CREATOR, ME);
+ creator.addPubinfoStatement(vf.createIRI(uri + "apple"), RDFS.SEEALSO, vf.createIRI(uri));
+ creator.addTimestamp(created);
+ return creator.finalizeNanopub();
+ }
+
+ @Test
+ void triplesAreWrittenRelativeToTheNanopublication() throws Exception {
+ Set form = TemplateFillGuard.triples(nanopub("https://w3id.org/np/~~~ARTIFACTCODE~~~/", "Apple", new Date(0)));
+ Set library = TemplateFillGuard.triples(nanopub("http://purl.org/nanopub/temp/abc/", "Apple", new Date()));
+ // Another URI and another creation time make no difference.
+ assertEquals(form, library);
+ assertTrue(form.contains("assertion: sub:apple <" + RDFS.LABEL + "> \"Apple\""), form.toString());
+ assertTrue(form.contains("pubinfo: this: <" + DCTERMS.CREATOR + "> <" + ME + ">"), form.toString());
+ assertTrue(form.stream().noneMatch(t -> t.contains(DCTERMS.CREATED.stringValue())), form.toString());
+
+ Set other = TemplateFillGuard.triples(nanopub("https://w3id.org/np/~~~ARTIFACTCODE~~~/", "Pear", new Date(0)));
+ assertNotEquals(form, other);
+ }
+
+ @Test
+ void whatTheLibraryCannotFillIsReported() throws Exception {
+ NanopubResolver nothing = id -> null;
+ TemplateFillGuard.Comparison comparison = TemplateFillGuard.check(nanopub("https://w3id.org/np/~~~ARTIFACTCODE~~~/", "Apple", new Date(0)),
+ () -> new FillRequest(TEMPLATE).set("name", "Apple").setCreator(ME), nothing);
+ assertNotNull(comparison);
+ assertFalse(comparison.isSame());
+ assertFalse(comparison.problems().isEmpty());
+ assertTrue(comparison.problems().get(0).contains(TEMPLATE), comparison.problems().toString());
+ }
+
+ @Test
+ void failureOfTheComparisonIsSwallowed() throws Exception {
+ Nanopub np = nanopub("https://w3id.org/np/~~~ARTIFACTCODE~~~/", "Apple", new Date(0));
+ assertNull(TemplateFillGuard.check(np, () -> {
+ throw new IllegalStateException("no session");
+ }, id -> null));
+ NanopubResolver failing = id -> {
+ throw new IllegalStateException("no network");
+ };
+ assertDoesNotThrow(() -> TemplateFillGuard.check(np, () -> new FillRequest(TEMPLATE), failing));
+ assertDoesNotThrow(() -> TemplateFillGuard.check(null, () -> new FillRequest(TEMPLATE).setCreator(ME), id -> null));
+ }
+
+}