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

knowledgepixels / nanodash / 23799954373

31 Mar 2026 01:30PM UTC coverage: 16.286% (-0.01%) from 16.297%
23799954373

push

github

web-flow
Merge pull request #424 from knowledgepixels/fix/423-error-after-publishing

fix: prevent error page after publishing

756 of 5705 branches covered (13.25%)

Branch coverage included in aggregate %.

1902 of 10616 relevant lines covered (17.92%)

2.46 hits per line

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

0.0
src/main/java/com/knowledgepixels/nanodash/component/PublishForm.java
1
package com.knowledgepixels.nanodash.component;
2

3
import com.knowledgepixels.nanodash.*;
4
import com.knowledgepixels.nanodash.domain.IndividualAgent;
5
import com.knowledgepixels.nanodash.domain.User;
6
import com.knowledgepixels.nanodash.page.*;
7
import com.knowledgepixels.nanodash.repository.MaintainedResourceRepository;
8
import com.knowledgepixels.nanodash.repository.SpaceRepository;
9
import com.knowledgepixels.nanodash.template.*;
10
import org.apache.commons.lang3.Strings;
11
import org.apache.wicket.Component;
12
import org.apache.wicket.RestartResponseException;
13
import org.apache.wicket.ajax.AjaxEventBehavior;
14
import org.apache.wicket.ajax.AjaxRequestTarget;
15
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
16
import org.apache.wicket.feedback.FeedbackMessage;
17
import org.apache.wicket.markup.html.WebMarkupContainer;
18
import org.apache.wicket.markup.html.WebPage;
19
import org.apache.wicket.markup.html.basic.Label;
20
import org.apache.wicket.markup.html.form.Button;
21
import org.apache.wicket.markup.html.form.CheckBox;
22
import org.apache.wicket.markup.html.form.Form;
23
import org.apache.wicket.markup.html.form.FormComponent;
24
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
25
import org.apache.wicket.markup.html.list.ListItem;
26
import org.apache.wicket.markup.html.list.ListView;
27
import org.apache.wicket.markup.html.panel.FeedbackPanel;
28
import org.apache.wicket.markup.html.panel.Panel;
29
import org.apache.wicket.markup.repeater.Item;
30
import org.apache.wicket.markup.repeater.data.DataView;
31
import org.apache.wicket.markup.repeater.data.ListDataProvider;
32
import org.apache.wicket.model.IModel;
33
import org.apache.wicket.model.Model;
34
import org.apache.wicket.request.mapper.parameter.PageParameters;
35
import org.eclipse.rdf4j.model.IRI;
36
import org.eclipse.rdf4j.model.Literal;
37
import org.eclipse.rdf4j.model.Statement;
38
import org.eclipse.rdf4j.model.ValueFactory;
39
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
40
import org.eclipse.rdf4j.model.vocabulary.FOAF;
41
import org.eclipse.rdf4j.model.vocabulary.RDFS;
42
import org.nanopub.MalformedNanopubException;
43
import org.nanopub.Nanopub;
44
import org.nanopub.NanopubAlreadyFinalizedException;
45
import org.nanopub.NanopubCreator;
46
import org.nanopub.extra.security.SignNanopub;
47
import org.nanopub.extra.security.SignatureAlgorithm;
48
import org.nanopub.extra.security.TransformContext;
49
import org.nanopub.extra.server.PublishNanopub;
50
import org.nanopub.extra.services.ApiResponse;
51
import org.nanopub.extra.services.ApiResponseEntry;
52
import org.nanopub.extra.services.QueryRef;
53
import org.nanopub.vocabulary.NPX;
54
import org.nanopub.vocabulary.NTEMPLATE;
55
import org.slf4j.Logger;
56
import org.slf4j.LoggerFactory;
57
import org.wicketstuff.select2.ChoiceProvider;
58
import org.wicketstuff.select2.Response;
59
import org.wicketstuff.select2.Select2Choice;
60

61
import java.lang.reflect.InvocationTargetException;
62
import java.util.*;
63

64
/**
65
 * Form for publishing a nanopublication.
66
 */
67
public class PublishForm extends Panel {
68

69
    private static final Logger logger = LoggerFactory.getLogger(PublishForm.class);
×
70

71
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
72

73
    public static final String CREATOR_PUB_INFO_TEMPLATE = "https://w3id.org/np/RAukAcWHRDlkqxk7H2XNSegc1WnHI569INvNr-xdptDGI";
74
    public static final String LICENSE_PUB_INFO_TEMPLATE = "https://w3id.org/np/RACJ58Gvyn91LqCKIO9zu1eijDQIeEff28iyDrJgjSJF8";
75
    public static final String DEFAULT_PROV_TEMPLATE = "https://w3id.org/np/RA7lSq6MuK_TIC6JMSHvLtee3lpLoZDOqLJCLXevnrPoU";
76
    private static final String supersedesPubInfoTemplateId = "https://w3id.org/np/RAoTD7udB2KtUuOuAe74tJi1t3VzK0DyWS7rYVAq1GRvw";
77
    private static final String derivesFromPubInfoTemplateId = "https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ";
78

79
    private static final String[] fixedPubInfoTemplates = new String[]{CREATOR_PUB_INFO_TEMPLATE, LICENSE_PUB_INFO_TEMPLATE};
×
80

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

399
        });
