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

knowledgepixels / nanodash / 27622721129

16 Jun 2026 01:55PM UTC coverage: 26.963% (+6.3%) from 20.697%
27622721129

Pull #483

github

web-flow
Merge 73a4d0fe1 into 663f14f46
Pull Request #483: Space/resource About pages, ref-aware spaces, and magic query params

1542 of 6717 branches covered (22.96%)

Branch coverage included in aggregate %.

3407 of 11638 relevant lines covered (29.27%)

4.31 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

298
        final Nanopub improveNp;
299
        if (!pageParams.get("improve").isNull()) {
×
300
            improveNp = Utils.getNanopub(pageParams.get("improve").toString());
×
301
        } else {
302
            improveNp = null;
×
303
        }
304

305
        // Propagate fill source (supersede/derive/improve) so contexts can resolve
306
        // the `local:nanopub`/`local:assertion` sentinels to the fill nanopub's URIs.
307
        Nanopub fillSource = fillNp != null ? fillNp : improveNp;
×
308
        if (fillSource != null) {
×
309
            assertionContext.setFillSource(fillSource);
×
310
            provenanceContext.setFillSource(fillSource);
×
311
            for (TemplateContext c : pubInfoContexts) {
×
312
                c.setFillSource(fillSource);
×
313
            }
×
314
        }
315

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

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

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

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

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

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

402
        });
403
        add(new DataView<Statement>("unused-prstatements", new ListDataProvider<Statement>(unusedPrStatementList)) {
×
404

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

410
        });
411
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
412

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

418
        });
419

420
        // Finalize statements, which picks up parameter values in repetitions:
421
        assertionContext.finalizeStatements();
×
422
        provenanceContext.finalizeStatements();
×
423
        for (TemplateContext c : pubInfoContexts) {
×
424
            c.finalizeStatements();
×
425
        }
×
426

427
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
428
        consentCheck.add(new InvalidityHighlighting());
×
429

