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

knowledgepixels / nanodash / 20299457275

17 Dec 2025 10:20AM UTC coverage: 14.401% (-0.9%) from 15.279%
20299457275

push

github

tkuhn
fix: Use API result cache for all requests

546 of 5004 branches covered (10.91%)

Branch coverage included in aggregate %.

1496 of 9176 relevant lines covered (16.3%)

2.13 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 java.lang.reflect.InvocationTargetException;
4
import java.util.ArrayList;
5
import java.util.Collection;
6
import java.util.HashMap;
7
import java.util.List;
8
import java.util.Map;
9

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.CheckBox;
21
import org.apache.wicket.markup.html.form.Form;
22
import org.apache.wicket.markup.html.form.FormComponent;
23
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
24
import org.apache.wicket.markup.html.list.ListItem;
25
import org.apache.wicket.markup.html.list.ListView;
26
import org.apache.wicket.markup.html.panel.FeedbackPanel;
27
import org.apache.wicket.markup.html.panel.Panel;
28
import org.apache.wicket.markup.repeater.Item;
29
import org.apache.wicket.markup.repeater.data.DataView;
30
import org.apache.wicket.markup.repeater.data.ListDataProvider;
31
import org.apache.wicket.model.IModel;
32
import org.apache.wicket.model.Model;
33
import org.apache.wicket.request.mapper.parameter.PageParameters;
34
import org.apache.wicket.validation.IValidatable;
35
import org.apache.wicket.validation.IValidator;
36
import org.apache.wicket.validation.ValidationError;
37
import org.eclipse.rdf4j.model.IRI;
38
import org.eclipse.rdf4j.model.Literal;
39
import org.eclipse.rdf4j.model.Statement;
40
import org.eclipse.rdf4j.model.ValueFactory;
41
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
42
import org.eclipse.rdf4j.model.vocabulary.FOAF;
43
import org.eclipse.rdf4j.model.vocabulary.RDFS;
44
import org.nanopub.MalformedNanopubException;
45
import org.nanopub.Nanopub;
46
import org.nanopub.NanopubAlreadyFinalizedException;
47
import org.nanopub.NanopubCreator;
48
import org.nanopub.extra.security.SignNanopub;
49
import org.nanopub.extra.security.SignatureAlgorithm;
50
import org.nanopub.extra.security.TransformContext;
51
import org.nanopub.extra.server.PublishNanopub;
52
import org.nanopub.extra.services.ApiResponse;
53
import org.nanopub.extra.services.ApiResponseEntry;
54
import org.nanopub.extra.services.QueryRef;
55
import org.nanopub.vocabulary.NPX;
56
import org.nanopub.vocabulary.NTEMPLATE;
57
import org.slf4j.Logger;
58
import org.slf4j.LoggerFactory;
59
import org.wicketstuff.select2.ChoiceProvider;
60
import org.wicketstuff.select2.Response;
61
import org.wicketstuff.select2.Select2Choice;
62

63
import com.knowledgepixels.nanodash.ApiCache;
64
import com.knowledgepixels.nanodash.LocalUri;
65
import com.knowledgepixels.nanodash.MaintainedResource;
66
import com.knowledgepixels.nanodash.NanodashPreferences;
67
import com.knowledgepixels.nanodash.NanodashSession;
68
import com.knowledgepixels.nanodash.ProfiledResource;
69
import com.knowledgepixels.nanodash.QueryApiAccess;
70
import com.knowledgepixels.nanodash.Space;
71
import com.knowledgepixels.nanodash.User;
72
import com.knowledgepixels.nanodash.Utils;
73
import com.knowledgepixels.nanodash.page.ExplorePage;
74
import com.knowledgepixels.nanodash.page.NanodashPage;
75
import com.knowledgepixels.nanodash.template.ContextType;
76
import com.knowledgepixels.nanodash.template.Template;
77
import com.knowledgepixels.nanodash.template.TemplateContext;
78
import com.knowledgepixels.nanodash.template.TemplateData;
79
import com.knowledgepixels.nanodash.template.ValueFiller;
80

