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

knowledgepixels / nanodash / 22618039211

03 Mar 2026 10:05AM UTC coverage: 16.058% (+0.2%) from 15.884%
22618039211

Pull #365

github

web-flow
Merge 1e7e700f0 into a8c4b4a77
Pull Request #365: Refactor of `ResourceWithProfile` and related classes

699 of 5287 branches covered (13.22%)

Branch coverage included in aggregate %.

1721 of 9783 relevant lines covered (17.59%)

2.41 hits per line

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

0.0
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
    private static String creatorPubinfoTemplateId = "https://w3id.org/np/RAukAcWHRDlkqxk7H2XNSegc1WnHI569INvNr-xdptDGI";
×
74
    private static String licensePubinfoTempalteId = "https://w3id.org/np/RA0J4vUn_dekg-U1kK3AOEt02p9mT2WO03uGxLDec1jLw";
×
75
    private static String defaultProvTemplateId = "https://w3id.org/np/RA7lSq6MuK_TIC6JMSHvLtee3lpLoZDOqLJCLXevnrPoU";
×
76
    private static String supersedesPubinfoTemplateId = "https://w3id.org/np/RAoTD7udB2KtUuOuAe74tJi1t3VzK0DyWS7rYVAq1GRvw";
×
77
    private static String derivesFromPubinfoTemplateId = "https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ";
×
78

79
    private static String[] fixedPubInfoTemplates = new String[]{creatorPubinfoTemplateId, licensePubinfoTempalteId};
×
80

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

99
    protected Form<?> form;
100
    protected FeedbackPanel feedbackPanel;
101
    private final TemplateContext assertionContext;
102
    private TemplateContext provenanceContext;
103
    private List<TemplateContext> pubInfoContexts = new ArrayList<>();
×
104
    private Map<String, TemplateContext> pubInfoContextMap = new HashMap<>();
×
105
    private List<TemplateContext> requiredPubInfoContexts = new ArrayList<>();
×
106
    private String targetNamespace;
107
    private 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 = defaultProvTemplateId;
×
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
        }
211
        if (fillMode == FillMode.SUPERSEDE) {
×
212
            TemplateContext c = new TemplateContext(ContextType.PUBINFO, supersedesPubinfoTemplateId, "pi-statement", targetNamespace);
×
213
            pubInfoContexts.add(c);
×
214
            pubInfoContextMap.put(supersedesPubinfoTemplateId, c);
×
215
            //requiredPubInfoContexts.add(c);
216
            c.setParam("np", fillNp.getUri().stringValue());
×
217
        } else if (fillMode == FillMode.DERIVE) {
×
218
            TemplateContext c = new TemplateContext(ContextType.PUBINFO, derivesFromPubinfoTemplateId, "pi-statement", targetNamespace);
×
219
            pubInfoContexts.add(c);
×
220
            pubInfoContextMap.put(derivesFromPubinfoTemplateId, c);
×
221
            c.setParam("np", fillNp.getUri().stringValue());
×
222
        }
223
        for (IRI r : assertionContext.getTemplate().getRequiredPubinfoElements()) {
×
224
            String latestId = QueryApiAccess.getLatestVersionId(r.stringValue());
×
225
            if (pubInfoContextMap.containsKey(r.stringValue()) || pubInfoContextMap.containsKey(latestId)) continue;
×
226
            TemplateContext c = new TemplateContext(ContextType.PUBINFO, r.stringValue(), "pi-statement", targetNamespace);
×
227
            pubInfoContexts.add(c);
×
228
            pubInfoContextMap.put(c.getTemplateId(), c);
×
229
            requiredPubInfoContexts.add(c);
×
230
        }
×
231
        Map<Integer, TemplateContext> piParamIdMap = new HashMap<>();
×
232
        for (String k : pageParams.getNamedKeys()) {
×
233
            if (!k.matches("pitemplate[1-9][0-9]*")) continue;
×
234
            Integer i = Integer.parseInt(k.replaceFirst("^pitemplate([1-9][0-9]*)$", "$1"));
×
235
            String tid = pageParams.get(k).toString();
×
236
            // TODO Allow for automatically using latest template version:
237
            //String piTempalteIdLatest = QueryApiAccess.getLatestVersionId(tid);
238
            TemplateContext c = createPubinfoContext(tid);
×
239
            if (piParamIdMap.containsKey(i)) {
×
240
                // TODO: handle this error better
241
                logger.error("ERROR: pitemplate param identifier assigned multiple times: {}", i);
×
242
            }
243
            piParamIdMap.put(i, c);
×
244
        }