430
        form = new Form<Void>("form") {
×
431

432
            @Override
433
            protected void onConfigure() {
434
                super.onConfigure();
×
435
                form.getFeedbackMessages().clear();
×
436
//                                formComponents.clear();
437
            }
×
438

439
            protected void onSubmit() {
440
                if (!Boolean.TRUE.equals(consentCheck.getModelObject())) {
×
441
                    feedbackPanel.error("You need to check the checkbox that you understand the consequences.");
×
442
                    return;
×
443
                }
444
                logger.info("Publish form submitted");
×
445
                Nanopub signedNp;
446
                try {
447
                    Nanopub np = createNanopub();
×
448
                    logger.info("Nanopublication created: {}", np.getUri());
×
449
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
450
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
451
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
452
                    String npUrl = PublishNanopub.publish(signedNp);
×
453
                    logger.info("Nanopublication published: {}", npUrl);
×
454
                    Utils.cacheNanopub(signedNp);
×
455
                } catch (Exception ex) {
×
456
                    signedNp = null;
×
457
                    logger.error("Nanopublication publishing failed: {}", ex.getMessage());
×
458
                    String message = ex.getClass().getName();
×
459
                    if (ex.getMessage() != null) {
×
460
                        message = ex.getMessage();
×
461
                    }
462
                    feedbackPanel.error(message);
×
463
                }
×
464
                if (signedNp != null) {
×
465
                    String toRefresh = pageParams.get("refresh-upon-publish").toString("");
×
466
                    if (!toRefresh.isEmpty()) {
×
467
                        WicketApplication.get().notifyNanopubPublished(signedNp, toRefresh, 5 * 1000);
×
468
                    }
469
                    String contextId = pageParams.get("context").toString("");
×
470
                    // Broaden the refresh: also force-refresh the context resource's own
471
                    // data (e.g. a space's roles/members) so the page we redirect to —
472
                    // typically its Content tab — reflects the just-published change, not
473
                    // only the specific view query that was acted on.
474
                    if (!contextId.isEmpty() && !contextId.equals(toRefresh)
×
475
                            && AbstractResourceWithProfile.isResourceWithProfile(contextId)) {
×
476
                        WicketApplication.get().notifyNanopubPublished(signedNp, contextId, 5 * 1000);
×
477
                    }
478
                    String partId = pageParams.get("part").toString("");
×
479
                    if (!contextId.isEmpty() && pageParams.get("postpub-redirect-url").isEmpty()) {
×
480
                        PageParameters redirectParams = new PageParameters().set("just-published", signedNp.getUri().stringValue());
×
481
                        if (!partId.isEmpty()) {
×
482
                            // User was on a part page (e.g. paper collection); redirect back to the part page
483
                            redirectParams.set("id", partId).set("context", contextId);
×
484
                            throw new RestartResponseException(ResourcePartPage.class, redirectParams);
×
485
                        }
486
                        redirectParams.set("id", contextId);
×
487
                        // Return to the tab the action asked for (e.g. "about" for a
488
                        // space's About-tab role actions); default is the Content tab.
489
                        String postpubTab = pageParams.get("postpub-tab").toString("");
×
490
                        if (!postpubTab.isEmpty()) redirectParams.set("tab", postpubTab);
×
491
                        if (SpaceRepository.get().findById(contextId) != null) {
×
492
                            throw new RestartResponseException(SpacePage.class, redirectParams);
×
493
                        }
494
                        if (MaintainedResourceRepository.get().findById(contextId) != null) {
×
495
                            throw new RestartResponseException(MaintainedResourcePage.class, redirectParams);
×
496
                        }
497
                        if (IndividualAgent.isUser(contextId)) {
×
498
                            throw new RestartResponseException(UserPage.class, redirectParams);
×
499
                        }
500
                    }
501
                    NanodashPage confirmPage = getConfirmPage(signedNp, pageParams);
×
502
                    if (confirmPage != null) {
×
503
                        throw new RestartResponseException(confirmPage);
×
504
                    }
505
                    throw new RestartResponseException(ExplorePage.class,
×
506
                            new PageParameters(pageParams).set("id", signedNp.getUri().stringValue()));
×
507
                }
508
            }
×
509

510
            @Override
511
            protected void onValidate() {
512
                super.onValidate();
×
513
                for (Component fc : assertionContext.getComponents()) {
×
514
                    processFeedback(fc);
×
515
                }
×
516
                for (Component fc : provenanceContext.getComponents()) {
×
517
                    processFeedback(fc);
×
518
                }
×
519
                for (TemplateContext c : pubInfoContexts) {
×
520
                    for (Component fc : c.getComponents()) {
×
521
                        processFeedback(fc);
×
522
                    }
×
523
                }
×
524
            }
×
525

526
            private void processFeedback(Component c) {
527
                if (c instanceof FormComponent) {
×
528
                    ((FormComponent<?>) c).processInput();
×
529
                }
530
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
531
                    form.getFeedbackMessages().add(fm);
×
532
                }
×
533
            }
×
534

535
        };
536
        form.setOutputMarkupId(true);
×
537

538
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
539

540
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
541
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
542
        String description = assertionContext.getTemplate().getLabel();
×
543
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
544

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

547
            protected void populateItem(ListItem<StatementItem> item) {
548
                item.add(item.getModelObject());
×
549
            }
×
550

551
        });
552

553
        final Map<String, Boolean> handledProvTemplates = new HashMap<>();
×
554
        final String defaultProvTemplateId;
555
        if (assertionContext.getTemplate().getDefaultProvenance() != null) {
×
556
            defaultProvTemplateId = assertionContext.getTemplate().getDefaultProvenance().stringValue();
×
557
            handledProvTemplates.put(defaultProvTemplateId, true);
×
558
        } else {
559
            defaultProvTemplateId = null;
×
560
        }
561
        final List<String> recommendedProvTemplateOptionIds = new ArrayList<>();
×
562
        final List<String> provTemplateOptionIds = new ArrayList<>();