81
/**
82
 * Form for publishing a nanopublication.
83
 */
84
public class PublishForm extends Panel {
85

86
    private static final Logger logger = LoggerFactory.getLogger(PublishForm.class);
×
87

88
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
89

90
    private static String creatorPubinfoTemplateId = "https://w3id.org/np/RAukAcWHRDlkqxk7H2XNSegc1WnHI569INvNr-xdptDGI";
×
91
    private static String licensePubinfoTempalteId = "https://w3id.org/np/RA0J4vUn_dekg-U1kK3AOEt02p9mT2WO03uGxLDec1jLw";
×
92
    private static String defaultProvTemplateId = "https://w3id.org/np/RA7lSq6MuK_TIC6JMSHvLtee3lpLoZDOqLJCLXevnrPoU";
×
93
    private static String supersedesPubinfoTemplateId = "https://w3id.org/np/RAoTD7udB2KtUuOuAe74tJi1t3VzK0DyWS7rYVAq1GRvw";
×
94
    private static String derivesFromPubinfoTemplateId = "https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ";
×
95

96
    private static String[] fixedPubInfoTemplates = new String[]{creatorPubinfoTemplateId, licensePubinfoTempalteId};
×
97

98
    /**
99
     * Fill modes for the nanopublication to be created.
100
     */
101
    public enum FillMode {
×
102
        /**
103
         * Use fill mode
104
         */
105
        USE,
×
106
        /**
107
         * Supersede fill mode
108
         */
109
        SUPERSEDE,
×
110
        /**
111
         * Derive fill mode
112
         */
113
        DERIVE
×
114
    }
115

116
    protected Form<?> form;
117
    protected FeedbackPanel feedbackPanel;
118
    private final TemplateContext assertionContext;
119
    private TemplateContext provenanceContext;
120
    private List<TemplateContext> pubInfoContexts = new ArrayList<>();
×
121
    private Map<String, TemplateContext> pubInfoContextMap = new HashMap<>();
×
122
    private List<TemplateContext> requiredPubInfoContexts = new ArrayList<>();
×
123
    private String targetNamespace;
124
    private Class<? extends WebPage> confirmPageClass;
125

126
    /**
127
     * Constructor for the PublishForm.
128
     *
129
     * @param id               the Wicket component ID
130
     * @param pageParams       the parameters for the page, which may include information on how to fill the form
131
     * @param publishPageClass the class of the page to redirect to after successful publication
132
     * @param confirmPageClass the class of the confirmation page to show after publication
133
     */
134
    public PublishForm(String id, final PageParameters pageParams, Class<? extends WebPage> publishPageClass, Class<? extends WebPage> confirmPageClass) {
135
        super(id);
×
136
        setOutputMarkupId(true);
×
137
        this.confirmPageClass = confirmPageClass;
×
138

139
        WebMarkupContainer linkMessageItem = new WebMarkupContainer("link-message-item");
×
140
        if (pageParams.get("link-message").isNull()) {
×
141
            linkMessageItem.add(new Label("link-message", ""));
×
142
            linkMessageItem.setVisible(false);
×
143
        } else {
144
            linkMessageItem.add(new Label("link-message", Utils.sanitizeHtml(pageParams.get("link-message").toString())).setEscapeModelStrings(false));
×
145
        }
146
        add(linkMessageItem);
×
147

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

186
        final TemplateData td = TemplateData.get();
×
187

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

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

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

309
        // Init statements only now, in order to pick up parameter values:
310
        assertionContext.initStatements();
×
311
        provenanceContext.initStatements();
×
312
        for (TemplateContext c : pubInfoContexts) {
×
313
            c.initStatements();
×
314
        }
×
315

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

330
        final Nanopub improveNp;
331
        if (!pageParams.get("improve").isNull()) {
×
332
            improveNp = Utils.getNanopub(pageParams.get("improve").toString());
×
333
        } else {
334
            improveNp = null;
×
335
        }
336

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

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

350
                ValueFiller piFiller = new ValueFiller(fillNp, ContextType.PUBINFO, true);
×
351
                if (!assertionContext.getTemplate().getTargetNanopubTypes().isEmpty()) {
×
352
                    for (Statement st : new ArrayList<>(piFiller.getUnusedStatements())) {
×
353
                        if (st.getSubject().stringValue().equals(LocalUri.of("nanopub").stringValue()) && st.getPredicate().equals(NPX.HAS_NANOPUB_TYPE)) {
×
354
                            if (assertionContext.getTemplate().getTargetNanopubTypes().contains(st.getObject())) {
×
355
                                piFiller.removeUnusedStatement(st);
×
356
                            }
357
                        }
358
                    }
×
359
                }
360
                for (TemplateContext c : pubInfoContexts) {
×
361
                    piFiller.fill(c);
×
362
                }
×
363
                piFiller.removeUnusedStatements(NanodashSession.get().getUserIri(), FOAF.NAME, null);
×
364
                if (piFiller.hasUnusedStatements()) {
×
365
                    final String handcodedStatementsTemplateId = "https://w3id.org/np/RAMEgudZsQ1bh1fZhfYnkthqH6YSXpghSE_DEN1I-6eAI";
×
366
                    if (!pubInfoContextMap.containsKey(handcodedStatementsTemplateId)) {
×
367
                        TemplateContext c = createPubinfoContext(handcodedStatementsTemplateId);
×
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.setRequired(true);
×
428
        consentCheck.add(new InvalidityHighlighting());
×
429
        consentCheck.add(new IValidator<Boolean>() {
×
430

431
            @Override
432
            public void validate(IValidatable<Boolean> validatable) {
433
                if (!Boolean.TRUE.equals(validatable.getValue())) {
×
434
                    validatable.error(new ValidationError("You need to check the checkbox that you understand the consequences."));
×
435
                }
436
            }
×
437

438
        });
439

440
        form = new Form<Void>("form") {
×
441

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

449
            protected void onSubmit() {
450
                logger.info("Publish form submitted");
×
451
                Nanopub signedNp = null;
×
452
                try {
453
                    Nanopub np = createNanopub();
×
454
                    logger.info("Nanopublication created: {}", np.getUri());
×
455
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
456
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
457
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
458
                    String npUrl = PublishNanopub.publish(signedNp);
×
459
                    logger.info("Nanopublication published: {}", npUrl);
×
460
                } catch (Exception ex) {
×
461
                    signedNp = null;
×
462
                    logger.error("Nanopublication publishing failed: {}", ex);
×
463
                    String message = ex.getClass().getName();
×
464
                    if (ex.getMessage() != null) {
×
465
                        message = ex.getMessage();
×
466
                    }
467
                    feedbackPanel.error(message);
×
468
                }
×
469
                if (!pageParams.get("refresh-upon-publish").isEmpty()) {
×
470
                    String toRefresh = pageParams.get("refresh-upon-publish").toString();
×
471
                    if (toRefresh.equals("spaces")) {
×
472
                        Space.forceRootRefresh(3 * 1000);
×
473
                    } else if (toRefresh.equals("maintainedResources")) {
×
474
                        MaintainedResource.forceRootRefresh(3 * 1000);
×
475
                    } else if (ProfiledResource.isProfiledResource(toRefresh)) {
×
476
                        ProfiledResource.forceRefresh(toRefresh, 3 * 1000);
×
477
                    } else {
478
                        QueryRef queryRef = QueryRef.parseString(toRefresh);
×
479
                        // Make sure the next cache update happens not before 3 seconds from now, at which point the
480
                        // published nanopub should show up in the Nanopub Query instances:
481
                        ApiCache.clearCache(queryRef, 3 * 1000);
×
482
                    }
483
                }
484
                if (signedNp != null) {
×
485
                    throw new RestartResponseException(getConfirmPage(signedNp, pageParams));
×
486
                } else {
487
                    logger.error("Nanopublication publishing failed");
×
488
                }
489
            }
×
490

491
            @Override
492
            protected void onValidate() {
493
                super.onValidate();
×
494
                for (Component fc : assertionContext.getComponents()) {
×
495
                    processFeedback(fc);
×
496
                }
×
497
                for (Component fc : provenanceContext.getComponents()) {
×
498
                    processFeedback(fc);
×
499
                }
×
500
                for (TemplateContext c : pubInfoContexts) {
×
501
                    for (Component fc : c.getComponents()) {
×
502
                        processFeedback(fc);
×
503
                    }
×
504
                }
×
505
            }
×
506

507
            private void processFeedback(Component c) {
508
                if (c instanceof FormComponent) {
×
509
                    ((FormComponent<?>) c).processInput();
×
510
                }
511
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
512
                    form.getFeedbackMessages().add(fm);
×
513
                }
×
514
            }
×
515

516
        };
517
        form.setOutputMarkupId(true);
×
518

519
        form.add(new Label("nanopub-namespace", targetNamespaceLabel));
×
520

521
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
522
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
523
        String description = assertionContext.getTemplate().getLabel();
×
524
        if (description == null) description = "";
×
525
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
526

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

529
            protected void populateItem(ListItem<StatementItem> item) {
530
                item.add(item.getModelObject());
×
531
            }
×
532

533
        });
534

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

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

575
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
576

577
            @Override
578
            public String getDisplayValue(String object) {
579
                if (object == null || object.isEmpty()) return "";
×
580
                Template t = td.getTemplate(object);
×
581
                if (t != null) return t.getLabel();
×
582
                return object;
×
583
            }
584

585
            @Override
586
            public String getIdValue(String object) {
587
                return object;
×
588
            }
589

590
            // Getting strange errors with Tomcat if this method is not overridden:
591
            @Override
592
            public void detach() {
593
            }
×
594

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

628
            @Override
629
            public Collection<String> toChoices(Collection<String> ids) {
630
                return ids;
×
631
            }
632

633
        };
