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

knowledgepixels / nanodash / 28569727260

02 Jul 2026 06:17AM UTC coverage: 28.06% (+0.03%) from 28.026%
28569727260

push

github

web-flow
Merge pull request #526 from knowledgepixels/feat/template-role-direction-pins

feat: emit role-direction pins in pubinfo from templates

1734 of 7047 branches covered (24.61%)

Branch coverage included in aggregate %.

3621 of 12037 relevant lines covered (30.08%)

4.45 hits per line

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

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

64
import java.lang.reflect.InvocationTargetException;
65
import java.util.*;
66

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

72
    private static final Logger logger = LoggerFactory.getLogger(PublishForm.class);
×
73

74
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
75

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

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

84
    /**
85
     * Fill modes for the nanopublication to be created.
86
     */
87
    public enum FillMode {
9✔
88
        /**
89
         * Use fill mode
90
         */
91
        USE,
18✔
92
        /**
93
         * Supersede fill mode
94
         */
95
        SUPERSEDE,
18✔
96
        /**
97
         * Derive fill mode
98
         */
99
        DERIVE
18✔
100
    }
101

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

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

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

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

172
        final TemplateData td = TemplateData.get();
×
173

174
        // TODO Properly integrate this namespace feature:
175
        String templateId = pageParams.get("template").toString();
×
176
        if (td.getTemplate(templateId).getTargetNamespace() != null) {
×
177
            targetNamespace = td.getTemplate(templateId).getTargetNamespace();
×
178
        }
179
        if (!pageParams.get("target-namespace").isNull()) {
×
180
            targetNamespace = pageParams.get("target-namespace").toString();
×
181
        }
182
        if (targetNamespace == null) {
×
183
            targetNamespace = Template.DEFAULT_TARGET_NAMESPACE;
×
184
        }
185
        String targetNamespaceLabel = targetNamespace + "...";
×
186
        targetNamespace = targetNamespace + "~~~ARTIFACTCODE~~~/";
×
187

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

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

300
        final Nanopub improveNp;
301
        if (!pageParams.get("improve").isNull()) {
×
302
            improveNp = Utils.getNanopub(pageParams.get("improve").toString());
×
303
        } else {
304
            improveNp = null;
×
305
        }
306

307
        // Propagate fill source (supersede/derive/improve) so contexts can resolve
308
        // the `local:nanopub`/`local:assertion` sentinels to the fill nanopub's URIs.
309
        Nanopub fillSource = fillNp != null ? fillNp : improveNp;
×
310
        if (fillSource != null) {
×
311
            assertionContext.setFillSource(fillSource);
×
312
            provenanceContext.setFillSource(fillSource);
×
313
            for (TemplateContext c : pubInfoContexts) {
×
314
                c.setFillSource(fillSource);
×
315
            }
×
316
        }
317

318
        // Init statements only now, in order to pick up parameter values:
319
        assertionContext.initStatements();
×
320
        provenanceContext.initStatements();
×
321
        for (TemplateContext c : pubInfoContexts) {
×
322
            c.initStatements();
×
323
        }
×
324

325
        String latestAssertionId = QueryApiAccess.getLatestVersionId(assertionContext.getTemplateId());
×
326
        if (!assertionContext.getTemplateId().equals(latestAssertionId)) {
×
327
            add(new Label("newversion", "There is a new version of this assertion template:"));
×
328
            PageParameters params = new PageParameters(pageParams);
×
329
            params.set("template", latestAssertionId);
×
330
            add(new BookmarkablePageLink<Void>("newversionlink", publishPageClass, params));
×
331
            if ("latest".equals(pageParams.get("template-version").toString())) {
×
332
                throw new RestartResponseException(publishPageClass, params);
×
333
            }
334
        } else {
×
335
            add(new Label("newversion", "").setVisible(false));
×
336
            add(new Label("newversionlink", "").setVisible(false));
×
337
        }
338

339
        final List<Statement> unusedStatementList = new ArrayList<>();
×
340
        final List<Statement> unusedPrStatementList = new ArrayList<>();
×
341
        final List<Statement> unusedPiStatementList = new ArrayList<>();
×
342
        if (fillNp != null) {
×
343
            ValueFiller filler = new ValueFiller(fillNp, ContextType.ASSERTION, true, fillMode);
×
344
            filler.fill(assertionContext);
×
345
            unusedStatementList.addAll(filler.getUnusedStatements());
×
346

347
            if (!fillOnlyAssertion) {
×
348
                ValueFiller prFiller = new ValueFiller(fillNp, ContextType.PROVENANCE, true);
×
349
                prFiller.fill(provenanceContext);
×
350
                unusedPrStatementList.addAll(prFiller.getUnusedStatements());
×
351

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

399
            @Override
400
            protected void populateItem(Item<Statement> item) {
401
                item.add(new TripleItem("unused-statement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
402
            }
×
403

404
        });
405
        add(new DataView<Statement>("unused-prstatements", new ListDataProvider<Statement>(unusedPrStatementList)) {
×
406

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

412
        });
413
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
414

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

420
        });