×
245
        if (fillNp != null && !fillOnlyAssertion) {
×
246
            for (IRI piTemplateId : td.getPubinfoTemplateIds(fillNp)) {
×
247
                String piTempalteIdLatest = QueryApiAccess.getLatestVersionId(piTemplateId.stringValue());
×
248
                if (piTempalteIdLatest.equals(supersedesPubinfoTemplateId)) continue;
×
249
                if (!pubInfoContextMap.containsKey(piTempalteIdLatest)) {
×
250
                    // TODO Allow for automatically using latest template version
251
                    createPubinfoContext(piTemplateId.stringValue());
×
252
                }
253
            }
×
254
        }
255
        if (!pageParams.get("values-from-query").isEmpty() && !pageParams.get("values-from-query-mapping").isEmpty()) {
×
256
            String querySpec = pageParams.get("values-from-query").toString();
×
257

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

292
        // Init statements only now, in order to pick up parameter values:
293
        assertionContext.initStatements();
×
294
        provenanceContext.initStatements();
×
295
        for (TemplateContext c : pubInfoContexts) {
×
296
            c.initStatements();
×
297
        }
×
298

299
        String latestAssertionId = QueryApiAccess.getLatestVersionId(assertionContext.getTemplateId());
×
300
        if (!assertionContext.getTemplateId().equals(latestAssertionId)) {
×
301
            add(new Label("newversion", "There is a new version of this assertion template:"));
×
302
            PageParameters params = new PageParameters(pageParams);
×
303
            params.set("template", latestAssertionId).remove("formobj");
×
304
            add(new BookmarkablePageLink<Void>("newversionlink", publishPageClass, params));
×
305
            if ("latest".equals(pageParams.get("template-version").toString())) {
×
306
                throw new RestartResponseException(publishPageClass, params);
×
307
            }
308
        } else {
×
309
            add(new Label("newversion", "").setVisible(false));
×
310
            add(new Label("newversionlink", "").setVisible(false));
×
311
        }
312

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

320
        final List<Statement> unusedStatementList = new ArrayList<>();
×
321
        final List<Statement> unusedPrStatementList = new ArrayList<>();
×
322
        final List<Statement> unusedPiStatementList = new ArrayList<>();
×
323
        if (fillNp != null) {
×
324
            ValueFiller filler = new ValueFiller(fillNp, ContextType.ASSERTION, true, fillMode);
×
325
            filler.fill(assertionContext);
×
326
            unusedStatementList.addAll(filler.getUnusedStatements());
×
327

328
            if (!fillOnlyAssertion) {
×
329
                ValueFiller prFiller = new ValueFiller(fillNp, ContextType.PROVENANCE, true);
×
330
                prFiller.fill(provenanceContext);
×
331
                unusedPrStatementList.addAll(prFiller.getUnusedStatements());
×
332

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

379
            @Override
380
            protected void populateItem(Item<Statement> item) {
381
                item.add(new TripleItem("unused-statement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
382
            }
×
383

384
        });
385
        add(new DataView<Statement>("unused-prstatements", new ListDataProvider<Statement>(unusedPrStatementList)) {
×
386

387
            @Override
388
            protected void populateItem(Item<Statement> item) {
389
                item.add(new TripleItem("unused-prstatement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
390
            }
×
391

392
        });
393
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
394

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

400
        });
401

402
        // Finalize statements, which picks up parameter values in repetitions:
403
        assertionContext.finalizeStatements();
×
404
        provenanceContext.finalizeStatements();
×
405
        for (TemplateContext c : pubInfoContexts) {
×
406
            c.finalizeStatements();
×
407
        }
×
408

409
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
410
        consentCheck.add(new InvalidityHighlighting());
×
411

412
        form = new Form<Void>("form") {
×
413

414
            @Override
415
            protected void onConfigure() {
416
                super.onConfigure();
×
417
                form.getFeedbackMessages().clear();
×
418
//                                formComponents.clear();
419
            }
×
420

421
            protected void onSubmit() {
422
                if (!Boolean.TRUE.equals(consentCheck.getModelObject())) {
×
423
                    feedbackPanel.error("You need to check the checkbox that you understand the consequences.");
×
424
                    return;
×
425
                }
426
                logger.info("Publish form submitted");
×
427
                Nanopub signedNp;
428
                try {
429
                    Nanopub np = createNanopub();
×
430
                    logger.info("Nanopublication created: {}", np.getUri());
×
431
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
432
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
433
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
434
                    String npUrl = PublishNanopub.publish(signedNp);
×
435
                    logger.info("Nanopublication published: {}", npUrl);
×
436
                } catch (Exception ex) {
×
437
                    signedNp = null;
×
438
                    logger.error("Nanopublication publishing failed: {}", ex.getMessage());
×
439
                    String message = ex.getClass().getName();
×
440
                    if (ex.getMessage() != null) {
×
441
                        message = ex.getMessage();
×
442
                    }
443
                    feedbackPanel.error(message);
×
444
                }
×
445
                if (!pageParams.get("refresh-upon-publish").isEmpty()) {
×
446
                    String toRefresh = pageParams.get("refresh-upon-publish").toString();
×
447
                    WicketApplication.get().notifyNanopubPublished(signedNp, toRefresh, 3 * 1000);
×
448
                }
449
                if (signedNp != null) {
×
450
                    String contextId = pageParams.get("context").toString("");
×
451
                    String partId = pageParams.get("part").toString("");
×
452
                    if (!contextId.isEmpty()) {
×
453
                        PageParameters redirectParams = new PageParameters().set("just-published", signedNp.getUri().stringValue());
×
454
                        if (!partId.isEmpty()) {
×
455
                            // User was on a part page (e.g. paper collection); redirect back to the part page
456
                            redirectParams.set("id", partId).set("context", contextId);
×
457
                            throw new RestartResponseException(ResourcePartPage.class, redirectParams);
×
458
                        }
459
                        redirectParams.set("id", contextId);
×
460
                        if (SpaceRepository.get().findById(contextId) != null) {
×
461
                            throw new RestartResponseException(SpacePage.class, redirectParams);
×
462
                        }
463
                        if (MaintainedResourceRepository.get().findById(contextId) != null) {
×
464
                            throw new RestartResponseException(MaintainedResourcePage.class, redirectParams);
×
465
                        }
466
                        if (IndividualAgent.isUser(contextId)) {
×
467
                            throw new RestartResponseException(UserPage.class, redirectParams);
×
468
                        }
469
                    }
470
                    throw new RestartResponseException(getConfirmPage(signedNp, pageParams));
×
471
                }
472
            }
×
473

474
            @Override
475
            protected void onValidate() {
476
                super.onValidate();
×
477
                for (Component fc : assertionContext.getComponents()) {
×
478
                    processFeedback(fc);
×
479
                }
×
480
                for (Component fc : provenanceContext.getComponents()) {
×
481
                    processFeedback(fc);
×
482
                }
×
483
                for (TemplateContext c : pubInfoContexts) {
×
484
                    for (Component fc : c.getComponents()) {
×
485
                        processFeedback(fc);
×
486
                    }
×
487
                }
×
488
            }
×
489

490
            private void processFeedback(Component c) {
491
                if (c instanceof FormComponent) {
×
492
                    ((FormComponent<?>) c).processInput();
×
493
                }
494
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
495
                    form.getFeedbackMessages().add(fm);
×
496
                }
×
497
            }
×
498

499
        };
500
        form.setOutputMarkupId(true);
×
501

502
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
503

504
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
505
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
506
        String description = assertionContext.getTemplate().getLabel();
×
507
        if (description == null) description = "";
×
508
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
509

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

512
            protected void populateItem(ListItem<StatementItem> item) {
513
                item.add(item.getModelObject());
×
514
            }
×
515

516
        });
