• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanodash / 28936601485

08 Jul 2026 10:43AM UTC coverage: 28.314% (+0.2%) from 28.115%
28936601485

Pull #545

github

web-flow
Merge 2842605b1 into 3cb376d20
Pull Request #545: feat: identify templates by embedded IRIs with dual-mode parser

1838 of 7333 branches covered (25.06%)

Branch coverage included in aggregate %.

3749 of 12399 relevant lines covered (30.24%)

4.5 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.53
src/main/java/com/knowledgepixels/nanodash/component/PublishForm.java
1
package com.knowledgepixels.nanodash.component;
2

3
import com.knowledgepixels.nanodash.*;
4
import com.knowledgepixels.nanodash.domain.AbstractResourceWithProfile;
5
import com.knowledgepixels.nanodash.vocabulary.KPXL_TERMS;
6
import com.knowledgepixels.nanodash.domain.User;
7
import com.knowledgepixels.nanodash.component.menu.EntryActionMenu;
8
import com.knowledgepixels.nanodash.page.*;
9
import com.knowledgepixels.nanodash.template.*;
10
import org.apache.commons.lang3.Strings;
11
import org.apache.wicket.Component;
12
import org.apache.wicket.RestartResponseException;
13
import org.apache.wicket.ajax.AjaxEventBehavior;
14
import org.apache.wicket.ajax.AjaxRequestTarget;
15
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
16
import org.apache.wicket.feedback.FeedbackMessage;
17
import org.apache.wicket.markup.html.WebMarkupContainer;
18
import org.apache.wicket.markup.html.WebPage;
19
import org.apache.wicket.markup.html.basic.Label;
20
import org.apache.wicket.markup.html.form.Button;
21
import org.apache.wicket.markup.html.form.CheckBox;
22
import org.apache.wicket.markup.html.form.Form;
23
import org.apache.wicket.markup.html.form.FormComponent;
24
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
25
import org.apache.wicket.markup.html.list.ListItem;
26
import org.apache.wicket.markup.html.list.ListView;
27
import org.apache.wicket.markup.html.panel.FeedbackPanel;
28
import org.apache.wicket.markup.html.panel.Panel;
29
import org.apache.wicket.markup.repeater.Item;
30
import org.apache.wicket.markup.repeater.data.DataView;
31
import org.apache.wicket.markup.repeater.data.ListDataProvider;
32
import org.apache.wicket.model.IModel;
33
import org.apache.wicket.model.Model;
34
import org.apache.wicket.request.mapper.parameter.PageParameters;
35
import org.eclipse.rdf4j.model.IRI;
36
import org.eclipse.rdf4j.model.Literal;
37
import org.eclipse.rdf4j.model.Statement;
38
import org.eclipse.rdf4j.model.ValueFactory;
39
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
40
import org.eclipse.rdf4j.model.vocabulary.FOAF;
41
import org.eclipse.rdf4j.model.vocabulary.RDF;
42
import org.eclipse.rdf4j.model.vocabulary.RDFS;
43
import org.nanopub.MalformedNanopubException;
44
import org.nanopub.Nanopub;
45
import org.nanopub.NanopubAlreadyFinalizedException;
46
import org.nanopub.NanopubCreator;
47
import org.nanopub.extra.security.SignNanopub;
48
import org.nanopub.extra.security.SignatureAlgorithm;
49
import org.nanopub.extra.security.TransformContext;
50
import org.nanopub.extra.server.PublishNanopub;
51
import org.nanopub.extra.services.ApiResponse;
52
import org.nanopub.extra.services.ApiResponseEntry;
53
import org.nanopub.extra.services.QueryRef;
54
import org.nanopub.vocabulary.NPX;
55
import org.nanopub.vocabulary.NTEMPLATE;
56
import org.slf4j.Logger;
57
import org.slf4j.LoggerFactory;
58
import org.wicketstuff.select2.ChoiceProvider;
59
import org.wicketstuff.select2.Response;
60
import org.wicketstuff.select2.Select2Choice;
61

62
import java.lang.reflect.InvocationTargetException;
63
import java.util.*;
64

65
/**
66
 * Form for publishing a nanopublication.
67
 */