×
563
        if (pageParams.get("prtemplate-options").isNull()) {
×
564
            // TODO Make this dynamic and consider updated templates:
565
            recommendedProvTemplateOptionIds.add(DEFAULT_PROV_TEMPLATE);
×
566
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAcTpoh5Ra0ssqmcpOgWdaZ_YiPE6demO6cpw-2RvSNs8");
×
567
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA4LGtuOqTIMqVAkjnfBXk1YDcAPNadP5CGiaJiBkdHCQ");
×
568
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAl_-VTw9Re_uRF8r8y0rjlfnu7FlhTa8xg_8xkcweqiE");
×
569
            recommendedProvTemplateOptionIds.add("https://w3id.org/np/RASORV2mMEVpS4lWh2bwUTEcV-RWjbD9RPbN7J0PIeYAU");
×
570
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAjkBbM5yQm7hKH1l_Jk3HAUqWi3Bd57TPmAOZCsZmi_M");
×
571
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAGXx_k9eQMnXaCbsXMsJbGClwZtQEGNg0GVJu6amdAVw");
×
572
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA1fnITI3Pu1UQ0CHghNpys3JwQrM32LBnjmDLoayp9-4");
×
573
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAJgbsGeGdTG-zq_gU0TLw4s3raMgoRk-mPlc2DSLXvE0");
×
574
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA6SXfhUY-xeblZU8HhPddw6tsu-C5NXevG6C_zv4bMxU");
×
575
            for (String s : recommendedProvTemplateOptionIds) {
×
576
                handledProvTemplates.put(s, true);
×
577
            }
×
578

579
            for (ApiResponseEntry t : td.getProvenanceTemplates()) {
×
580
                String tid = t.get("np");
×
581
                if (handledProvTemplates.containsKey(tid)) continue;
×
582
                provTemplateOptionIds.add(tid);
×
583
                handledProvTemplates.put(tid, true);
×
584
            }
×
585
        } else {
586
            for (String s : pageParams.get("prtemplate-options").toString().split(" ")) {
×
587
                if (handledProvTemplates.containsKey(s)) continue;
×
588
                recommendedProvTemplateOptionIds.add(s);
×
589
                handledProvTemplates.put(s, true);
×
590
            }
591
        }
592

593
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
594

595
            @Override
596
            public String getDisplayValue(String object) {
597
                if (object == null || object.isEmpty()) return "";
×
598
                Template t = td.getTemplate(object);
×
599
                if (t != null) return t.getLabel();
×
600
                return object;
×
601
            }
602

603
            @Override
604
            public String getIdValue(String object) {
605
                return object;
×
606
            }
607

608
            // Getting strange errors with Tomcat if this method is not overridden:
609
            @Override
610
            public void detach() {
611
            }
×
612

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

646
            @Override
647
            public Collection<String> toChoices(Collection<String> ids) {
648
                return ids;
×
649
            }
650

651
        };
652
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
653
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
654
        prTemplateChoice.setRequired(true);
×
655
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
656
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
657

658
            @Override
659
            protected void onUpdate(AjaxRequestTarget target) {
660
                String o = prTemplateModel.getObject();
×
661
                if (o.startsWith("——")) {
×
662
                    o = provenanceContext.getTemplate().getId();
×
663
                    prTemplateModel.setObject(o);
×
664
                }
665
                provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateModel.getObject(), "pr-statement", targetNamespace);
×
666
                provenanceContext.initStatements();
×
667
                refreshProvenance(target);
×
668
                provenanceContext.finalizeStatements();
×
669
            }
×
670

671
        });
672
        form.add(prTemplateChoice);
×
673
        refreshProvenance(null);
×
674

675
        final Map<String, Boolean> handledPiTemplates = new HashMap<>();
×
676
        final List<String> recommendedPiTemplateOptionIds = new ArrayList<>();
×
677
        final List<String> piTemplateOptionIds = new ArrayList<>();
×
678
        // TODO Make this dynamic and consider updated templates:
679
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAXflINqt3smqxV5Aq7E9lzje4uLdkKIOefa6Bp8oJ8CY");
×
680
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ");
×
681
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RA16U9Wo30ObhrK1NzH7EsmVRiRtvEuEA_Dfc-u8WkUCA");
×
682
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAdyqI6k07V5nAS82C6hvIDtNWk179EIV4DV-sLbOFKg4");
×
683
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RAjvEpLZUE7rMoa8q6mWSsN6utJDp-5FmgO47YGsbgw3w");
×
684
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAxuGRKID6yNg63V5Mf0ot2NjncOnodh-mkN3qT_1txGI");
×
685
        for (TemplateContext c : pubInfoContexts) {
×
686
            String s = c.getTemplate().getId();
×
687
            handledPiTemplates.put(s, true);
×
688
        }