517

518
        final Map<String, Boolean> handledProvTemplates = new HashMap<>();
×
519
        final String defaultProvTemplateId;
520
        if (assertionContext.getTemplate().getDefaultProvenance() != null) {
×
521
            defaultProvTemplateId = assertionContext.getTemplate().getDefaultProvenance().stringValue();
×
522
            handledProvTemplates.put(defaultProvTemplateId, true);
×
523
        } else {
524
            defaultProvTemplateId = null;
×
525
        }
526
        final List<String> recommendedProvTemplateOptionIds = new ArrayList<>();
×
527
        final List<String> provTemplateOptionIds = new ArrayList<>();
×
528
        if (pageParams.get("prtemplate-options").isNull()) {
×
529
            // TODO Make this dynamic and consider updated templates:
530
            recommendedProvTemplateOptionIds.add("https://w3id.org/np/RA7lSq6MuK_TIC6JMSHvLtee3lpLoZDOqLJCLXevnrPoU");
×
531
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAcTpoh5Ra0ssqmcpOgWdaZ_YiPE6demO6cpw-2RvSNs8");
×
532
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA4LGtuOqTIMqVAkjnfBXk1YDcAPNadP5CGiaJiBkdHCQ");
×
533
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAl_-VTw9Re_uRF8r8y0rjlfnu7FlhTa8xg_8xkcweqiE");
×
534
            recommendedProvTemplateOptionIds.add("https://w3id.org/np/RASORV2mMEVpS4lWh2bwUTEcV-RWjbD9RPbN7J0PIeYAU");
×
535
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAjkBbM5yQm7hKH1l_Jk3HAUqWi3Bd57TPmAOZCsZmi_M");
×
536
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAGXx_k9eQMnXaCbsXMsJbGClwZtQEGNg0GVJu6amdAVw");
×
537
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA1fnITI3Pu1UQ0CHghNpys3JwQrM32LBnjmDLoayp9-4");
×
538
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAJgbsGeGdTG-zq_gU0TLw4s3raMgoRk-mPlc2DSLXvE0");
×
539
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA6SXfhUY-xeblZU8HhPddw6tsu-C5NXevG6C_zv4bMxU");
×
540
            for (String s : recommendedProvTemplateOptionIds) {
×
541
                handledProvTemplates.put(s, true);
×
542
            }
×
543

544
            for (ApiResponseEntry t : td.getProvenanceTemplates()) {
×
545
                String tid = t.get("np");
×
546
                if (handledProvTemplates.containsKey(tid)) continue;
×
547
                provTemplateOptionIds.add(tid);
×
548
                handledProvTemplates.put(tid, true);
×
549
            }
×
550
        } else {
551
            for (String s : pageParams.get("prtemplate-options").toString().split(" ")) {
×
552
                if (handledProvTemplates.containsKey(s)) continue;
×
553
                recommendedProvTemplateOptionIds.add(s);
×
554
                handledProvTemplates.put(s, true);
×
555
            }
556
        }