421

422
        // Finalize statements, which picks up parameter values in repetitions:
423
        assertionContext.finalizeStatements();
×
424
        provenanceContext.finalizeStatements();
×
425
        for (TemplateContext c : pubInfoContexts) {
×
426
            c.finalizeStatements();
×
427
        }
×
428

429
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
430
        consentCheck.add(new InvalidityHighlighting());
×
431

432
        form = new Form<Void>("form") {
×
433

434
            @Override
435
            protected void onConfigure() {
436
                super.onConfigure();
×
437
                form.getFeedbackMessages().clear();
×
438
//                                formComponents.clear();
439
            }
×
440

441
            protected void onSubmit() {
442
                if (!Boolean.TRUE.equals(consentCheck.getModelObject())) {
×
443
                    feedbackPanel.error("You need to check the checkbox that you understand the consequences.");
×
444
                    return;
×
445
                }
446
                logger.info("Publish form submitted");
×
447
                Nanopub signedNp;
448
                try {
449
                    Nanopub np = createNanopub();
×
450
                    logger.info("Nanopublication created: {}", np.getUri());
×
451
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
452
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
453
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
454
                    String npUrl = PublishNanopub.publish(signedNp);
×
455
                    logger.info("Nanopublication published: {}", npUrl);
×
456
                    Utils.cacheNanopub(signedNp);
×
457
                } catch (Exception ex) {
×
458
                    signedNp = null;
×
459
                    logger.error("Nanopublication publishing failed: {}", ex.getMessage());
×
460
                    String message = ex.getClass().getName();
×
461
                    if (ex.getMessage() != null) {
×
462
                        message = ex.getMessage();
×
463
                    }
464
                    feedbackPanel.error(message);
×
465
                }
×
466
                if (signedNp != null) {
×
467
                    String toRefresh = pageParams.get("refresh-upon-publish").toString("");
×
468
                    if (!toRefresh.isEmpty()) {
×
469
                        WicketApplication.get().notifyNanopubPublished(signedNp, toRefresh, 5 * 1000);
×
470
                    }
471
                    String contextId = pageParams.get("context").toString("");
×
472
                    // Broaden the refresh: also force-refresh the context resource's own
473
                    // data (e.g. a space's roles/members) so the page we redirect to —
474
                    // typically its Content tab — reflects the just-published change, not
475
                    // only the specific view query that was acted on.
476
                    if (!contextId.isEmpty() && !contextId.equals(toRefresh)
×
477
                            && AbstractResourceWithProfile.isResourceWithProfile(contextId)) {
×
478
                        WicketApplication.get().notifyNanopubPublished(signedNp, contextId, 5 * 1000);
×
479
                    }
480
                    String partId = pageParams.get("part").toString("");
×
481
                    if (!contextId.isEmpty() && pageParams.get("postpub-redirect-url").isEmpty()) {
×
482
                        PageParameters redirectParams = new PageParameters().set("just-published", signedNp.getUri().stringValue());
×
483
                        if (!partId.isEmpty()) {
×
484
                            // User was on a part page (e.g. paper collection); redirect back to the part page
485
                            redirectParams.set("id", partId).set("context", contextId);
×
486
                            throw new RestartResponseException(ResourcePartPage.class, redirectParams);
×
487
                        }
488
                        redirectParams.set("id", contextId);
×
489
                        // Return to the tab the action asked for (e.g. "about" for a
490
                        // space's About-tab role actions); default is the Content tab.
491
                        String postpubTab = pageParams.get("postpub-tab").toString("");
×
492
                        if (!postpubTab.isEmpty()) redirectParams.set("tab", postpubTab);
×
493
                        if (SpaceRepository.get().findById(contextId) != null) {
×
494
                            throw new RestartResponseException(SpacePage.class, redirectParams);
×
495
                        }
496
                        if (MaintainedResourceRepository.get().findById(contextId) != null) {
×
497
                            throw new RestartResponseException(MaintainedResourcePage.class, redirectParams);
×
498
                        }
499
                        if (IndividualAgent.isUser(contextId)) {
×
500
                            throw new RestartResponseException(UserPage.class, redirectParams);
×
501
                        }
502
                    }
503
                    NanodashPage confirmPage = getConfirmPage(signedNp, pageParams);
×
504
                    if (confirmPage != null) {
×
505
                        throw new RestartResponseException(confirmPage);
×
506
                    }
507
                    throw new RestartResponseException(ExplorePage.class,
×
508
                            new PageParameters(pageParams).set("id", signedNp.getUri().stringValue()));
×
509
                }
510
            }
×
511

512
            @Override
513
            protected void onValidate() {
514
                super.onValidate();
×
515
                for (Component fc : assertionContext.getComponents()) {
×
516
                    processFeedback(fc);
×
517
                }
×
518
                for (Component fc : provenanceContext.getComponents()) {
×
519
                    processFeedback(fc);
×
520
                }
×
521
                for (TemplateContext c : pubInfoContexts) {
×
522
                    for (Component fc : c.getComponents()) {
×
523
                        processFeedback(fc);
×
524
                    }
×
525
                }
×
526
            }
×
527

528
            private void processFeedback(Component c) {
529
                if (c instanceof FormComponent) {
×
530
                    ((FormComponent<?>) c).processInput();
×
531
                }
532
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
533
                    form.getFeedbackMessages().add(fm);
×
534
                }
×
535
            }