68
public class PublishForm extends Panel {
69

70
    private static final Logger logger = LoggerFactory.getLogger(PublishForm.class);
×
71

72
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
73

74
    public static final String CREATOR_PUB_INFO_TEMPLATE = "https://w3id.org/np/RAukAcWHRDlkqxk7H2XNSegc1WnHI569INvNr-xdptDGI";
75
    public static final String LICENSE_PUB_INFO_TEMPLATE = "https://w3id.org/np/RACJ58Gvyn91LqCKIO9zu1eijDQIeEff28iyDrJgjSJF8";
76
    public static final String DEFAULT_PROV_TEMPLATE = "https://w3id.org/np/RA7lSq6MuK_TIC6JMSHvLtee3lpLoZDOqLJCLXevnrPoU";
77
    private static final String supersedesPubInfoTemplateId = "https://w3id.org/np/RAoTD7udB2KtUuOuAe74tJi1t3VzK0DyWS7rYVAq1GRvw";
78
    private static final String derivesFromPubInfoTemplateId = "https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ";
79

80
    private static final String[] fixedPubInfoTemplates = new String[]{CREATOR_PUB_INFO_TEMPLATE, LICENSE_PUB_INFO_TEMPLATE};
×
81

82
    /**
83
     * Fill modes for the nanopublication to be created.
84
     */
85
    public enum FillMode {
9✔
86
        /**
87
         * Use fill mode
88
         */
89
        USE,
18✔
90
        /**
91
         * Supersede fill mode
92
         */
93
        SUPERSEDE,
18✔
94
        /**
95
         * Derive fill mode
96
         */
97
        DERIVE,
18✔
98
        /**
99
         * Override fill mode: like {@link #DERIVE} in that it records a
100
         * {@code prov:wasDerivedFrom} link, but (like {@link #SUPERSEDE}) it keeps the
101
         * source nanopub's introduced resource IRIs and its root definition nanopub.
102
         */
103
        OVERRIDE
18✔
104
    }
105

106
    protected Form<?> form;
107
    protected FeedbackPanel feedbackPanel;
108
    private final TemplateContext assertionContext;
109
    private TemplateContext provenanceContext;
110
    private final List<TemplateContext> pubInfoContexts = new ArrayList<>();
×
111
    private final Map<String, TemplateContext> pubInfoContextMap = new HashMap<>();
×
112
    private final List<TemplateContext> requiredPubInfoContexts = new ArrayList<>();
×
113
    private String targetNamespace;
114
    private final Class<? extends WebPage> confirmPageClass;
115

116
    /**
117
     * Constructor for the PublishForm.
118
     *
119
     * @param id               the Wicket component ID
120
     * @param pageParams       the parameters for the page, which may include information on how to fill the form
121
     * @param publishPageClass the class of the page to redirect to after successful publication
122
     * @param confirmPageClass the class of the confirmation page to show after publication
123
     */
124
    public PublishForm(String id, final PageParameters pageParams, Class<? extends WebPage> publishPageClass, Class<? extends WebPage> confirmPageClass) {
125
        super(id);
×
126
        setOutputMarkupId(true);
×
127
        this.confirmPageClass = confirmPageClass;
×
128

129
        WebMarkupContainer linkMessageItem = new WebMarkupContainer("link-message-item");
×
130
        if (pageParams.get("link-message").isNull()) {
×
131
            linkMessageItem.add(new Label("link-message", ""));
×
132
            linkMessageItem.setVisible(false);
×
133
        } else {
134
            linkMessageItem.add(new Label("link-message", Utils.sanitizeHtml(pageParams.get("link-message").toString())).setEscapeModelStrings(false));
×
135
        }
136
        add(linkMessageItem);
×
137

138
        final Nanopub fillNp;
139
        final FillMode fillMode;
140
        boolean fillOnlyAssertion = false;
×
141
        if (!pageParams.get("use").isNull()) {
×
142
            fillNp = Utils.getNanopub(pageParams.get("use").toString());
×
143
            fillMode = FillMode.USE;
×
144
        } else if (!pageParams.get("use-a").isNull()) {
×
145
            fillNp = Utils.getNanopub(pageParams.get("use-a").toString());
×
146
            fillMode = FillMode.USE;
×
147
            fillOnlyAssertion = true;
×
148
        } else if (!pageParams.get("supersede").isNull()) {
×
149
            fillNp = Utils.getNanopub(pageParams.get("supersede").toString());
×
150
            fillMode = FillMode.SUPERSEDE;
×
151
            targetNamespace = pageParams.get("supersede").toString().replaceFirst("RA[A-Za-z0-9-_]{43}$", "");
×
152
        } else if (!pageParams.get("supersede-a").isNull()) {
×
153
            fillNp = Utils.getNanopub(pageParams.get("supersede-a").toString());
×
154
            fillMode = FillMode.SUPERSEDE;
×
155
            fillOnlyAssertion = true;
×
156
        } else if (!pageParams.get("derive").isNull()) {
×
157
            fillNp = Utils.getNanopub(pageParams.get("derive").toString());
×
158
            fillMode = FillMode.DERIVE;
×
159
        } else if (!pageParams.get("derive-a").isNull()) {
×
160
            fillNp = Utils.getNanopub(pageParams.get("derive-a").toString());
×
161
            fillMode = FillMode.DERIVE;
×
162
            fillOnlyAssertion = true;
×
163
        } else if (!pageParams.get("override").isNull()) {
×
164
            fillNp = Utils.getNanopub(pageParams.get("override").toString());
×
165
            fillMode = FillMode.OVERRIDE;
×
166
        } else if (!pageParams.get("override-a").isNull()) {
×
167
            fillNp = Utils.getNanopub(pageParams.get("override-a").toString());
×
168
            fillMode = FillMode.OVERRIDE;
×
169
            fillOnlyAssertion = true;
×
170
        } else if (!pageParams.get("fill-all").isNull()) {
×
171
            // TODO: This is deprecated and should be removed at some point
172
            fillNp = Utils.getNanopub(pageParams.get("fill-all").toString());
×
173
            fillMode = FillMode.USE;
×
174
        } else if (!pageParams.get("fill").isNull()) {
×
175
            // TODO: This is deprecated and should be removed at some point
176
            fillNp = Utils.getNanopub(pageParams.get("fill").toString());
×
177
            fillMode = FillMode.SUPERSEDE;
×
178
        } else {
179
            fillNp = null;
×
180
            fillMode = null;
×
181
        }
182

183
        final TemplateData td = TemplateData.get();
×
184

185
        // TODO Properly integrate this namespace feature:
186
        String templateId = pageParams.get("template").toString();
×
187
        if (td.getTemplate(templateId).getTargetNamespace() != null) {
×
188
            targetNamespace = td.getTemplate(templateId).getTargetNamespace();
×
189
        }
190
        if (!pageParams.get("target-namespace").isNull()) {
×
191
            targetNamespace = pageParams.get("target-namespace").toString();
×
192
        }
193
        if (targetNamespace == null) {
×
194
            targetNamespace = Template.DEFAULT_TARGET_NAMESPACE;
×
195
        }
196
        String targetNamespaceLabel = targetNamespace + "...";
×
197
        targetNamespace = targetNamespace + "~~~ARTIFACTCODE~~~/";
×
198

199
        assertionContext = new TemplateContext(ContextType.ASSERTION, templateId, "statement", targetNamespace);
×
200
        assertionContext.setFillMode(fillMode);
×
201
        final String prTemplateId;
202
        if (pageParams.get("prtemplate").toString() != null) {
×
203
            prTemplateId = pageParams.get("prtemplate").toString();
×
204
        } else {
205
            if (fillNp != null && !fillOnlyAssertion) {
×
206
                if (td.getProvenanceTemplateId(fillNp) != null) {
×
207
                    prTemplateId = td.getProvenanceTemplateId(fillNp).stringValue();
×
208
                } else {
209
                    prTemplateId = "http://purl.org/np/RAcm8OurwUk15WOgBM9wySo-T3a5h6as4K8YR5MBrrxUc";
×
210
                }
211
            } else if (assertionContext.getTemplate().getDefaultProvenance() != null) {
×
212
                prTemplateId = assertionContext.getTemplate().getDefaultProvenance().stringValue();
×
213
            } else {
214
                prTemplateId = DEFAULT_PROV_TEMPLATE;
×
215
            }
216
        }
217
        provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateId, "pr-statement", targetNamespace);
×
218
        for (String t : fixedPubInfoTemplates) {
×
219
            // TODO consistently check for latest versions of templates here and below:
220
            TemplateContext c = new TemplateContext(ContextType.PUBINFO, t, "pi-statement", targetNamespace);
×
221
            pubInfoContexts.add(c);
×
222
            pubInfoContextMap.put(c.getTemplate().getId(), c);
×
223
            requiredPubInfoContexts.add(c);
×
224
            if (t.equals(LICENSE_PUB_INFO_TEMPLATE) && fillMode != FillMode.SUPERSEDE && fillMode != FillMode.DERIVE && fillMode != FillMode.OVERRIDE) {
×
225
                IRI defaultLicense = User.getDefaultLicense(NanodashSession.get().getUserIri());
×
226
                if (defaultLicense != null) {
×
227
                    c.setParam("license", defaultLicense.stringValue());
×
228
                }
229
            }
230
        }
231
        if (fillMode == FillMode.SUPERSEDE) {
×
232
            TemplateContext c = new TemplateContext(ContextType.PUBINFO, supersedesPubInfoTemplateId, "pi-statement", targetNamespace);
×
233
            pubInfoContexts.add(c);
×
234
            pubInfoContextMap.put(supersedesPubInfoTemplateId, c);
×
235
            //requiredPubInfoContexts.add(c);
236
            c.setParam("np", fillNp.getUri().stringValue());
×
237
        } else if (fillMode == FillMode.DERIVE || fillMode == FillMode.OVERRIDE) {
×
238
            TemplateContext c = new TemplateContext(ContextType.PUBINFO, derivesFromPubInfoTemplateId, "pi-statement", targetNamespace);
×
239
            pubInfoContexts.add(c);
×
240
            pubInfoContextMap.put(derivesFromPubInfoTemplateId, c);
×
241
            c.setParam("np", fillNp.getUri().stringValue());
×
242
        }
243
        for (IRI r : assertionContext.getTemplate().getRequiredPubInfoElements()) {
×
244
            String latestId = td.getLatestTemplateId(r.stringValue());
×
245
            if (pubInfoContextMap.containsKey(r.stringValue()) || pubInfoContextMap.containsKey(latestId)) continue;
×
246
            TemplateContext c = new TemplateContext(ContextType.PUBINFO, r.stringValue(), "pi-statement", targetNamespace);
×
247
            pubInfoContexts.add(c);
×
248
            pubInfoContextMap.put(c.getTemplateId(), c);
×
249
            requiredPubInfoContexts.add(c);
×
250
        }
×
251
        Map<Integer, TemplateContext> piParamIdMap = new HashMap<>();
×
252
        for (String k : pageParams.getNamedKeys()) {
×
253
            if (!k.matches("pitemplate[1-9][0-9]*")) continue;
×
254
            Integer i = Integer.parseInt(k.replaceFirst("^pitemplate([1-9][0-9]*)$", "$1"));
×
255
            String tid = pageParams.get(k).toString();
×
256
            // TODO Allow for automatically using latest template version:
257
            //String piTemplateIdLatest = QueryApiAccess.getLatestVersionId(tid);
258
            TemplateContext c = createPubInfoContext(tid);
×
259
            if (piParamIdMap.containsKey(i)) {
×
260
                // TODO: handle this error better
261
                logger.error("Publication Info template param identifier defined multiple times: {}", i);
×
262
            }
263
            piParamIdMap.put(i, c);
×
264
        }
×
265
        if (fillNp != null && !fillOnlyAssertion) {
×
266
            for (IRI piTemplateId : td.getPubinfoTemplateIds(fillNp)) {
×
267
                String piTemplateIdLatest = td.getLatestTemplateId(piTemplateId.stringValue());
×
268
                if (piTemplateIdLatest.equals(supersedesPubInfoTemplateId)) continue;
×
269
                if (!pubInfoContextMap.containsKey(piTemplateIdLatest)) {
×
270
                    // TODO Allow for automatically using latest template version
271
                    createPubInfoContext(piTemplateId.stringValue());
×
272
                }
273
            }
×
274
        }
275
        if (!pageParams.get("values-from-query").isEmpty() && !pageParams.get("values-from-query-mapping").isEmpty()) {
×
276
            String querySpec = pageParams.get("values-from-query").toString();
×
277

278
            String mapping = pageParams.get("values-from-query-mapping").toString();
×
279
            String mapsFrom, mapsTo;
280
            if (mapping.contains(":")) {
×
281
                mapsFrom = mapping.split(":")[0];
×
282
                mapsTo = mapping.split(":")[1];
×
283
            } else {
284
                mapsFrom = mapping;
×
285
                mapsTo = mapping;
×
286
            }
287
            ApiResponse resp = ApiCache.retrieveResponseSync(QueryRef.parseString(querySpec), false);
×
288
            int i = 0;
×
289
            for (ApiResponseEntry e : resp.getData()) {
×
290
                String mapsToSuffix = "";
×
291
                if (i > 0) mapsToSuffix = "__" + i;
×
292
                assertionContext.setParam(mapsTo + mapsToSuffix, e.get(mapsFrom));
×
293
                i++;
×
294
            }
×
295
        }
296
        for (String k : pageParams.getNamedKeys()) {
×
297
            if (k.startsWith("param_")) assertionContext.setParam(k.substring(6), pageParams.get(k).toString());
×
298
            if (k.startsWith("prparam_")) provenanceContext.setParam(k.substring(8), pageParams.get(k).toString());
×
299
            if (k.matches("piparam[1-9][0-9]*_.*")) {
×
300
                Integer i = Integer.parseInt(k.replaceFirst("^piparam([1-9][0-9]*)_.*$", "$1"));
×
301
                if (!piParamIdMap.containsKey(i)) {
×
302
                    logger.error("Parameter {} of the publication info template not found", i);
×
303
                    continue;
×
304
                }
305
                String n = k.replaceFirst("^piparam[1-9][0-9]*_(.*)$", "$1");
×
306
                logger.info(n);
×
307
                piParamIdMap.get(i).setParam(n, pageParams.get(k).toString());
×
308
            }
309
        }
×
310

311
        final Nanopub improveNp;
312
        if (!pageParams.get("improve").isNull()) {
×
313
            improveNp = Utils.getNanopub(pageParams.get("improve").toString());
×
314
        } else {
315
            improveNp = null;
×
316
        }
317

318
        // Propagate fill source (supersede/derive/improve) so contexts can resolve
319
        // the `local:nanopub`/`local:assertion` sentinels to the fill nanopub's URIs.
320
        Nanopub fillSource = fillNp != null ? fillNp : improveNp;
×
321
        if (fillSource != null) {
×
322
            assertionContext.setFillSource(fillSource);
×
323
            provenanceContext.setFillSource(fillSource);
×
324
            for (TemplateContext c : pubInfoContexts) {
×
325
                c.setFillSource(fillSource);
×
326
            }
×
327
        }
328

329
        // Init statements only now, in order to pick up parameter values:
330
        assertionContext.initStatements();
×
331
        provenanceContext.initStatements();
×
332
        for (TemplateContext c : pubInfoContexts) {
×
333
            c.initStatements();
×
334
        }
×
335

336
        String latestAssertionId = td.getLatestTemplateId(assertionContext.getTemplateId());
×
337
        if (!assertionContext.getTemplateId().equals(latestAssertionId)) {
×
338
            add(new Label("newversion", "There is a new version of this assertion template:"));
×
339
            PageParameters params = new PageParameters(pageParams);
×
340
            params.set("template", latestAssertionId);
×
341
            add(new BookmarkablePageLink<Void>("newversionlink", publishPageClass, params));
×
342
            if ("latest".equals(pageParams.get("template-version").toString())) {
×
343
                throw new RestartResponseException(publishPageClass, params);
×
344
            }
345
        } else {
×
346
            add(new Label("newversion", "").setVisible(false));
×
347
            add(new Label("newversionlink", "").setVisible(false));
×
348
        }
349

350
        final List<Statement> unusedStatementList = new ArrayList<>();
×
351
        final List<Statement> unusedPrStatementList = new ArrayList<>();
×
352
        final List<Statement> unusedPiStatementList = new ArrayList<>();
×
353
        if (fillNp != null) {
×
354
            ValueFiller filler = new ValueFiller(fillNp, ContextType.ASSERTION, true, fillMode);
×
355
            filler.fill(assertionContext);
×
356
            unusedStatementList.addAll(filler.getUnusedStatements());
×
357

358
            if (!fillOnlyAssertion) {
×
359
                ValueFiller prFiller = new ValueFiller(fillNp, ContextType.PROVENANCE, true);
×
360
                prFiller.fill(provenanceContext);
×
361
                unusedPrStatementList.addAll(prFiller.getUnusedStatements());
×
362

363
                ValueFiller piFiller = new ValueFiller(fillNp, ContextType.PUBINFO, true);
×
364
                if (!assertionContext.getTemplate().getTargetNanopubTypes().isEmpty()) {
×
365
                    for (Statement st : new ArrayList<>(piFiller.getUnusedStatements())) {
×
366
                        if (st.getSubject().stringValue().equals(LocalUri.of("nanopub").stringValue()) && st.getPredicate().equals(NPX.HAS_NANOPUB_TYPE)) {
×
367
                            if (assertionContext.getTemplate().getTargetNanopubTypes().contains(st.getObject())) {
×
368
                                piFiller.removeUnusedStatement(st);
×
369
                            }
370
                        }
371
                    }
×
372
                }
373
                for (TemplateContext c : pubInfoContexts) {
×
374
                    piFiller.fill(c);
×
375
                }
×
376
                piFiller.removeUnusedStatements(NanodashSession.get().getUserIri(), FOAF.NAME, null);
×
377
                if (piFiller.hasUnusedStatements()) {
×
378
                    final String handcodedStatementsTemplateId = "https://w3id.org/np/RAMEgudZsQ1bh1fZhfYnkthqH6YSXpghSE_DEN1I-6eAI";
×
379
                    if (!pubInfoContextMap.containsKey(handcodedStatementsTemplateId)) {
×
380
                        TemplateContext c = createPubInfoContext(handcodedStatementsTemplateId);
×
381
                        c.setFillSource(fillNp);
×
382
                        c.initStatements();
×
383
                        piFiller.fill(c);
×
384
                    }
385
                }
386
                unusedPiStatementList.addAll(piFiller.getUnusedStatements());
×
387
                // TODO: Also use pubinfo templates stated in nanopub to be filled in?
388
//                                Set<IRI> pubinfoTemplateIds = Template.getPubinfoTemplateIds(fillNp);
389
//                                if (!pubinfoTemplateIds.isEmpty()) {
390
//                                        ValueFiller piFiller = new ValueFiller(fillNp, ContextType.PUBINFO);
391
//                                        for (IRI pubinfoTemplateId : pubinfoTemplateIds) {
392
//                                                // TODO: Make smart choice on the ordering in trying to fill in all pubinfo elements
393
//                                                piFiller.fill(pubInfoContextMap.get(pubinfoTemplateId.stringValue()));
394
//                                        }
395
//                                        warningMessage += (piFiller.getWarningMessage() == null ? "" : "Publication info: " + piFiller.getWarningMessage() + " ");
396
//                                }
397
            }
398
        } else if (improveNp != null) {
×
399
            ValueFiller filler = new ValueFiller(improveNp, ContextType.ASSERTION, true);
×
400
            filler.fill(assertionContext);
×
401
            unusedStatementList.addAll(filler.getUnusedStatements());
×
402
        }
403
        if (!unusedStatementList.isEmpty()) {
×
404
            add(new Label("warnings", "Some content from the existing nanopublication could not be filled in:"));
×
405
        } else {
406
            add(new Label("warnings", "").setVisible(false));
×
407
        }
408
        add(new DataView<Statement>("unused-statements", new ListDataProvider<Statement>(unusedStatementList)) {
×
409

410
            @Override
411
            protected void populateItem(Item<Statement> item) {
412
                item.add(new TripleItem("unused-statement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
413
            }
×
414

415
        });
416
        add(new DataView<Statement>("unused-prstatements", new ListDataProvider<Statement>(unusedPrStatementList)) {
×
417

418
            @Override
419
            protected void populateItem(Item<Statement> item) {
420
                item.add(new TripleItem("unused-prstatement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
421
            }
×
422

423
        });
424
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
425

426
            @Override
427
            protected void populateItem(Item<Statement> item) {
428
                item.add(new TripleItem("unused-pistatement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
429
            }
×
430

431
        });
432

433
        // Finalize statements, which picks up parameter values in repetitions:
434
        assertionContext.finalizeStatements();
×
435
        provenanceContext.finalizeStatements();
×
436
        for (TemplateContext c : pubInfoContexts) {
×
437
            c.finalizeStatements();
×
438
        }
×
439

440
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
441
        consentCheck.add(new InvalidityHighlighting());
×
442

443
        form = new Form<Void>("form") {
×
444

445
            @Override
446
            protected void onConfigure() {
447
                super.onConfigure();
×
448
                form.getFeedbackMessages().clear();
×
449
//                                formComponents.clear();
450
            }
×
451

452
            protected void onSubmit() {
453
                if (!Boolean.TRUE.equals(consentCheck.getModelObject())) {
×
454
                    feedbackPanel.error("You need to check the checkbox that you understand the consequences.");
×
455
                    return;
×
456
                }
457
                logger.info("Publish form submitted");
×
458
                Nanopub signedNp;
459
                try {
460
                    Nanopub np = createNanopub();
×
461
                    logger.info("Nanopublication created: {}", np.getUri());
×
462
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
463
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
464
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
465
                    String npUrl = PublishNanopub.publish(signedNp);
×
466
                    logger.info("Nanopublication published: {}", npUrl);
×
467
                    Utils.cacheNanopub(signedNp);
×
468
                } catch (Exception ex) {
×
469
                    signedNp = null;
×
470
                    logger.error("Nanopublication publishing failed: {}", ex.getMessage());
×
471
                    String message = ex.getClass().getName();
×
472
                    if (ex.getMessage() != null) {
×
473
                        message = ex.getMessage();
×
474
                    }
475
                    feedbackPanel.error(message);
×
476
                }
×
477
                if (signedNp != null) {
×
478
                    String toRefresh = pageParams.get("refresh-upon-publish").toString("");
×
479
                    if (!toRefresh.isEmpty()) {
×
480
                        WicketApplication.get().notifyNanopubPublished(signedNp, toRefresh, 5 * 1000);
×
481
                    }
482
                    String contextId = pageParams.get("context").toString("");
×
483
                    // Broaden the refresh: also force-refresh the context resource's own
484
                    // data (e.g. a space's roles/members) so the page we redirect to —
485
                    // typically its Content tab — reflects the just-published change, not
486
                    // only the specific view query that was acted on.
487
                    if (!contextId.isEmpty() && !contextId.equals(toRefresh)
×
488
                            && AbstractResourceWithProfile.isResourceWithProfile(contextId)) {
×
489
                        WicketApplication.get().notifyNanopubPublished(signedNp, contextId, 5 * 1000);
×
490
                    }
491
                    if (pageParams.get("postpub-redirect-url").isEmpty() && confirmPageClass == null) {
×
492
                        // Forward to the context resource's page, or home if no context; always throws.
493
                        NavigationContext.redirectAfterPublish(signedNp, pageParams);
×
494
                    }
495
                    // Connector flow: show the connector's own confirmation page.
496
                    NanodashPage confirmPage = getConfirmPage(signedNp, pageParams);
×
497
                    if (confirmPage != null) {
×
498
                        throw new RestartResponseException(confirmPage);
×
499
                    }
500
                    NavigationContext.redirectAfterPublish(signedNp, pageParams);
×
501
                }
502
            }
×
503

504
            @Override
505
            protected void onValidate() {
506
                super.onValidate();
×
507
                for (Component fc : assertionContext.getComponents()) {
×
508
                    processFeedback(fc);
×
509
                }
×
510
                for (Component fc : provenanceContext.getComponents()) {
×
511
                    processFeedback(fc);
×
512
                }
×
513
                for (TemplateContext c : pubInfoContexts) {
×
514
                    for (Component fc : c.getComponents()) {
×
515
                        processFeedback(fc);
×
516
                    }
×
517
                }
×
518
            }
×
519

520
            private void processFeedback(Component c) {
521
                if (c instanceof FormComponent) {
×
522
                    ((FormComponent<?>) c).processInput();
×
523
                }
524
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
525
                    form.getFeedbackMessages().add(fm);
×
526
                }
×
527
            }
×
528

529
        };
530
        form.setOutputMarkupId(true);
×
531

532
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
533

534
        form.add(newSourceMenu("templatelink", assertionContext.getTemplate().getId()));
×
535
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
536
        String description = assertionContext.getTemplate().getLabel();
×
537
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
538

539
        form.add(new ListView<StatementItem>("statements", assertionContext.getStatementItems()) {
×
540

541
            protected void populateItem(ListItem<StatementItem> item) {
542
                item.add(item.getModelObject());
×
543
            }
×
544

545
        });
546

547
        final Map<String, Boolean> handledProvTemplates = new HashMap<>();
×
548
        final String defaultProvTemplateId;
549
        if (assertionContext.getTemplate().getDefaultProvenance() != null) {
×
550
            defaultProvTemplateId = assertionContext.getTemplate().getDefaultProvenance().stringValue();
×
551
            handledProvTemplates.put(defaultProvTemplateId, true);
×
552
        } else {
553
            defaultProvTemplateId = null;
×
554
        }
555
        final List<String> recommendedProvTemplateOptionIds = new ArrayList<>();
×
556
        final List<String> provTemplateOptionIds = new ArrayList<>();
×
557
        if (pageParams.get("prtemplate-options").isNull()) {
×
558
            // TODO Make this dynamic and consider updated templates:
559
            recommendedProvTemplateOptionIds.add(DEFAULT_PROV_TEMPLATE);
×
560
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAcTpoh5Ra0ssqmcpOgWdaZ_YiPE6demO6cpw-2RvSNs8");
×
561
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA4LGtuOqTIMqVAkjnfBXk1YDcAPNadP5CGiaJiBkdHCQ");
×
562
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAl_-VTw9Re_uRF8r8y0rjlfnu7FlhTa8xg_8xkcweqiE");
×
563
            recommendedProvTemplateOptionIds.add("https://w3id.org/np/RASORV2mMEVpS4lWh2bwUTEcV-RWjbD9RPbN7J0PIeYAU");
×
564
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAjkBbM5yQm7hKH1l_Jk3HAUqWi3Bd57TPmAOZCsZmi_M");
×
565
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAGXx_k9eQMnXaCbsXMsJbGClwZtQEGNg0GVJu6amdAVw");
×
566
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA1fnITI3Pu1UQ0CHghNpys3JwQrM32LBnjmDLoayp9-4");
×
567
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAJgbsGeGdTG-zq_gU0TLw4s3raMgoRk-mPlc2DSLXvE0");
×
568
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA6SXfhUY-xeblZU8HhPddw6tsu-C5NXevG6C_zv4bMxU");
×
569
            for (String s : recommendedProvTemplateOptionIds) {
×
570
                handledProvTemplates.put(s, true);
×
571
            }
×
572

573
            for (ApiResponseEntry t : td.getProvenanceTemplates()) {
×
574
                String tid = t.get("np");
×
575
                if (handledProvTemplates.containsKey(tid)) continue;
×
576
                provTemplateOptionIds.add(tid);
×
577
                handledProvTemplates.put(tid, true);
×
578
            }
×
579
        } else {
580
            for (String s : pageParams.get("prtemplate-options").toString().split(" ")) {
×
581
                if (handledProvTemplates.containsKey(s)) continue;
×
582
                recommendedProvTemplateOptionIds.add(s);
×
583
                handledProvTemplates.put(s, true);
×
584
            }
585
        }
586

587
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
588

589
            @Override
590
            public String getDisplayValue(String object) {
591
                if (object == null || object.isEmpty()) return "";
×
592
                Template t = td.getTemplate(object);
×
593
                if (t != null) return t.getLabel();
×
594
                return object;
×
595
            }
596

597
            @Override
598
            public String getIdValue(String object) {
599
                return object;
×
600
            }
601

602
            // Getting strange errors with Tomcat if this method is not overridden:
603
            @Override
604
            public void detach() {
605
            }
×
606

607
            @Override
608
            public void query(String term, int page, Response<String> response) {
609
                if (term == null) term = "";
×
610
                term = term.toLowerCase();
×
611
                if (pageParams.get("prtemplate").toString() != null) {
×
612
                    // Using this work-around with "——" because 'optgroup' is not available through Wicket's Select2 classes
613
                    response.add("—— default for this link ——");
×
614
                    response.add(prTemplateId);
×
615
                }
616
                if (defaultProvTemplateId != null) {
×
617
                    response.add("—— default for this template ——");
×
618
                    response.add(defaultProvTemplateId);
×
619
                }
620
                if (!recommendedProvTemplateOptionIds.isEmpty()) {
×
621
                    if (pageParams.get("prtemplate-options").isNull()) {
×
622
                        response.add("—— recommended ——");
×
623
                    }
624
                    for (String s : recommendedProvTemplateOptionIds) {
×
625
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
626
                            response.add(s);
×
627
                        }
628
                    }
×
629
                }
630
                if (!provTemplateOptionIds.isEmpty()) {
×
631
                    response.add("—— others ——");
×
632
                    for (String s : provTemplateOptionIds) {
×
633
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
634
                            response.add(s);
×
635
                        }
636
                    }
×
637
                }
638
            }
×
639

640
            @Override
641
            public Collection<String> toChoices(Collection<String> ids) {
642
                return ids;
×
643
            }
644

645
        };
646
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
647
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
648
        prTemplateChoice.setRequired(true);
×
649
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
650
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
651

652
            @Override
653
            protected void onUpdate(AjaxRequestTarget target) {
654
                String o = prTemplateModel.getObject();
×
655
                if (o.startsWith("——")) {
×
656
                    o = provenanceContext.getTemplate().getId();
×
657
                    prTemplateModel.setObject(o);
×
658
                }
659
                provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateModel.getObject(), "pr-statement", targetNamespace);
×
660
                provenanceContext.initStatements();
×
661
                refreshProvenance(target);
×
662
                provenanceContext.finalizeStatements();
×
663
            }