×
689
        for (String s : recommendedPiTemplateOptionIds) {
×
690
            handledPiTemplates.put(s, true);
×
691
        }
×
692

693
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
694
            String tid = entry.get("np");
×
695
            if (handledPiTemplates.containsKey(tid)) continue;
×
696
            piTemplateOptionIds.add(tid);
×
697
            handledPiTemplates.put(tid, true);
×
698
        }
×
699

700
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
701

702
            @Override
703
            public String getDisplayValue(String object) {
704
                if (object == null || object.isEmpty()) return "";
×
705
                Template t = td.getTemplate(object);
×
706
                if (t != null) return t.getLabel();
×
707
                return object;
×
708
            }
709

710
            @Override
711
            public String getIdValue(String object) {
712
                return object;
×
713
            }
714

715
            // Getting strange errors with Tomcat if this method is not overridden:
716
            @Override
717
            public void detach() {
718
            }
×
719

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

760
            @Override
761
            public Collection<String> toChoices(Collection<String> ids) {
762
                return ids;
×
763
            }
764

765
        };
766
        final IModel<String> newPiTemplateModel = Model.of();
×
767
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
768
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
769
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
770
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
771

772
            @Override
773
            protected void onUpdate(AjaxRequestTarget target) {
774
                if (newPiTemplateModel.getObject().startsWith("——")) {
×
775
                    newPiTemplateModel.setObject(null);
×
776
                    refreshPubInfo(target);
×
777
                    return;
×
778
                }
779
                String id = newPiTemplateModel.getObject();
×
780
                TemplateContext c = new TemplateContext(ContextType.PUBINFO, id, "pi-statement", targetNamespace);
×
781
                c.initStatements();
×
782
                pubInfoContexts.add(c);
×
783
                newPiTemplateModel.setObject(null);
×
784
                refreshPubInfo(target);
×
785
                c.finalizeStatements();
×
786
            }
×
787

788
        });
789
        form.add(piTemplateChoice);
×
790
        refreshPubInfo(null);
×
791

792
        form.add(consentCheck);
×
793

794
        form.add(new Button("preview-button") {
×
795
            @Override
796
            public void onSubmit() {
797
                try {
798
                    Nanopub np = createNanopub();
×
799
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
800
                    Nanopub signedNp = SignNanopub.signAndTransform(np, tc);
×
801
                    String previewId = signedNp.getUri().stringValue();
×
802
                    NanodashSession.get().setPreviewNanopub(previewId,
×
803
                            new NanodashSession.PreviewNanopub(signedNp, pageParams, confirmPageClass, Boolean.TRUE.equals(consentCheck.getModelObject()), getPage().getPageReference()));
×
804
                    throw new RestartResponseException(PreviewPage.class, new PageParameters().set("id", previewId));
×
805
                } catch (RestartResponseException ex) {
×
806
                    throw ex;
×
807
                } catch (Exception ex) {
×
808
                    logger.error("Preview failed: {}", ex.getMessage());
×
809
                    String message = ex.getClass().getName();
×
810
                    if (ex.getMessage() != null) {
×
811
                        message = ex.getMessage();
×
812
                    }
813
                    feedbackPanel.error(message);
×
814
                }
815
            }
×
816
        });
817

818
        add(form);
×
819

820
        feedbackPanel = new FeedbackPanel("feedback");
×
821
        feedbackPanel.setOutputMarkupId(true);
×
822
        add(feedbackPanel);
×
823
    }
×
824

825
    private void refreshProvenance(AjaxRequestTarget target) {
826
        if (target != null) {
×
827
            form.remove("prtemplatelink");
×
828
            form.remove("pr-statements");
×
829
            target.add(form);
×
830
            target.appendJavaScript("updateElements();");
×
831
        }
832
        form.add(new BookmarkablePageLink<Void>("prtemplatelink", ExplorePage.class, new PageParameters().set("id", provenanceContext.getTemplate().getId())));
×
833
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
834

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

839
        };
840
        list.setOutputMarkupId(true);
×
841
        form.add(list);
×
842
    }
×
843