634
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
635
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
636
        prTemplateChoice.setRequired(true);
×
637
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
638
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
639

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

653
        });
654
        form.add(prTemplateChoice);
×
655
        refreshProvenance(null);
×
656

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

675
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
676
            String tid = entry.get("np");
×
677
            if (handledPiTemplates.containsKey(tid)) continue;
×
678
            piTemplateOptionIds.add(tid);
×
679
            handledPiTemplates.put(tid, true);
×
680
        }
×
681

682
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
683

684
            @Override
685
            public String getDisplayValue(String object) {
686
                if (object == null || object.isEmpty()) return "";
×
687
                Template t = td.getTemplate(object);
×
688
                if (t != null) return t.getLabel();
×
689
                return object;
×
690
            }
691

692
            @Override
693
            public String getIdValue(String object) {
694
                return object;
×
695
            }
696

697
            // Getting strange errors with Tomcat if this method is not overridden:
698
            @Override
699
            public void detach() {
700
            }
×
701

702
            @Override
703
            public void query(String term, int page, Response<String> response) {
704
                if (term == null) term = "";
×
705
                term = term.toLowerCase();
×
706
                if (!recommendedPiTemplateOptionIds.isEmpty()) {
×
707
                    response.add("—— recommended ——");
×
708
                    for (String s : recommendedPiTemplateOptionIds) {
×
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
                if (!piTemplateOptionIds.isEmpty()) {
×
724
                    response.add("—— others ——");
×
725
                    for (String s : piTemplateOptionIds) {
×
726
                        boolean isAlreadyUsed = false;
×
727
                        for (TemplateContext c : pubInfoContexts) {
×
728
                            // TODO: make this more efficient/nicer
729
                            if (c.getTemplate().getId().equals(s)) {
×
730
                                isAlreadyUsed = true;
×
731
                                break;
×
732
                            }
733
                        }
×
734
                        if (isAlreadyUsed) continue;
×
735
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
736
                            response.add(s);
×
737
                        }
738
                    }
×
739
                }
740
            }
×
741

742
            @Override
743
            public Collection<String> toChoices(Collection<String> ids) {
744
                return ids;
×
745
            }
746

747
        };