×
664

665
        });
666
        form.add(prTemplateChoice);
×
667
        refreshProvenance(null);
×
668

669
        final Map<String, Boolean> handledPiTemplates = new HashMap<>();
×
670
        final List<String> recommendedPiTemplateOptionIds = new ArrayList<>();
×
671
        final List<String> piTemplateOptionIds = new ArrayList<>();
×
672
        // TODO Make this dynamic and consider updated templates:
673
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAXflINqt3smqxV5Aq7E9lzje4uLdkKIOefa6Bp8oJ8CY");
×
674
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ");
×
675
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RA16U9Wo30ObhrK1NzH7EsmVRiRtvEuEA_Dfc-u8WkUCA");
×
676
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAdyqI6k07V5nAS82C6hvIDtNWk179EIV4DV-sLbOFKg4");
×
677
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RAjvEpLZUE7rMoa8q6mWSsN6utJDp-5FmgO47YGsbgw3w");
×
678
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAxuGRKID6yNg63V5Mf0ot2NjncOnodh-mkN3qT_1txGI");
×
679
        for (TemplateContext c : pubInfoContexts) {
×
680
            // Key both ID forms: the "others" dedup below compares against listing
681
            // entries keyed by nanopub URI, which for a template with embedded
682
            // identity differs from its canonical ID.
683
            handledPiTemplates.put(c.getTemplate().getId(), true);
×
684
            handledPiTemplates.put(c.getTemplate().getNanopub().getUri().stringValue(), true);
×
685
        }