844
    private void refreshPubInfo(AjaxRequestTarget target) {
845
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
846

847
            protected void populateItem(ListItem<TemplateContext> item) {
848
                final TemplateContext pic = item.getModelObject();
×
849
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
850
                item.add(new BookmarkablePageLink<Void>("pitemplatelink", ExplorePage.class, new PageParameters().set("id", pic.getTemplate().getId())));
×
851
                Label remove = new Label("piremove", "×");
×
852
                item.add(remove);
×
853
                remove.add(new AjaxEventBehavior("click") {
×
854

855
                    @Override
856
                    protected void onEvent(AjaxRequestTarget target) {
857
                        pubInfoContexts.remove(pic);
×
858
                        target.add(PublishForm.this);
×
859
                        target.appendJavaScript("updateElements();");
×
860
                    }
×
861

862
                });
863
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
864
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
865

866
                    protected void populateItem(ListItem<StatementItem> item) {
867
                        item.add(item.getModelObject());
×
868
                    }
×
869

870
                });
871
            }
×
872

873
        };
874
        list.setOutputMarkupId(true);
×
875
        if (target == null) {
×
876
            form.add(list);
×
877
        } else {
878
            form.remove("pis");
×
879
            form.add(list);
×
880
            target.add(form);
×
881
            target.appendJavaScript("updateElements();");
×
882
        }
883
    }
×
884

885
    private TemplateContext createPubInfoContext(String piTemplateId) {
886
        TemplateContext c;
887
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
888
            c = pubInfoContextMap.get(piTemplateId);
×
889
        } else {
890
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
891
            pubInfoContextMap.put(piTemplateId, c);
×
892
            pubInfoContexts.add(c);
×
893
        }
894
        return c;
×
895
    }
896

897
    private synchronized Nanopub createNanopub() throws MalformedNanopubException, NanopubAlreadyFinalizedException {
898
        assertionContext.getIntroducedIris().clear();
×
899
        NanopubCreator npCreator = new NanopubCreator(targetNamespace);
×
900
        npCreator.setAssertionUri(vf.createIRI(targetNamespace + "assertion"));
×
901
        assertionContext.propagateStatements(npCreator);
×
902
        provenanceContext.propagateStatements(npCreator);
×
903
        for (TemplateContext c : pubInfoContexts) {
×
904
            c.propagateStatements(npCreator);
×
905
        }
×
906
        for (IRI introducedIri : assertionContext.getIntroducedIris()) {
×
907
            npCreator.addPubinfoStatement(NPX.INTRODUCES, introducedIri);
×
908
        }
×
909
        for (IRI embeddedIri : assertionContext.getEmbeddedIris()) {
×
910
            npCreator.addPubinfoStatement(NPX.EMBEDS, embeddedIri);
×
911
        }
×
912
        npCreator.addNamespace("this", targetNamespace);
×
913
        npCreator.addNamespace("sub", targetNamespace + "/");
×
914
        npCreator.addTimestampNow();
×
915
        IRI templateUri = assertionContext.getTemplate().getNanopub().getUri();
×
916
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_TEMPLATE, templateUri);
×
917
        IRI prTemplateUri = provenanceContext.getTemplate().getNanopub().getUri();
×
918
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PROVENANCE_TEMPLATE, prTemplateUri);
×
919
        for (TemplateContext c : pubInfoContexts) {
×
920
            IRI piTemplateUri = c.getTemplate().getNanopub().getUri();
×
921
            npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PUBINFO_TEMPLATE, piTemplateUri);
×
922
        }
×
923
        String nanopubLabel = getNanopubLabel(npCreator);
×
924
        if (nanopubLabel != null) {
×
925
            npCreator.addPubinfoStatement(RDFS.LABEL, vf.createLiteral(nanopubLabel));
×
926
        }
927
        for (IRI type : assertionContext.getTemplate().getTargetNanopubTypes()) {
×
928
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, type);
×
929
        }
×
930
        IRI userIri = NanodashSession.get().getUserIri();
×
931
        if (User.getName(userIri) != null) {
×
932
            npCreator.addPubinfoStatement(userIri, FOAF.NAME, vf.createLiteral(User.getName(userIri)));
×
933
            npCreator.addNamespace("foaf", FOAF.NAMESPACE);
×
934
        }
935
        String websiteUrl = NanodashPreferences.get().getWebsiteUrl();