557

558
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
559

560
            @Override
561
            public String getDisplayValue(String object) {
562
                if (object == null || object.isEmpty()) return "";
×
563
                Template t = td.getTemplate(object);
×
564
                if (t != null) return t.getLabel();
×
565
                return object;
×
566
            }
567

568
            @Override
569
            public String getIdValue(String object) {
570
                return object;
×
571
            }
572

573
            // Getting strange errors with Tomcat if this method is not overridden:
574
            @Override
575
            public void detach() {
576
            }
×
577

578
            @Override
579
            public void query(String term, int page, Response<String> response) {
580
                if (term == null) term = "";
×
581
                term = term.toLowerCase();
×
582
                if (pageParams.get("prtemplate").toString() != null) {
×
583
                    // Using this work-around with "——" because 'optgroup' is not available through Wicket's Select2 classes
584
                    response.add("—— default for this link ——");
×
585
                    response.add(prTemplateId);
×
586
                }
587
                if (defaultProvTemplateId != null) {
×
588
                    response.add("—— default for this template ——");
×
589
                    response.add(defaultProvTemplateId);
×
590
                }
591
                if (!recommendedProvTemplateOptionIds.isEmpty()) {
×
592
                    if (pageParams.get("prtemplate-options").isNull()) {
×
593
                        response.add("—— recommended ——");
×
594
                    }
595
                    for (String s : recommendedProvTemplateOptionIds) {
×
596
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
597
                            response.add(s);
×
598
                        }
599
                    }
×
600
                }