×
686
        for (String s : recommendedPiTemplateOptionIds) {
×
687
            handledPiTemplates.put(s, true);
×
688
        }
×
689

690
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
691
            String tid = entry.get("np");
×
692
            if (handledPiTemplates.containsKey(tid)) continue;
×
693
            piTemplateOptionIds.add(tid);
×
694
            handledPiTemplates.put(tid, true);
×
695
        }
×
696

697
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
698

699
            @Override
700
            public String getDisplayValue(String object) {
701
                if (object == null || object.isEmpty()) return "";
×
702
                Template t = td.getTemplate(object);
×
703
                if (t != null) return t.getLabel();
×
704
                return object;
×
705
            }
706

707
            @Override
708
            public String getIdValue(String object) {
709
                return object;
×
710
            }
711

712
            // Getting strange errors with Tomcat if this method is not overridden:
713
            @Override
714
            public void detach() {
715
            }
×
716

717
            @Override
718
            public void query(String term, int page, Response<String> response) {
719
                if (term == null) term = "";
×
720
                term = term.toLowerCase();
×
721
                if (!recommendedPiTemplateOptionIds.isEmpty()) {
×
722
                    response.add("—— recommended ——");
×
723
                    for (String s : recommendedPiTemplateOptionIds) {
×
724
                        boolean isAlreadyUsed = false;
×
725
                        for (TemplateContext c : pubInfoContexts) {
×
726
                            // TODO: make this more efficient/nicer
727
                            if (c.getTemplate().hasId(s)) {
×
728
                                isAlreadyUsed = true;
×
729
                                break;
×
730
                            }
731
                        }
×
732
                        if (isAlreadyUsed) continue;
×
733
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
734
                            response.add(s);
×
735
                        }
736
                    }
×
737
                }
