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

knowledgepixels / nanodash / 28792900518

06 Jul 2026 12:52PM UTC coverage: 28.504% (-0.006%) from 28.51%
28792900518

Pull #536

github

web-flow
Merge fd800ea3b into afb8fc1ab
Pull Request #536: feat: replace template-form '^' source links with dropdown menus

1811 of 7177 branches covered (25.23%)

Branch coverage included in aggregate %.

3710 of 12192 relevant lines covered (30.43%)

4.52 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 = QueryApiAccess.getLatestVersionId(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 = QueryApiAccess.getLatestVersionId(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 = QueryApiAccess.getLatestVersionId(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
            String s = c.getTemplate().getId();
×
681
            handledPiTemplates.put(s, true);
×
682
        }
×
683
        for (String s : recommendedPiTemplateOptionIds) {
×
684
            handledPiTemplates.put(s, true);
×
685
        }
×
686

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

694
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
695

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

704
            @Override
705
            public String getIdValue(String object) {
706
                return object;
×
707
            }
708

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

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

754
            @Override
755
            public Collection<String> toChoices(Collection<String> ids) {
756
                return ids;
×
757
            }
758

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

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

782
        });
783
        form.add(piTemplateChoice);
×
784
        refreshPubInfo(null);
×
785

786
        form.add(consentCheck);
×
787

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

812
        add(form);
×
813

814
        feedbackPanel = new FeedbackPanel("feedback");
×
815
        feedbackPanel.setOutputMarkupId(true);
×
816
        add(feedbackPanel);
×
817
    }
×
818

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

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

836
            protected void populateItem(ListItem<StatementItem> item) {
837
                item.add(item.getModelObject());
×
838
            }
×
839

840
        };
841
        list.setOutputMarkupId(true);
×
842
        form.add(list);
×
843
    }
×
844

845
    private void refreshPubInfo(AjaxRequestTarget target) {
846
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
847

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

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

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

867
                    protected void populateItem(ListItem<StatementItem> item) {
868
                        item.add(item.getModelObject());
×
869
                    }
×
870

871
                });
872
            }
×
873

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

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

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

953
    private String getNanopubLabel(NanopubCreator npCreator) {
954
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
955

956
        Map<IRI, String> labelMap = new HashMap<>();
×
957
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
958
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
959
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
960
            }
961
        }
×
962

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

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

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

1032
}
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