×
936
        if (websiteUrl != null) {
×
937
            npCreator.addPubinfoStatement(NPX.WAS_CREATED_AT, vf.createIRI(websiteUrl));
×
938
        }
939
        return npCreator.finalizeNanopub();
×
940
    }
941

942
    private String getNanopubLabel(NanopubCreator npCreator) {
943
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
944

945
        Map<IRI, String> labelMap = new HashMap<>();
×
946
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
947
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
948
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
949
            }
950
        }
×
951

952
        String nanopubLabel = assertionContext.getTemplate().getNanopubLabelPattern();
×
953
        while (nanopubLabel.matches(".*\\$\\{[_a-zA-Z0-9-]+\\}.*")) {
×
954
            String placeholderPostfix = nanopubLabel.replaceFirst("^.*\\$\\{([_a-zA-Z0-9-]+)\\}.*$", "$1");
×
955
            IRI placeholderIriHash = vf.createIRI(assertionContext.getTemplateId() + "#" + placeholderPostfix);
×
956
            IRI placeholderIriSlash = vf.createIRI(assertionContext.getTemplateId() + "/" + placeholderPostfix);
×
957
            IRI placeholderIri;
958
            String placeholderValue = "";
×
959
            if (assertionContext.getComponentModels().get(placeholderIriSlash) != null) {
×
960
                placeholderIri = placeholderIriSlash;
×
961
            } else {
962
                placeholderIri = placeholderIriHash;
×
963
            }
964
            IModel<String> m = (IModel<String>) assertionContext.getComponentModels().get(placeholderIri);
×
965
            if (m != null) placeholderValue = m.orElse("").getObject();
×
966
            if (placeholderValue == null) placeholderValue = "";
×
967
            String placeholderLabel = placeholderValue;
×
968
            if (assertionContext.getTemplate().isUriPlaceholder(placeholderIri)) {
×
969
                try {
970
                    // TODO Fix this. It doesn't work for placeholders with auto-encode placeholders, etc.
971
                    //      Not sure we need labels for these, but this code should be improved anyway.
972
                    String prefix = assertionContext.getTemplate().getPrefix(placeholderIri);
×
973
                    if (prefix != null) placeholderValue = prefix + placeholderValue;
×
974
                    IRI placeholderValueIri = vf.createIRI(placeholderValue);
×
975
                    String l = assertionContext.getTemplate().getLabel(placeholderValueIri);
×
976
                    if (labelMap.containsKey(placeholderValueIri)) {
×
977
                        l = labelMap.get(placeholderValueIri);
×
978
                    }
979
                    if (l == null) l = GuidedChoiceItem.getLabel(placeholderValue);
×
980
                    if (assertionContext.getTemplate().isAgentPlaceholder(placeholderIri) && !placeholderValue.isEmpty()) {
×
981
                        l = User.getName(vf.createIRI(placeholderValue));
×
982
                    }
983
                    if (l != null && !l.isEmpty()) {
×
984
                        placeholderLabel = l.replaceFirst(" - .*$", "");
×
985
                    } else {
986
                        placeholderLabel = Utils.getShortNameFromURI(placeholderValueIri);
×
987
                    }
988
                } catch (Exception ex) {
×
989
                    logger.error("Nanopub label placeholder IRI error: {}", ex.getMessage());
×
990
                }
×
991
            }
992
            placeholderLabel = placeholderLabel.replaceAll("\\s+", " ");
×
993
            if (placeholderLabel.length() > 100) placeholderLabel = placeholderLabel.substring(0, 97) + "...";
×
994
            nanopubLabel = Strings.CS.replace(nanopubLabel, "${" + placeholderPostfix + "}", placeholderLabel);
×
995
        }
×
996
        return nanopubLabel;
×
997
    }
998

999
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
1000
        try {
1001
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
1002
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
1003
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
1004
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
1005
        }
1006
        return null;
×
1007
    }
1008

1009
    /**
1010
     * Returns a hint whether the form is stateless or not.
1011
     *
1012
     * @return false if the form is stateful, true if it is stateless.
1013
     */
1014
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
1015
    // if the user browses other pages in parallel:
1016
    protected boolean getStatelessHint() {
1017
        return false;
×
1018
    }
1019

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