601
                if (!provTemplateOptionIds.isEmpty()) {
×
602
                    response.add("—— others ——");
×
603
                    for (String s : provTemplateOptionIds) {
×
604
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
605
                            response.add(s);
×
606
                        }
607
                    }
×
608
                }
609
            }
×
610

611
            @Override
612
            public Collection<String> toChoices(Collection<String> ids) {
613
                return ids;
×
614
            }
615

616
        };
617
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
618
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
619
        prTemplateChoice.setRequired(true);
×
620
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
621
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
622

623
            @Override
624
            protected void onUpdate(AjaxRequestTarget target) {
625
                String o = prTemplateModel.getObject();
×
626
                if (o.startsWith("——")) {
×
627
                    o = provenanceContext.getTemplate().getId();
×
628
                    prTemplateModel.setObject(o);
×
629
                }
630
                provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateModel.getObject(), "pr-statement", targetNamespace);
×
631
                provenanceContext.initStatements();
×
632
                refreshProvenance(target);
×
633
                provenanceContext.finalizeStatements();
×
634
            }
×
635

636
        });
637
        form.add(prTemplateChoice);
×
638
        refreshProvenance(null);
×
639

640
        final Map<String, Boolean> handledPiTemplates = new HashMap<>();
×
641
        final List<String> recommendedPiTemplateOptionIds = new ArrayList<>();
×
642
        final List<String> piTemplateOptionIds = new ArrayList<>();
×
643
        // TODO Make this dynamic and consider updated templates:
644
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAXflINqt3smqxV5Aq7E9lzje4uLdkKIOefa6Bp8oJ8CY");
×
645
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ");
×
646
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RA16U9Wo30ObhrK1NzH7EsmVRiRtvEuEA_Dfc-u8WkUCA");
×
647
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAdyqI6k07V5nAS82C6hvIDtNWk179EIV4DV-sLbOFKg4");
×
648
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RAjvEpLZUE7rMoa8q6mWSsN6utJDp-5FmgO47YGsbgw3w");
×
649
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAxuGRKID6yNg63V5Mf0ot2NjncOnodh-mkN3qT_1txGI");
×
650
        for (TemplateContext c : pubInfoContexts) {
×
651
            String s = c.getTemplate().getId();
×
652
            handledPiTemplates.put(s, true);
×
653
        }
×
654
        for (String s : recommendedPiTemplateOptionIds) {
×
655
            handledPiTemplates.put(s, true);
×
656
        }
×
657

658
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
659
            String tid = entry.get("np");
×
660
            if (handledPiTemplates.containsKey(tid)) continue;
×
661
            piTemplateOptionIds.add(tid);
×
662
            handledPiTemplates.put(tid, true);
×
663
        }
×
664

665
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
666

667
            @Override
668
            public String getDisplayValue(String object) {
669
                if (object == null || object.isEmpty()) return "";
×
670
                Template t = td.getTemplate(object);
×
671
                if (t != null) return t.getLabel();
×
672
                return object;
×
673
            }
674

675
            @Override
676
            public String getIdValue(String object) {
677
                return object;
×
678
            }
679

680
            // Getting strange errors with Tomcat if this method is not overridden:
681
            @Override
682
            public void detach() {
683
            }
×
684

685
            @Override
686
            public void query(String term, int page, Response<String> response) {
687
                if (term == null) term = "";
×
688
                term = term.toLowerCase();
×
689
                if (!recommendedPiTemplateOptionIds.isEmpty()) {
×
690
                    response.add("—— recommended ——");
×
691
                    for (String s : recommendedPiTemplateOptionIds) {
×
692
                        boolean isAlreadyUsed = false;
×
693
                        for (TemplateContext c : pubInfoContexts) {
×
694
                            // TODO: make this more efficient/nicer
695
                            if (c.getTemplate().getId().equals(s)) {
×
696
                                isAlreadyUsed = true;
×
697
                                break;
×
698
                            }
699
                        }
×
700
                        if (isAlreadyUsed) continue;
×
701
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
702
                            response.add(s);
×
703
                        }
704
                    }
×
705
                }