×
536

537
        };
538
        form.setOutputMarkupId(true);
×
539

540
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
541

542
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
543
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
544
        String description = assertionContext.getTemplate().getLabel();
×
545
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
546

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

549
            protected void populateItem(ListItem<StatementItem> item) {
550
                item.add(item.getModelObject());
×
551
            }
×
552

553
        });
554

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

581
            for (ApiResponseEntry t : td.getProvenanceTemplates()) {
×
582
                String tid = t.get("np");
×
583
                if (handledProvTemplates.containsKey(tid)) continue;
×
584
                provTemplateOptionIds.add(tid);
×
585
                handledProvTemplates.put(tid, true);
×
586
            }
×
587
        } else {
588
            for (String s : pageParams.get("prtemplate-options").toString().split(" ")) {
×
589
                if (handledProvTemplates.containsKey(s)) continue;
×
590
                recommendedProvTemplateOptionIds.add(s);
×
591
                handledProvTemplates.put(s, true);
×
592
            }
593
        }
594

595
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
596

597
            @Override
598
            public String getDisplayValue(String object) {
599
                if (object == null || object.isEmpty()) return "";
×
600
                Template t = td.getTemplate(object);
×
601
                if (t != null) return t.getLabel();
×
602
                return object;
×
603
            }
604

605
            @Override
606
            public String getIdValue(String object) {
607
                return object;
×
608
            }
609

610
            // Getting strange errors with Tomcat if this method is not overridden:
611
            @Override
612
            public void detach() {
613
            }
×
614

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

648
            @Override
649
            public Collection<String> toChoices(Collection<String> ids) {
650
                return ids;
×
651
            }
652

653
        };
654
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
655
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
656
        prTemplateChoice.setRequired(true);
×
657
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
658
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
659

660
            @Override
661
            protected void onUpdate(AjaxRequestTarget target) {
662
                String o = prTemplateModel.getObject();
×
663
                if (o.startsWith("——")) {
×
664
                    o = provenanceContext.getTemplate().getId();
×
665
                    prTemplateModel.setObject(o);
×
666
                }
667
                provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateModel.getObject(), "pr-statement", targetNamespace);
×
668
                provenanceContext.initStatements();
×
669
                refreshProvenance(target);
×
670
                provenanceContext.finalizeStatements();
×
671
            }
×
672

673
        });
674
        form.add(prTemplateChoice);
×
675
        refreshProvenance(null);
×
676

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

695
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
696
            String tid = entry.get("np");
×
697
            if (handledPiTemplates.containsKey(tid)) continue;
×
698
            piTemplateOptionIds.add(tid);
×
699
            handledPiTemplates.put(tid, true);
×
700
        }
×
701

702
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
703

704
            @Override
705
            public String getDisplayValue(String object) {
706
                if (object == null || object.isEmpty()) return "";
×
707
                Template t = td.getTemplate(object);
×
708
                if (t != null) return t.getLabel();
×
709
                return object;
×
710
            }
711

712
            @Override
713
            public String getIdValue(String object) {
714
                return object;
×
715
            }
716

717
            // Getting strange errors with Tomcat if this method is not overridden:
718
            @Override
719
            public void detach() {
720
            }
×
721

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

762
            @Override
763
            public Collection<String> toChoices(Collection<String> ids) {
764
                return ids;
×
765
            }
766

767
        };
768
        final IModel<String> newPiTemplateModel = Model.of();
×
769
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
770
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
771
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
772
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
773

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

790
        });
791
        form.add(piTemplateChoice);
×
792
        refreshPubInfo(null);
×
793

794
        form.add(consentCheck);
×
795

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

820
        add(form);
×
821

822
        feedbackPanel = new FeedbackPanel("feedback");
×
823
        feedbackPanel.setOutputMarkupId(true);
×
824
        add(feedbackPanel);
×
825
    }
×
826

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

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

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

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

849
            protected void populateItem(ListItem<TemplateContext> item) {
850
                final TemplateContext pic = item.getModelObject();
×
851
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
852
                item.add(new BookmarkablePageLink<Void>("pitemplatelink", ExplorePage.class, new PageParameters().set("id", pic.getTemplate().getId())));
×
853
                Label remove = new Label("piremove", "×");
×
854
                item.add(remove);
×
855
                remove.add(new AjaxEventBehavior("click") {
×
856

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

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

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

872
                });
873
            }
×
874

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

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

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

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

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

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

1011
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
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