738
                if (!piTemplateOptionIds.isEmpty()) {
×
739
                    response.add("—— others ——");
×
740
                    for (String s : piTemplateOptionIds) {
×
741
                        boolean isAlreadyUsed = false;
×
742
                        for (TemplateContext c : pubInfoContexts) {
×
743
                            // TODO: make this more efficient/nicer
744
                            if (c.getTemplate().hasId(s)) {
×
745
                                isAlreadyUsed = true;
×
746
                                break;
×
747
                            }
748
                        }
×
749
                        if (isAlreadyUsed) continue;
×
750
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
751
                            response.add(s);
×
752
                        }
753
                    }
×
754
                }
755
            }
×
756

757
            @Override
758
            public Collection<String> toChoices(Collection<String> ids) {
759
                return ids;
×
760
            }
761

762
        };
763
        final IModel<String> newPiTemplateModel = Model.of();
×
764
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
765
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
766
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
767
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
768

769
            @Override
770
            protected void onUpdate(AjaxRequestTarget target) {
771
                if (newPiTemplateModel.getObject().startsWith("——")) {
×
772
                    newPiTemplateModel.setObject(null);
×
773
                    refreshPubInfo(target);
×
774
                    return;
×
775
                }
776
                String id = newPiTemplateModel.getObject();
×
777
                TemplateContext c = new TemplateContext(ContextType.PUBINFO, id, "pi-statement", targetNamespace);
×
778
                c.initStatements();
×
779
                pubInfoContexts.add(c);
×
780
                newPiTemplateModel.setObject(null);
×
781
                refreshPubInfo(target);
×
782
                c.finalizeStatements();
×
783
            }
