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

knowledgepixels / nanodash / 19366908152

14 Nov 2025 02:02PM UTC coverage: 14.317% (+0.4%) from 13.87%
19366908152

push

github

tkuhn
feat: "refresh-upon-publish" PublishPage param to force cache refreshing

546 of 4776 branches covered (11.43%)

Branch coverage included in aggregate %.

1401 of 8823 relevant lines covered (15.88%)

0.71 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.QueryApiAccess;
72
import com.knowledgepixels.nanodash.Space;
73
import com.knowledgepixels.nanodash.User;
74
import com.knowledgepixels.nanodash.Utils;
75
import com.knowledgepixels.nanodash.page.ExplorePage;
76
import com.knowledgepixels.nanodash.page.NanodashPage;
77
import com.knowledgepixels.nanodash.template.ContextType;
78
import com.knowledgepixels.nanodash.template.Template;
79
import com.knowledgepixels.nanodash.template.TemplateContext;
80
import com.knowledgepixels.nanodash.template.TemplateData;
81
import com.knowledgepixels.nanodash.template.ValueFiller;
82

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

423
        });
424

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

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

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

444
        });
445

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

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

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

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

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

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

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

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

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

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

539
        });
540

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

833
                });
834
            }
×
835

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

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

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

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

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

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

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

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

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