748
        final IModel<String> newPiTemplateModel = Model.of();
×
749
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
750
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
751
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
752
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
753

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

770
        });
771
        form.add(piTemplateChoice);
×
772
        refreshPubInfo(null);
×
773

774
        form.add(consentCheck);
×
775
        add(form);
×
776

777
        feedbackPanel = new FeedbackPanel("feedback");
×
778
        feedbackPanel.setOutputMarkupId(true);
×
779
        add(feedbackPanel);
×
780
    }
×
781

782
    private void refreshProvenance(AjaxRequestTarget target) {
783
        if (target != null) {
×
784
            form.remove("prtemplatelink");
×
785
            form.remove("pr-statements");
×
786
            target.add(form);
×
787
            target.appendJavaScript("updateElements();");
×
788
        }
789
        form.add(new BookmarkablePageLink<Void>("prtemplatelink", ExplorePage.class, new PageParameters().set("id", provenanceContext.getTemplate().getId())));
×
790
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
791

792
            protected void populateItem(ListItem<StatementItem> item) {
793
                item.add(item.getModelObject());
×
794
            }
×
795

796
        };
797
        list.setOutputMarkupId(true);
×
798
        form.add(list);
×
799
    }
×
800

801
    private void refreshPubInfo(AjaxRequestTarget target) {
802
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
803

804
            protected void populateItem(ListItem<TemplateContext> item) {
805
                final TemplateContext pic = item.getModelObject();
×
806
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
807
                item.add(new BookmarkablePageLink<Void>("pitemplatelink", ExplorePage.class, new PageParameters().set("id", pic.getTemplate().getId())));
×
808
                Label remove = new Label("piremove", "×");
×
809
                item.add(remove);
×
810
                remove.add(new AjaxEventBehavior("click") {
×
811

812
                    @Override
813
                    protected void onEvent(AjaxRequestTarget target) {
814
                        pubInfoContexts.remove(pic);
×
815
                        target.add(PublishForm.this);
×
816
                        target.appendJavaScript("updateElements();");
×
817
                    }
×
818

819
                });
820
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
821
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
822

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

827
                });
828
            }
×
829

830
        };
831
        list.setOutputMarkupId(true);
×
832
        if (target == null) {
×
833
            form.add(list);
×
834
        } else {
835
            form.remove("pis");
×
836
            form.add(list);
×
837
            target.add(form);
×
838
            target.appendJavaScript("updateElements();");
×
839
        }
840
    }
×
841

842
    private TemplateContext createPubinfoContext(String piTemplateId) {
843
        TemplateContext c;
844
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
845
            c = pubInfoContextMap.get(piTemplateId);
×
846
        } else {
847
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
848
            pubInfoContextMap.put(piTemplateId, c);
×
849
            pubInfoContexts.add(c);
×
850
        }
851
        return c;
×
852
    }
853

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

899
    private String getNanopubLabel(NanopubCreator npCreator) {
900
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
901

902
        Map<IRI, String> labelMap = new HashMap<>();
×
903
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
904
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
905
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
906
            }
907
        }
×
908

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

956
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
957
        try {
958
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
959
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
960
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
961
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
962
        }
963
        return null;
×
964
    }
965

966
    /**
967
     * Returns a hint whether the form is stateless or not.
968
     *
969
     * @return false if the form is stateful, true if it is stateless.
970
     */
971
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
972
    // if the user browses other pages in parallel:
973
    protected boolean getStatelessHint() {
974
        return false;
×
975
    }
976

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