×
784

785
        });
786
        form.add(piTemplateChoice);
×
787
        refreshPubInfo(null);
×
788

789
        form.add(consentCheck);
×
790

791
        form.add(new Button("preview-button") {
×
792
            @Override
793
            public void onSubmit() {
794
                try {
795
                    Nanopub np = createNanopub();
×
796
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
797
                    Nanopub signedNp = SignNanopub.signAndTransform(np, tc);
×
798
                    String previewId = signedNp.getUri().stringValue();
×
799
                    NanodashSession.get().setPreviewNanopub(previewId,
×
800
                            new NanodashSession.PreviewNanopub(signedNp, pageParams, confirmPageClass, Boolean.TRUE.equals(consentCheck.getModelObject()), getPage().getPageReference()));
×
801
                    throw new RestartResponseException(PreviewPage.class, new PageParameters().set("id", previewId));
×
802
                } catch (RestartResponseException ex) {
×
803
                    throw ex;
×
804
                } catch (Exception ex) {
×
805
                    logger.error("Preview failed: {}", ex.getMessage());
×
806
                    String message = ex.getClass().getName();
×
807
                    if (ex.getMessage() != null) {
×
808
                        message = ex.getMessage();
×
809
                    }
810
                    feedbackPanel.error(message);
×
811
                }
812
            }
×
813
        });