706
                if (!piTemplateOptionIds.isEmpty()) {
×
707
                    response.add("—— others ——");
×
708
                    for (String s : piTemplateOptionIds) {
×
709
                        boolean isAlreadyUsed = false;
×
710
                        for (TemplateContext c : pubInfoContexts) {
×
711
                            // TODO: make this more efficient/nicer
712
                            if (c.getTemplate().getId().equals(s)) {
×
713
                                isAlreadyUsed = true;
×
714
                                break;
×
715
                            }
716
                        }
×
717
                        if (isAlreadyUsed) continue;
×
718
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
719
                            response.add(s);
×
720
                        }
721
                    }
×
722
                }
723
            }
×
724

725
            @Override
726
            public Collection<String> toChoices(Collection<String> ids) {
727
                return ids;
×
728
            }
729

730
        };
731
        final IModel<String> newPiTemplateModel = Model.of();
×
732
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
733
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
734
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
735
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
736

737
            @Override
738
            protected void onUpdate(AjaxRequestTarget target) {
739
                if (newPiTemplateModel.getObject().startsWith("——")) {
×
740
                    newPiTemplateModel.setObject(null);
×
741
                    refreshPubInfo(target);
×
742
                    return;
×
743
                }
744
                String id = newPiTemplateModel.getObject();
×
745
                TemplateContext c = new TemplateContext(ContextType.PUBINFO, id, "pi-statement", targetNamespace);
×
746
                c.initStatements();
×
747
                pubInfoContexts.add(c);
×
748
                newPiTemplateModel.setObject(null);
×
749
                refreshPubInfo(target);
×
750
                c.finalizeStatements();
×
751
            }
×
752

753
        });
754
        form.add(piTemplateChoice);
×
755
        refreshPubInfo(null);
×
756

757
        form.add(consentCheck);
×
758

759
        form.add(new Button("preview-button") {
×
760
            @Override
761
            public void onSubmit() {
762
                try {
763
                    Nanopub np = createNanopub();
×
764
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
765
                    Nanopub signedNp = SignNanopub.signAndTransform(np, tc);
×
766
                    String previewId = signedNp.getUri().stringValue();
×
767
                    NanodashSession.get().setPreviewNanopub(previewId,
×
768
                            new NanodashSession.PreviewNanopub(signedNp, pageParams, confirmPageClass, Boolean.TRUE.equals(consentCheck.getModelObject())));
×
769
                    throw new RestartResponseException(PreviewPage.class, new PageParameters().set("id", previewId));
×
770
                } catch (RestartResponseException ex) {
×
771
                    throw ex;
×
772
                } catch (Exception ex) {
×
773
                    logger.error("Preview failed: {}", ex.getMessage());
×
774
                    String message = ex.getClass().getName();
×
775
                    if (ex.getMessage() != null) {
×
776
                        message = ex.getMessage();
×
777
                    }
778
                    feedbackPanel.error(message);
×
779
                }
780
            }
×
781
        });
782

783
        add(form);
×
784

785
        feedbackPanel = new FeedbackPanel("feedback");
×
786
        feedbackPanel.setOutputMarkupId(true);
×
787
        add(feedbackPanel);
×
788
    }
×
789

790
    private void refreshProvenance(AjaxRequestTarget target) {
791
        if (target != null) {
×
792
            form.remove("prtemplatelink");
×
793
            form.remove("pr-statements");
×
794
            target.add(form);
×
795
            target.appendJavaScript("updateElements();");
×
796
        }
797
        form.add(new BookmarkablePageLink<Void>("prtemplatelink", ExplorePage.class, new PageParameters().set("id", provenanceContext.getTemplate().getId())));
×
798
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
799

800
            protected void populateItem(ListItem<StatementItem> item) {
801
                item.add(item.getModelObject());
×
802
            }
×
803

804
        };
805
        list.setOutputMarkupId(true);
×
806
        form.add(list);
×
807
    }
×
808

