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

knowledgepixels / nanodash / 28789064412

06 Jul 2026 11:44AM UTC coverage: 28.51% (+0.008%) from 28.502%
28789064412

push

github

web-flow
Merge pull request #535 from knowledgepixels/feat/navigation-context

feat: persistent navigation context with back-link and post-publish forwarding

1811 of 7177 branches covered (25.23%)

Branch coverage included in aggregate %.

3710 of 12188 relevant lines covered (30.44%)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

430
        });
431

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

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

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

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

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

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

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

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

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

533
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
534
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
535
        String description = assertionContext.getTemplate().getLabel();
×
536
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
537

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

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

544
        });
545

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

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

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

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

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

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

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

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

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

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

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

668
        final Map<String, Boolean> handledPiTemplates = new HashMap<>();
×
669
        final List<String> recommendedPiTemplateOptionIds = new ArrayList<>();
×
670
        final List<String> piTemplateOptionIds = new ArrayList<>();
×
671
        // TODO Make this dynamic and consider updated templates:
672
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAXflINqt3smqxV5Aq7E9lzje4uLdkKIOefa6Bp8oJ8CY");
×
673
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ");
×
674
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RA16U9Wo30ObhrK1NzH7EsmVRiRtvEuEA_Dfc-u8WkUCA");
×
675
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAdyqI6k07V5nAS82C6hvIDtNWk179EIV4DV-sLbOFKg4");
×
676
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RAjvEpLZUE7rMoa8q6mWSsN6utJDp-5FmgO47YGsbgw3w");
×
677
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAxuGRKID6yNg63V5Mf0ot2NjncOnodh-mkN3qT_1txGI");
×
678
        for (TemplateContext c : pubInfoContexts) {
×
679
            String s = c.getTemplate().getId();
×
680
            handledPiTemplates.put(s, true);
×
681
        }
×
682
        for (String s : recommendedPiTemplateOptionIds) {
×
683
            handledPiTemplates.put(s, true);
×
684
        }
×
685

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

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

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

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

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

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

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

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

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

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

785
        form.add(consentCheck);
×
786

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

811
        add(form);
×
812

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

818
    private void refreshProvenance(AjaxRequestTarget target) {
819
        if (target != null) {
×
820
            form.remove("prtemplatelink");
×
821
            form.remove("pr-statements");
×
822
            target.add(form);
×
823
            target.appendJavaScript("updateElements();");
×
824
        }
825
        form.add(new BookmarkablePageLink<Void>("prtemplatelink", ExplorePage.class, new PageParameters().set("id", provenanceContext.getTemplate().getId())));
×
826
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
827

828
            protected void populateItem(ListItem<StatementItem> item) {
829
                item.add(item.getModelObject());
×
830
            }
×
831

832
        };
833
        list.setOutputMarkupId(true);
×
834
        form.add(list);
×
835
    }
×
836

837
    private void refreshPubInfo(AjaxRequestTarget target) {
838
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
839

840
            protected void populateItem(ListItem<TemplateContext> item) {
841
                final TemplateContext pic = item.getModelObject();
×
842
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
843
                item.add(new BookmarkablePageLink<Void>("pitemplatelink", ExplorePage.class, new PageParameters().set("id", pic.getTemplate().getId())));
×
844
                Label remove = new Label("piremove", "×");
×
845
                item.add(remove);
×
846
                remove.add(new AjaxEventBehavior("click") {
×
847

848
                    @Override
849
                    protected void onEvent(AjaxRequestTarget target) {
850
                        pubInfoContexts.remove(pic);
×
851
                        target.add(PublishForm.this);
×
852
                        target.appendJavaScript("updateElements();");
×
853
                    }
×
854

855
                });
856
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
857
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
858

859
                    protected void populateItem(ListItem<StatementItem> item) {
860
                        item.add(item.getModelObject());
×
861
                    }
×
862

863
                });
864
            }
×
865

866
        };
867
        list.setOutputMarkupId(true);
×
868
        if (target == null) {
×
869
            form.add(list);
×
870
        } else {
871
            form.remove("pis");
×
872
            form.add(list);
×
873
            target.add(form);
×
874
            target.appendJavaScript("updateElements();");
×
875
        }
876
    }
×
877

878
    private TemplateContext createPubInfoContext(String piTemplateId) {
879
        TemplateContext c;
880
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
881
            c = pubInfoContextMap.get(piTemplateId);
×
882
        } else {
883
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
884
            pubInfoContextMap.put(piTemplateId, c);
×
885
            pubInfoContexts.add(c);
×
886
        }
887
        return c;
×
888
    }
889

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

945
    private String getNanopubLabel(NanopubCreator npCreator) {
946
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
947

948
        Map<IRI, String> labelMap = new HashMap<>();
×
949
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
950
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
951
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
952
            }
953
        }
×
954

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

1002
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
1003
        if (confirmPageClass == null) return null;
×
1004
        try {
1005
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
1006
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
1007
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
1008
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
1009
        }
1010
        return null;
×
1011
    }
1012

1013
    /**
1014
     * Returns a hint whether the form is stateless or not.
1015
     *
1016
     * @return false if the form is stateful, true if it is stateless.
1017
     */
1018
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
1019
    // if the user browses other pages in parallel:
1020
    protected boolean getStatelessHint() {
1021
        return false;
×
1022
    }
1023

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