814

815
        add(form);
×
816

817
        feedbackPanel = new FeedbackPanel("feedback");
×
818
        feedbackPanel.setOutputMarkupId(true);
×
819
        add(feedbackPanel);
×
820
    }
×
821

822
    static EntryActionMenu newSourceMenu(String id, String templateId) {
823
        BookmarkablePageLink<Void> sourceLink = new BookmarkablePageLink<>("link", ExplorePage.class, new PageParameters().set("id", templateId));
×
824
        sourceLink.add(NavigationContext.pageContextFallback());
×
825
        sourceLink.setBody(Model.of("<span class=\"actionmenu-icon\">↗︎</span>source")).setEscapeModelStrings(false);
×
826
        return new EntryActionMenu(id, List.of(sourceLink));
×
827
    }
828

829
    private void refreshProvenance(AjaxRequestTarget target) {
830
        if (target != null) {
×
831
            form.remove("prtemplatelink");
×
832
            form.remove("pr-statements");
×
833
            target.add(form);
×
834
            target.appendJavaScript("updateElements();");
×
835
        }
836
        form.add(newSourceMenu("prtemplatelink", provenanceContext.getTemplate().getId()));
×
837
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
838

839
            protected void populateItem(ListItem<StatementItem> item) {
840
                item.add(item.getModelObject());
×
841
            }
×
842

843
        };
844
        list.setOutputMarkupId(true);
×
845
        form.add(list);
×
846
    }
×
847

848
    private void refreshPubInfo(AjaxRequestTarget target) {
849
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
850

851
            protected void populateItem(ListItem<TemplateContext> item) {
852
                final TemplateContext pic = item.getModelObject();
×
853
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
854
                item.add(newSourceMenu("pitemplatelink", pic.getTemplate().getId()));
×
855
                Label remove = new Label("piremove", "×");
×
856
                item.add(remove);
×
857
                remove.add(new AjaxEventBehavior("click") {
×
858

859
                    @Override
860
                    protected void onEvent(AjaxRequestTarget target) {
861
                        pubInfoContexts.remove(pic);
×
862
                        target.add(PublishForm.this);
×
863
                        target.appendJavaScript("updateElements();");
×
864
                    }
×
865

866
                });
867
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
868
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
869

870
                    protected void populateItem(ListItem<StatementItem> item) {
871
                        item.add(item.getModelObject());
×
872
                    }
×
873

874
                });
875
            }
×
876

877
        };
878
        list.setOutputMarkupId(true);
×
879
        if (target == null) {
×
880
            form.add(list);
×
881
        } else {
882
            form.remove("pis");
×
883
            form.add(list);
×
884
            target.add(form);
×
885
            target.appendJavaScript("updateElements();");
×
886
        }
887
    }
×
888

889
    private TemplateContext createPubInfoContext(String piTemplateId) {
890
        TemplateContext c;
891
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
892
            c = pubInfoContextMap.get(piTemplateId);
×
893
        } else {
894
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
895
            pubInfoContextMap.put(piTemplateId, c);
×
896
            pubInfoContexts.add(c);
×
897
        }
898
        return c;
×
899
    }
900

901
    private synchronized Nanopub createNanopub() throws MalformedNanopubException, NanopubAlreadyFinalizedException {
902
        assertionContext.getIntroducedIris().clear();
×
903
        assertionContext.getRolePropertyPins().clear();
×
904
        NanopubCreator npCreator = new NanopubCreator(targetNamespace);
×
905
        npCreator.setAssertionUri(vf.createIRI(targetNamespace + "assertion"));
×
906
        assertionContext.propagateStatements(npCreator);
×
907
        provenanceContext.propagateStatements(npCreator);
×
908
        for (TemplateContext c : pubInfoContexts) {
×
909
            c.propagateStatements(npCreator);
×
910
        }
×
911
        for (IRI introducedIri : assertionContext.getIntroducedIris()) {
×
912
            npCreator.addPubinfoStatement(NPX.INTRODUCES, introducedIri);
×
913
        }
×
914
        for (IRI embeddedIri : assertionContext.getEmbeddedIris()) {
×
915
            npCreator.addPubinfoStatement(NPX.EMBEDS, embeddedIri);
×
916
        }
×
917
        Map<IRI, IRI> rolePropertyPins = assertionContext.getRolePropertyPins();
×
918
        if (!rolePropertyPins.isEmpty()) {
×
919
            // A role predicate carrying a direction pin makes this a role-instantiation
920
            // nanopub; nanopub-query's pin-resolution branch is gated on this type (#525).
921
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, KPXL_TERMS.ROLE_INSTANTIATION);
×
922
            for (Map.Entry<IRI, IRI> pin : rolePropertyPins.entrySet()) {
×
923
                npCreator.addPubinfoStatement(pin.getKey(), RDF.TYPE, pin.getValue());
×
924
            }
×
925
        }