809
    private void refreshPubInfo(AjaxRequestTarget target) {
810
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
811

812
            protected void populateItem(ListItem<TemplateContext> item) {
813
                final TemplateContext pic = item.getModelObject();
×
814
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
815
                item.add(new BookmarkablePageLink<Void>("pitemplatelink", ExplorePage.class, new PageParameters().set("id", pic.getTemplate().getId())));
×
816
                Label remove = new Label("piremove", "×");
×
817
                item.add(remove);
×
818
                remove.add(new AjaxEventBehavior("click") {
×
819

820
                    @Override
821
                    protected void onEvent(AjaxRequestTarget target) {
822
                        pubInfoContexts.remove(pic);
×
823
                        target.add(PublishForm.this);
×
824
                        target.appendJavaScript("updateElements();");
×
825
                    }
×
826

827
                });
828
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
829
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
830

831
                    protected void populateItem(ListItem<StatementItem> item) {
832
                        item.add(item.getModelObject());
×
833
                    }
×
834

835
                });
836
            }
×
837

838
        };
839
        list.setOutputMarkupId(true);
×
840
        if (target == null) {
×
841
            form.add(list);
×
842
        } else {
843
            form.remove("pis");
×
844
            form.add(list);
×
845
            target.add(form);
×
846
            target.appendJavaScript("updateElements();");
×
847
        }
848
    }
×
849

850
    private TemplateContext createPubinfoContext(String piTemplateId) {
851
        TemplateContext c;
852
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
853
            c = pubInfoContextMap.get(piTemplateId);
×
854
        } else {
855
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
856
            pubInfoContextMap.put(piTemplateId, c);
×
857
            pubInfoContexts.add(c);
×
858
        }
859
        return c;
×
860
    }
861

862
    private synchronized Nanopub createNanopub() throws MalformedNanopubException, NanopubAlreadyFinalizedException {
863
        assertionContext.getIntroducedIris().clear();
×
864
        NanopubCreator npCreator = new NanopubCreator(targetNamespace);
×
865
        npCreator.setAssertionUri(vf.createIRI(targetNamespace + "assertion"));
×
866
        assertionContext.propagateStatements(npCreator);
×
867
        provenanceContext.propagateStatements(npCreator);
×
868
        for (TemplateContext c : pubInfoContexts) {
×
869
            c.propagateStatements(npCreator);
×
870
        }
×
871
        for (IRI introducedIri : assertionContext.getIntroducedIris()) {
×
872
            npCreator.addPubinfoStatement(NPX.INTRODUCES, introducedIri);
×
873
        }
×
874
        for (IRI embeddedIri : assertionContext.getEmbeddedIris()) {
×
875
            npCreator.addPubinfoStatement(NPX.EMBEDS, embeddedIri);
×
876
        }
×
877
        npCreator.addNamespace("this", targetNamespace);
×
878
        npCreator.addNamespace("sub", targetNamespace + "/");
×
879
        npCreator.addTimestampNow();
×
880
        IRI templateUri = assertionContext.getTemplate().getNanopub().getUri();
×
881
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_TEMPLATE, templateUri);
×
882
        IRI prTemplateUri = provenanceContext.getTemplate().getNanopub().getUri();
×
883
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PROVENANCE_TEMPLATE, prTemplateUri);
×
884
        for (TemplateContext c : pubInfoContexts) {
×
885
            IRI piTemplateUri = c.getTemplate().getNanopub().getUri();
×
886
            npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PUBINFO_TEMPLATE, piTemplateUri);
×
887
        }
×
888
        String nanopubLabel = getNanopubLabel(npCreator);
×
889
        if (nanopubLabel != null) {
×
890
            npCreator.addPubinfoStatement(RDFS.LABEL, vf.createLiteral(nanopubLabel));
×
891
        }
892
        for (IRI type : assertionContext.getTemplate().getTargetNanopubTypes()) {
×
893
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, type);
×
894
        }
×
895
        IRI userIri = NanodashSession.get().getUserIri();
×
896
        if (User.getName(userIri) != null) {
×
897
            npCreator.addPubinfoStatement(userIri, FOAF.NAME, vf.createLiteral(User.getName(userIri)));
×
898
            npCreator.addNamespace("foaf", FOAF.NAMESPACE);
×
899
        }
900
        String websiteUrl = NanodashPreferences.get().getWebsiteUrl();
