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

knowledgepixels / nanodash / 20165673093

12 Dec 2025 11:42AM UTC coverage: 15.633% (+0.1%) from 15.513%
20165673093

push

github

tkuhn
feat(ProfiledResource): Consistently refresh, also for view displays

610 of 4974 branches covered (12.26%)

Branch coverage included in aggregate %.

1589 of 9092 relevant lines covered (17.48%)

2.32 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.APINotReachableException;
53
import org.nanopub.extra.services.ApiResponse;
54
import org.nanopub.extra.services.ApiResponseEntry;
55
import org.nanopub.extra.services.FailedApiCallException;
56
import org.nanopub.extra.services.NotEnoughAPIInstancesException;
57
import org.nanopub.extra.services.QueryRef;
58
import org.nanopub.vocabulary.NPX;
59
import org.nanopub.vocabulary.NTEMPLATE;
60
import org.slf4j.Logger;
61
import org.slf4j.LoggerFactory;
62
import org.wicketstuff.select2.ChoiceProvider;
63
import org.wicketstuff.select2.Response;
64
import org.wicketstuff.select2.Select2Choice;
65

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

84
/**
85
 * Form for publishing a nanopublication.
86
 */
87
public class PublishForm extends Panel {
88

89
    private static final Logger logger = LoggerFactory.getLogger(PublishForm.class);
×
90

91
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
92

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

99
    private static String[] fixedPubInfoTemplates = new String[]{creatorPubinfoTemplateId, licensePubinfoTempalteId};
×
100

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

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

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

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

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

189
        final TemplateData td = TemplateData.get();
×
190

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

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

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

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

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

337
        final Nanopub improveNp;
338
        if (!pageParams.get("improve").isNull()) {
×
339
            improveNp = Utils.getNanopub(pageParams.get("improve").toString());
×
340
        } else {
341
            improveNp = null;
×
342
        }
343

344
        final List<Statement> unusedStatementList = new ArrayList<>();
×
345
        final List<Statement> unusedPrStatementList = new ArrayList<>();
×
346
        final List<Statement> unusedPiStatementList = new ArrayList<>();
×
347
        if (fillNp != null) {
×
348
            ValueFiller filler = new ValueFiller(fillNp, ContextType.ASSERTION, true, fillMode);
×
349
            filler.fill(assertionContext);
×
350
            unusedStatementList.addAll(filler.getUnusedStatements());
×
351

352
            if (!fillOnlyAssertion) {
×
353
                ValueFiller prFiller = new ValueFiller(fillNp, ContextType.PROVENANCE, true);
×
354
                prFiller.fill(provenanceContext);
×
355
                unusedPrStatementList.addAll(prFiller.getUnusedStatements());
×
356

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

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

408
        });
409
        add(new DataView<Statement>("unused-prstatements", new ListDataProvider<Statement>(unusedPrStatementList)) {
×
410

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

416
        });
417
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
418

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

424
        });
425

426
        // Finalize statements, which picks up parameter values in repetitions:
427
        assertionContext.finalizeStatements();
×
428
        provenanceContext.finalizeStatements();
×
429
        for (TemplateContext c : pubInfoContexts) {
×
430
            c.finalizeStatements();
×
431
        }
×
432

433
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
434
        consentCheck.setRequired(true);
×
435
        consentCheck.add(new InvalidityHighlighting());
×
436
        consentCheck.add(new IValidator<Boolean>() {
×
437

438
            @Override
439
            public void validate(IValidatable<Boolean> validatable) {
440
                if (!Boolean.TRUE.equals(validatable.getValue())) {
×
441
                    validatable.error(new ValidationError("You need to check the checkbox that you understand the consequences."));
×
442
                }
443
            }
×
444

445
        });
446

447
        form = new Form<Void>("form") {
×
448

449
            @Override
450
            protected void onConfigure() {
451
                super.onConfigure();
×
452
                form.getFeedbackMessages().clear();
×
453
//                                formComponents.clear();
454
            }
×
455

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

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

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

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

526
        form.add(new Label("nanopub-namespace", targetNamespaceLabel));
×
527

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

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

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

540
        });
541

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

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

582
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
583

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

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

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

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

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

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

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

660
        });
661
        form.add(prTemplateChoice);
×
662
        refreshProvenance(null);
×
663

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

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

689
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
690

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

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

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

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

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

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

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

777
        });
778
        form.add(piTemplateChoice);
×
779
        refreshPubInfo(null);
×
780

781
        form.add(consentCheck);
×
782
        add(form);
×
783

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

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

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

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

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

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

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

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

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

834
                });
835
            }
×
836

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

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

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

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

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

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

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

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

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