400

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

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

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

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

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

479
            @Override
480
            protected void onValidate() {
481
                super.onValidate();
×
482
                for (Component fc : assertionContext.getComponents()) {
×
483
                    processFeedback(fc);
×
484
                }
×
485
                for (Component fc : provenanceContext.getComponents()) {
×
486
                    processFeedback(fc);
×
487
                }
×
488
                for (TemplateContext c : pubInfoContexts) {
×
489
                    for (Component fc : c.getComponents()) {
×
490
                        processFeedback(fc);
×
491
                    }
×
492
                }
×
493
            }
×
494

495
            private void processFeedback(Component c) {
496
                if (c instanceof FormComponent) {
×
497
                    ((FormComponent<?>) c).processInput();
×
498
                }
499
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
500
                    form.getFeedbackMessages().add(fm);
×
501
                }
×
502
            }
×
503

504
        };
505
        form.setOutputMarkupId(true);
×
506

507
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
508

509
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
510
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
511
        String description = assertionContext.getTemplate().getLabel();
×
512
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
513

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

516
            protected void populateItem(ListItem<StatementItem> item) {
517
                item.add(item.getModelObject());
×
518
            }
×
519

520
        });
521

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

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

562
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
563

564
            @Override
565
            public String getDisplayValue(String object) {
566
                if (object == null || object.isEmpty()) return "";
×
567
                Template t = td.getTemplate(object);
×
568
                if (t != null) return t.getLabel();
×
569
                return object;
×
570
            }
571

572
            @Override
573
            public String getIdValue(String object) {
574
                return object;
×
575
            }
576

577
            // Getting strange errors with Tomcat if this method is not overridden:
578
            @Override
579
            public void detach() {
580
            }
×
581

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

615
            @Override
616
            public Collection<String> toChoices(Collection<String> ids) {
617
                return ids;
×
618
            }
619

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

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

640
        });
641
        form.add(prTemplateChoice);
×
642
        refreshProvenance(null);
×
643

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

662
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
663
            String tid = entry.get("np");
×
664
            if (handledPiTemplates.containsKey(tid)) continue;
×
665
            piTemplateOptionIds.add(tid);
×
666
            handledPiTemplates.put(tid, true);
×
667
        }
×
668

669
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
670

671
            @Override
672
            public String getDisplayValue(String object) {
673
                if (object == null || object.isEmpty()) return "";
×
674
                Template t = td.getTemplate(object);
×
675
                if (t != null) return t.getLabel();
×
676
                return object;
×
677
            }
678

679
            @Override
680
            public String getIdValue(String object) {
681
                return object;
×
682
            }
683

684
            // Getting strange errors with Tomcat if this method is not overridden:
685
            @Override
686
            public void detach() {
687
            }
×
688

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

729
            @Override
730
            public Collection<String> toChoices(Collection<String> ids) {
731
                return ids;
×
732
            }
733

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

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

757
        });
758
        form.add(piTemplateChoice);
×
759
        refreshPubInfo(null);
×
760

761
        form.add(consentCheck);
×
762

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

787
        add(form);
×
788

789
        feedbackPanel = new FeedbackPanel("feedback");
×
790
        feedbackPanel.setOutputMarkupId(true);
×
791
        add(feedbackPanel);
×
792
    }
×
793

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

804
            protected void populateItem(ListItem<StatementItem> item) {
805
                item.add(item.getModelObject());
×
806
            }
×
807

808
        };
809
        list.setOutputMarkupId(true);
×
810
        form.add(list);
×
811
    }
×
812

813
    private void refreshPubInfo(AjaxRequestTarget target) {
814
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
815

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

824
                    @Override
825
                    protected void onEvent(AjaxRequestTarget target) {
826
                        pubInfoContexts.remove(pic);
×
827
                        target.add(PublishForm.this);
×
828
                        target.appendJavaScript("updateElements();");
×
829
                    }
×
830

831
                });
832
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
833
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
834

835
                    protected void populateItem(ListItem<StatementItem> item) {
836
                        item.add(item.getModelObject());
×
837
                    }
×
838

839
                });
840
            }
×
841

842
        };
843
        list.setOutputMarkupId(true);
×
844
        if (target == null) {
×
845
            form.add(list);
×
846
        } else {
847
            form.remove("pis");
×
848
            form.add(list);
×
849
            target.add(form);
×
850
            target.appendJavaScript("updateElements();");
×
851
        }
852
    }
×
853

854
    private TemplateContext createPubInfoContext(String piTemplateId) {
855
        TemplateContext c;
856
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
857
            c = pubInfoContextMap.get(piTemplateId);
×
858
        } else {
859
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
860
            pubInfoContextMap.put(piTemplateId, c);
×
861
            pubInfoContexts.add(c);
×
862
        }
863
        return c;
×
864
    }
865

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

911
    private String getNanopubLabel(NanopubCreator npCreator) {
912
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
913

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

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

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

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

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