×
901
        if (websiteUrl != null) {
×
902
            npCreator.addPubinfoStatement(NPX.WAS_CREATED_AT, vf.createIRI(websiteUrl));
×
903
        }
904
        return npCreator.finalizeNanopub();
×
905
    }
906

907
    private String getNanopubLabel(NanopubCreator npCreator) {
908
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
909

910
        Map<IRI, String> labelMap = new HashMap<>();
×
911
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
912
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
913
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
914
            }
915
        }
×
916

917
        String nanopubLabel = assertionContext.getTemplate().getNanopubLabelPattern();
×
918
        while (nanopubLabel.matches(".*\\$\\{[_a-zA-Z0-9-]+\\}.*")) {
×
919
            String placeholderPostfix = nanopubLabel.replaceFirst("^.*\\$\\{([_a-zA-Z0-9-]+)\\}.*$", "$1");
×
920
            IRI placeholderIriHash = vf.createIRI(assertionContext.getTemplateId() + "#" + placeholderPostfix);
×
921
            IRI placeholderIriSlash = vf.createIRI(assertionContext.getTemplateId() + "/" + placeholderPostfix);
×
922
            IRI placeholderIri;
923
            String placeholderValue = "";
×
924
            if (assertionContext.getComponentModels().get(placeholderIriSlash) != null) {
×
925
                placeholderIri = placeholderIriSlash;
×
926
            } else {
927
                placeholderIri = placeholderIriHash;
×
928
            }
929
            IModel<String> m = (IModel<String>) assertionContext.getComponentModels().get(placeholderIri);
×
930
            if (m != null) placeholderValue = m.orElse("").getObject();
×
931
            if (placeholderValue == null) placeholderValue = "";
×
932
            String placeholderLabel = placeholderValue;
×
933
            if (assertionContext.getTemplate().isUriPlaceholder(placeholderIri)) {
×
934
                try {
935
                    // TODO Fix this. It doesn't work for placeholders with auto-encode placeholders, etc.
936
                    //      Not sure we need labels for these, but this code should be improved anyway.
937
                    String prefix = assertionContext.getTemplate().getPrefix(placeholderIri);
×
938
                    if (prefix != null) placeholderValue = prefix + placeholderValue;
×
939
                    IRI placeholderValueIri = vf.createIRI(placeholderValue);
×
940
                    String l = assertionContext.getTemplate().getLabel(placeholderValueIri);
×
941
                    if (labelMap.containsKey(placeholderValueIri)) {
×
942
                        l = labelMap.get(placeholderValueIri);
×
943
                    }
944
                    if (l == null) l = GuidedChoiceItem.getLabel(placeholderValue);
×
945
                    if (assertionContext.getTemplate().isAgentPlaceholder(placeholderIri) && !placeholderValue.isEmpty()) {
×
946
                        l = User.getName(vf.createIRI(placeholderValue));
×
947
                    }
948
                    if (l != null && !l.isEmpty()) {
×
949
                        placeholderLabel = l.replaceFirst(" - .*$", "");
×
950
                    } else {
951
                        placeholderLabel = Utils.getShortNameFromURI(placeholderValueIri);
×
952
                    }
953
                } catch (Exception ex) {
×
954
                    logger.error("Nanopub label placeholder IRI error: {}", ex.getMessage());
×
955
                }
×
956
            }
957
            placeholderLabel = placeholderLabel.replaceAll("\\s+", " ");
×
958
            if (placeholderLabel.length() > 100) placeholderLabel = placeholderLabel.substring(0, 97) + "...";
×
959
            nanopubLabel = Strings.CS.replace(nanopubLabel, "${" + placeholderPostfix + "}", placeholderLabel);
×
960
        }
×
961
        return nanopubLabel;
×
962
    }
963

964
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
965
        try {
966
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
967
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
968
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
969
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
970
        }
971
        return null;
×
972
    }
973

974
    /**
975
     * Returns a hint whether the form is stateless or not.
976
     *
977
     * @return false if the form is stateful, true if it is stateless.
978
     */
979
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
980
    // if the user browses other pages in parallel:
981
    protected boolean getStatelessHint() {
982
        return false;
×
983
    }
984

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