926
        npCreator.addNamespace("this", targetNamespace);
×
927
        npCreator.addNamespace("sub", targetNamespace + "/");
×
928
        npCreator.addTimestampNow();
×
929
        // The canonical template ID: the embedded template-node IRI for templates
930
        // with embedded identity, the nanopub URI for legacy ones.
931
        IRI templateUri = vf.createIRI(assertionContext.getTemplate().getId());
×
932
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_TEMPLATE, templateUri);
×
933
        IRI prTemplateUri = vf.createIRI(provenanceContext.getTemplate().getId());
×
934
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PROVENANCE_TEMPLATE, prTemplateUri);
×
935
        for (TemplateContext c : pubInfoContexts) {
×
936
            IRI piTemplateUri = vf.createIRI(c.getTemplate().getId());
×
937
            npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PUBINFO_TEMPLATE, piTemplateUri);
×
938
        }
×
939
        String nanopubLabel = getNanopubLabel(npCreator);
×
940
        if (nanopubLabel != null) {
×
941
            npCreator.addPubinfoStatement(RDFS.LABEL, vf.createLiteral(nanopubLabel));
×
942
        }
943
        for (IRI type : assertionContext.getTemplate().getTargetNanopubTypes()) {
×
944
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, type);
×
945
        }
×
946
        IRI userIri = NanodashSession.get().getUserIri();
×
947
        if (User.getName(userIri) != null) {
×
948
            npCreator.addPubinfoStatement(userIri, FOAF.NAME, vf.createLiteral(User.getName(userIri)));
×
949
            npCreator.addNamespace("foaf", FOAF.NAMESPACE);
×
950
        }
951
        String websiteUrl = NanodashPreferences.get().getWebsiteUrl();
×
952
        if (websiteUrl != null) {
×
953
            npCreator.addPubinfoStatement(NPX.WAS_CREATED_AT, vf.createIRI(websiteUrl));
×
954
        }
955
        return npCreator.finalizeNanopub();
×
956
    }
957

958
    private String getNanopubLabel(NanopubCreator npCreator) {
959
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
960

961
        Map<IRI, String> labelMap = new HashMap<>();
×
962
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
963
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
964
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
965
            }
966
        }
×
967

968
        String nanopubLabel = assertionContext.getTemplate().getNanopubLabelPattern();
×
969
        while (nanopubLabel.matches(".*\\$\\{[_a-zA-Z0-9-]+\\}.*")) {
×
970
            String placeholderPostfix = nanopubLabel.replaceFirst("^.*\\$\\{([_a-zA-Z0-9-]+)\\}.*$", "$1");
×
971
            IRI placeholderIriHash = vf.createIRI(assertionContext.getTemplateNanopubUri() + "#" + placeholderPostfix);
×
972
            IRI placeholderIriSlash = vf.createIRI(assertionContext.getTemplateNanopubUri() + "/" + placeholderPostfix);
×
973
            IRI placeholderIri;
974
            String placeholderValue = "";
×
975
            if (assertionContext.getComponentModels().get(placeholderIriSlash) != null) {
×
976
                placeholderIri = placeholderIriSlash;
×
977
            } else {
978
                placeholderIri = placeholderIriHash;
×
979
            }
980
            IModel<String> m = (IModel<String>) assertionContext.getComponentModels().get(placeholderIri);
×
981
            if (m != null) placeholderValue = m.orElse("").getObject();
×
982
            if (placeholderValue == null) placeholderValue = "";
×
983
            String placeholderLabel = placeholderValue;
×
984
            if (assertionContext.getTemplate().isUriPlaceholder(placeholderIri)) {
×
985
                try {
986
                    // TODO Fix this. It doesn't work for placeholders with auto-encode placeholders, etc.
987
                    //      Not sure we need labels for these, but this code should be improved anyway.
988
                    String prefix = assertionContext.getTemplate().getPrefix(placeholderIri);
×
989
                    if (prefix != null) placeholderValue = prefix + placeholderValue;
×
990
                    IRI placeholderValueIri = vf.createIRI(placeholderValue);
×
991
                    String l = assertionContext.getTemplate().getLabel(placeholderValueIri);
×
992
                    if (labelMap.containsKey(placeholderValueIri)) {
×
993
                        l = labelMap.get(placeholderValueIri);
×
994
                    }
995
                    if (l == null) l = GuidedChoiceItem.getLabel(placeholderValue);
×
996
                    if (assertionContext.getTemplate().isAgentPlaceholder(placeholderIri) && !placeholderValue.isEmpty()) {
×
997
                        l = User.getName(vf.createIRI(placeholderValue));
×
998
                    }
999
                    if (l != null && !l.isEmpty()) {
×
1000
                        placeholderLabel = l.replaceFirst(" - .*$", "");
×
1001
                    } else {
1002
                        placeholderLabel = Utils.getShortNameFromURI(placeholderValueIri);
×
1003
                    }
1004
                } catch (Exception ex) {
×
1005
                    logger.error("Nanopub label placeholder IRI error: {}", ex.getMessage());
×
1006
                }
×
1007
            }
1008
            placeholderLabel = placeholderLabel.replaceAll("\\s+", " ");
×
1009
            if (placeholderLabel.length() > 100) placeholderLabel = placeholderLabel.substring(0, 97) + "...";
×
1010
            nanopubLabel = Strings.CS.replace(nanopubLabel, "${" + placeholderPostfix + "}", placeholderLabel);
×
1011
        }
×
1012
        return nanopubLabel;
×
1013
    }
1014

1015
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
1016
        if (confirmPageClass == null) return null;
×
1017
        try {
1018
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
1019
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
1020
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
1021
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
1022
        }
1023
        return null;
×
1024
    }
1025

1026
    /**
1027
     * Returns a hint whether the form is stateless or not.
1028
     *
1029
     * @return false if the form is stateful, true if it is stateless.
1030
     */
1031
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
1032
    // if the user browses other pages in parallel:
1033
    protected boolean getStatelessHint() {
1034
        return false;
×
1035
    }
1036

1037
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc