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

knowledgepixels / nanodash / 24880477649

24 Apr 2026 08:39AM UTC coverage: 18.287% (+0.8%) from 17.496%
24880477649

push

github

web-flow
Merge pull request #453 from knowledgepixels/add-root-nanopub-placeholder

feat: support RootNanopubPlaceholder in templates

956 of 6218 branches covered (15.37%)

Branch coverage included in aggregate %.

2251 of 11319 relevant lines covered (19.89%)

2.76 hits per line

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

0.43
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.IndividualAgent;
5
import com.knowledgepixels.nanodash.domain.User;
6
import com.knowledgepixels.nanodash.page.*;
7
import com.knowledgepixels.nanodash.repository.MaintainedResourceRepository;
8
import com.knowledgepixels.nanodash.repository.SpaceRepository;
9
import com.knowledgepixels.nanodash.template.*;
10
import org.apache.commons.lang3.Strings;
11
import org.apache.wicket.Component;
12
import org.apache.wicket.RestartResponseException;
13
import org.apache.wicket.ajax.AjaxEventBehavior;
14
import org.apache.wicket.ajax.AjaxRequestTarget;
15
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
16
import org.apache.wicket.feedback.FeedbackMessage;
17
import org.apache.wicket.markup.html.WebMarkupContainer;
18
import org.apache.wicket.markup.html.WebPage;
19
import org.apache.wicket.markup.html.basic.Label;
20
import org.apache.wicket.markup.html.form.Button;
21
import org.apache.wicket.markup.html.form.CheckBox;
22
import org.apache.wicket.markup.html.form.Form;
23
import org.apache.wicket.markup.html.form.FormComponent;
24
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
25
import org.apache.wicket.markup.html.list.ListItem;
26
import org.apache.wicket.markup.html.list.ListView;
27
import org.apache.wicket.markup.html.panel.FeedbackPanel;
28
import org.apache.wicket.markup.html.panel.Panel;
29
import org.apache.wicket.markup.repeater.Item;
30
import org.apache.wicket.markup.repeater.data.DataView;
31
import org.apache.wicket.markup.repeater.data.ListDataProvider;
32
import org.apache.wicket.model.IModel;
33
import org.apache.wicket.model.Model;
34
import org.apache.wicket.request.mapper.parameter.PageParameters;
35
import org.eclipse.rdf4j.model.IRI;
36
import org.eclipse.rdf4j.model.Literal;
37
import org.eclipse.rdf4j.model.Statement;
38
import org.eclipse.rdf4j.model.ValueFactory;
39
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
40
import org.eclipse.rdf4j.model.vocabulary.FOAF;
41
import org.eclipse.rdf4j.model.vocabulary.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

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

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

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

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

169
        final TemplateData td = TemplateData.get();
×
170

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

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

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

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

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

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

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

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

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

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

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

401
        });
402
        add(new DataView<Statement>("unused-prstatements", new ListDataProvider<Statement>(unusedPrStatementList)) {
×
403

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

409
        });
410
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
411

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

417
        });
418

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

426
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
427
        consentCheck.add(new InvalidityHighlighting());
×
428

429
        form = new Form<Void>("form") {
×
430

431
            @Override
432
            protected void onConfigure() {
433
                super.onConfigure();
×
434
                form.getFeedbackMessages().clear();
×
435
//                                formComponents.clear();
436
            }
×
437

438
            protected void onSubmit() {
439
                if (!Boolean.TRUE.equals(consentCheck.getModelObject())) {
×
440
                    feedbackPanel.error("You need to check the checkbox that you understand the consequences.");
×
441
                    return;
×
442
                }
443
                logger.info("Publish form submitted");
×
444
                Nanopub signedNp;
445
                try {
446
                    Nanopub np = createNanopub();
×
447
                    logger.info("Nanopublication created: {}", np.getUri());
×
448
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
449
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
450
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
451
                    String npUrl = PublishNanopub.publish(signedNp, Utils.getMainRegistryUrl());
×
452
                    logger.info("Nanopublication published: {}", npUrl);
×
453
                    Utils.cacheNanopub(signedNp);
×
454
                } catch (Exception ex) {
×
455
                    signedNp = null;
×
456
                    logger.error("Nanopublication publishing failed: {}", ex.getMessage());
×
457
                    String message = ex.getClass().getName();
×
458
                    if (ex.getMessage() != null) {
×
459
                        message = ex.getMessage();
×
460
                    }
461
                    feedbackPanel.error(message);
×
462
                }
×
463
                if (signedNp != null) {
×
464
                    if (!pageParams.get("refresh-upon-publish").isEmpty()) {
×
465
                        String toRefresh = pageParams.get("refresh-upon-publish").toString();
×
466
                        WicketApplication.get().notifyNanopubPublished(signedNp, toRefresh, 5 * 1000);
×
467
                    }
468
                    String contextId = pageParams.get("context").toString("");
×
469
                    String partId = pageParams.get("part").toString("");
×
470
                    if (!contextId.isEmpty() && pageParams.get("postpub-redirect-url").isEmpty()) {
×
471
                        PageParameters redirectParams = new PageParameters().set("just-published", signedNp.getUri().stringValue());
×
472
                        if (!partId.isEmpty()) {
×
473
                            // User was on a part page (e.g. paper collection); redirect back to the part page
474
                            redirectParams.set("id", partId).set("context", contextId);
×
475
                            throw new RestartResponseException(ResourcePartPage.class, redirectParams);
×
476
                        }
477
                        redirectParams.set("id", contextId);
×
478
                        if (SpaceRepository.get().findById(contextId) != null) {
×
479
                            throw new RestartResponseException(SpacePage.class, redirectParams);
×
480
                        }
481
                        if (MaintainedResourceRepository.get().findById(contextId) != null) {
×
482
                            throw new RestartResponseException(MaintainedResourcePage.class, redirectParams);
×
483
                        }
484
                        if (IndividualAgent.isUser(contextId)) {
×
485
                            throw new RestartResponseException(UserPage.class, redirectParams);
×
486
                        }
487
                    }
488
                    NanodashPage confirmPage = getConfirmPage(signedNp, pageParams);
×
489
                    if (confirmPage != null) {
×
490
                        throw new RestartResponseException(confirmPage);
×
491
                    }
492
                    throw new RestartResponseException(ExplorePage.class,
×
493
                            new PageParameters(pageParams).set("id", signedNp.getUri().stringValue()));
×
494
                }
495
            }
×
496

497
            @Override
498
            protected void onValidate() {
499
                super.onValidate();
×
500
                for (Component fc : assertionContext.getComponents()) {
×
501
                    processFeedback(fc);
×
502
                }
×
503
                for (Component fc : provenanceContext.getComponents()) {
×
504
                    processFeedback(fc);
×
505
                }
×
506
                for (TemplateContext c : pubInfoContexts) {
×
507
                    for (Component fc : c.getComponents()) {
×
508
                        processFeedback(fc);
×
509
                    }
×
510
                }
×
511
            }
×
512

513
            private void processFeedback(Component c) {
514
                if (c instanceof FormComponent) {
×
515
                    ((FormComponent<?>) c).processInput();
×
516
                }
517
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
518
                    form.getFeedbackMessages().add(fm);
×
519
                }
×
520
            }
×
521

522
        };
523
        form.setOutputMarkupId(true);
×
524

525
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
526

527
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
528
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
529
        String description = assertionContext.getTemplate().getLabel();
×
530
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
531

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

534
            protected void populateItem(ListItem<StatementItem> item) {
535
                item.add(item.getModelObject());
×
536
            }
×
537

538
        });
539

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

566
            for (ApiResponseEntry t : td.getProvenanceTemplates()) {
×
567
                String tid = t.get("np");
×
568
                if (handledProvTemplates.containsKey(tid)) continue;
×
569
                provTemplateOptionIds.add(tid);
×
570
                handledProvTemplates.put(tid, true);
×
571
            }
×
572
        } else {
573
            for (String s : pageParams.get("prtemplate-options").toString().split(" ")) {
×
574
                if (handledProvTemplates.containsKey(s)) continue;
×
575
                recommendedProvTemplateOptionIds.add(s);
×
576
                handledProvTemplates.put(s, true);
×
577
            }
578
        }
579

580
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
581

582
            @Override
583
            public String getDisplayValue(String object) {
584
                if (object == null || object.isEmpty()) return "";
×
585
                Template t = td.getTemplate(object);
×
586
                if (t != null) return t.getLabel();
×
587
                return object;
×
588
            }
589

590
            @Override
591
            public String getIdValue(String object) {
592
                return object;
×
593
            }
594

595
            // Getting strange errors with Tomcat if this method is not overridden:
596
            @Override
597
            public void detach() {
598
            }
×
599

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

633
            @Override
634
            public Collection<String> toChoices(Collection<String> ids) {
635
                return ids;
×
636
            }
637

638
        };
639
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
640
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
641
        prTemplateChoice.setRequired(true);
×
642
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
643
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
644

645
            @Override
646
            protected void onUpdate(AjaxRequestTarget target) {
647
                String o = prTemplateModel.getObject();
×
648
                if (o.startsWith("——")) {
×
649
                    o = provenanceContext.getTemplate().getId();
×
650
                    prTemplateModel.setObject(o);
×
651
                }
652
                provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateModel.getObject(), "pr-statement", targetNamespace);
×
653
                provenanceContext.initStatements();
×
654
                refreshProvenance(target);
×
655
                provenanceContext.finalizeStatements();
×
656
            }
×
657

658
        });
659
        form.add(prTemplateChoice);
×
660
        refreshProvenance(null);
×
661

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

680
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
681
            String tid = entry.get("np");
×
682
            if (handledPiTemplates.containsKey(tid)) continue;
×
683
            piTemplateOptionIds.add(tid);
×
684
            handledPiTemplates.put(tid, true);
×
685
        }
×
686

687
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
688

689
            @Override
690
            public String getDisplayValue(String object) {
691
                if (object == null || object.isEmpty()) return "";
×
692
                Template t = td.getTemplate(object);
×
693
                if (t != null) return t.getLabel();
×
694
                return object;
×
695
            }
696

697
            @Override
698
            public String getIdValue(String object) {
699
                return object;
×
700
            }
701

702
            // Getting strange errors with Tomcat if this method is not overridden:
703
            @Override
704
            public void detach() {
705
            }
×
706

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

747
            @Override
748
            public Collection<String> toChoices(Collection<String> ids) {
749
                return ids;
×
750
            }
751

752
        };
753
        final IModel<String> newPiTemplateModel = Model.of();
×
754
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
755
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
756
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
757
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
758

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

775
        });
776
        form.add(piTemplateChoice);
×
777
        refreshPubInfo(null);
×
778

779
        form.add(consentCheck);
×
780

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

805
        add(form);
×
806

807
        feedbackPanel = new FeedbackPanel("feedback");
×
808
        feedbackPanel.setOutputMarkupId(true);
×
809
        add(feedbackPanel);
×
810
    }
×
811

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

822
            protected void populateItem(ListItem<StatementItem> item) {
823
                item.add(item.getModelObject());
×
824
            }
×
825

826
        };
827
        list.setOutputMarkupId(true);
×
828
        form.add(list);
×
829
    }
×
830

831
    private void refreshPubInfo(AjaxRequestTarget target) {
832
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
833

834
            protected void populateItem(ListItem<TemplateContext> item) {
835
                final TemplateContext pic = item.getModelObject();
×
836
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
837
                item.add(new BookmarkablePageLink<Void>("pitemplatelink", ExplorePage.class, new PageParameters().set("id", pic.getTemplate().getId())));
×
838
                Label remove = new Label("piremove", "×");
×
839
                item.add(remove);
×
840
                remove.add(new AjaxEventBehavior("click") {
×
841

842
                    @Override
843
                    protected void onEvent(AjaxRequestTarget target) {
844
                        pubInfoContexts.remove(pic);
×
845
                        target.add(PublishForm.this);
×
846
                        target.appendJavaScript("updateElements();");
×
847
                    }
×
848

849
                });
850
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
851
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
852

853
                    protected void populateItem(ListItem<StatementItem> item) {
854
                        item.add(item.getModelObject());
×
855
                    }
×
856

857
                });
858
            }
×
859

860
        };
861
        list.setOutputMarkupId(true);
×
862
        if (target == null) {
×
863
            form.add(list);
×
864
        } else {
865
            form.remove("pis");
×
866
            form.add(list);
×
867
            target.add(form);
×
868
            target.appendJavaScript("updateElements();");
×
869
        }
870
    }
×
871

872
    private TemplateContext createPubInfoContext(String piTemplateId) {
873
        TemplateContext c;
874
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
875
            c = pubInfoContextMap.get(piTemplateId);
×
876
        } else {
877
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
878
            pubInfoContextMap.put(piTemplateId, c);
×
879
            pubInfoContexts.add(c);
×
880
        }
881
        return c;
×
882
    }
883

884
    private synchronized Nanopub createNanopub() throws MalformedNanopubException, NanopubAlreadyFinalizedException {
885
        assertionContext.getIntroducedIris().clear();
×
886
        NanopubCreator npCreator = new NanopubCreator(targetNamespace);
×
887
        npCreator.setAssertionUri(vf.createIRI(targetNamespace + "assertion"));
×
888
        assertionContext.propagateStatements(npCreator);
×
889
        provenanceContext.propagateStatements(npCreator);
×
890
        for (TemplateContext c : pubInfoContexts) {
×
891
            c.propagateStatements(npCreator);
×
892
        }
×
893
        for (IRI introducedIri : assertionContext.getIntroducedIris()) {
×
894
            npCreator.addPubinfoStatement(NPX.INTRODUCES, introducedIri);
×
895
        }
×
896
        for (IRI embeddedIri : assertionContext.getEmbeddedIris()) {
×
897
            npCreator.addPubinfoStatement(NPX.EMBEDS, embeddedIri);
×
898
        }
×
899
        npCreator.addNamespace("this", targetNamespace);
×
900
        npCreator.addNamespace("sub", targetNamespace + "/");
×
901
        npCreator.addTimestampNow();
×
902
        IRI templateUri = assertionContext.getTemplate().getNanopub().getUri();
×
903
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_TEMPLATE, templateUri);
×
904
        IRI prTemplateUri = provenanceContext.getTemplate().getNanopub().getUri();
×
905
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PROVENANCE_TEMPLATE, prTemplateUri);
×
906
        for (TemplateContext c : pubInfoContexts) {
×
907
            IRI piTemplateUri = c.getTemplate().getNanopub().getUri();
×
908
            npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PUBINFO_TEMPLATE, piTemplateUri);
×
909
        }
×
910
        String nanopubLabel = getNanopubLabel(npCreator);
×
911
        if (nanopubLabel != null) {
×
912
            npCreator.addPubinfoStatement(RDFS.LABEL, vf.createLiteral(nanopubLabel));
×
913
        }
914
        for (IRI type : assertionContext.getTemplate().getTargetNanopubTypes()) {
×
915
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, type);
×
916
        }
×
917
        IRI userIri = NanodashSession.get().getUserIri();
×
918
        if (User.getName(userIri) != null) {
×
919
            npCreator.addPubinfoStatement(userIri, FOAF.NAME, vf.createLiteral(User.getName(userIri)));
×
920
            npCreator.addNamespace("foaf", FOAF.NAMESPACE);
×
921
        }
922
        String websiteUrl = NanodashPreferences.get().getWebsiteUrl();
×
923
        if (websiteUrl != null) {
×
924
            npCreator.addPubinfoStatement(NPX.WAS_CREATED_AT, vf.createIRI(websiteUrl));
×
925
        }
926
        return npCreator.finalizeNanopub();
×
927
    }
928

929
    private String getNanopubLabel(NanopubCreator npCreator) {
930
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
931

932
        Map<IRI, String> labelMap = new HashMap<>();
×
933
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
934
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
935
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
936
            }
937
        }
×
938

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

986
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
987
        try {
988
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
989
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
990
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
991
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
992
        }
993
        return null;
×
994
    }
995

996
    /**
997
     * Returns a hint whether the form is stateless or not.
998
     *
999
     * @return false if the form is stateful, true if it is stateless.
1000
     */
1001
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
1002
    // if the user browses other pages in parallel:
1003
    protected boolean getStatelessHint() {
1004
        return false;
×
1005
    }
1006

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