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

knowledgepixels / nanodash / 24785731352

22 Apr 2026 03:01PM UTC coverage: 17.46% (-0.005%) from 17.465%
24785731352

Pull #449

github

web-flow
Merge e4d6d022c into c9b9c0de8
Pull Request #449: refactor: drop formobj, use PageReference for preview Back

899 of 6188 branches covered (14.53%)

Branch coverage included in aggregate %.

2156 of 11309 relevant lines covered (19.06%)

2.64 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.behavior.AttributeAppender;
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 {
×
86
        /**
87
         * Use fill mode
88
         */
89
        USE,
×
90
        /**
91
         * Supersede fill mode
92
         */
93
        SUPERSEDE,
×
94
        /**
95
         * Derive fill mode
96
         */
97
        DERIVE
×
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
    private final String formObjId = Long.toString(Math.abs(new java.util.Random().nextLong()));
×
110

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

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

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

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

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

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

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

299
        // Init statements only now, in order to pick up parameter values:
300
        assertionContext.initStatements();
×
301
        provenanceContext.initStatements();
×
302
        for (TemplateContext c : pubInfoContexts) {
×
303
            c.initStatements();
×
304
        }
×
305

306
        String latestAssertionId = QueryApiAccess.getLatestVersionId(assertionContext.getTemplateId());
×
307
        if (!assertionContext.getTemplateId().equals(latestAssertionId)) {
×
308
            add(new Label("newversion", "There is a new version of this assertion template:"));
×
309
            PageParameters params = new PageParameters(pageParams);
×
310
            params.set("template", latestAssertionId);
×
311
            add(new BookmarkablePageLink<Void>("newversionlink", publishPageClass, params));
×
312
            if ("latest".equals(pageParams.get("template-version").toString())) {
×
313
                throw new RestartResponseException(publishPageClass, params);
×
314
            }
315
        } else {
×
316
            add(new Label("newversion", "").setVisible(false));
×
317
            add(new Label("newversionlink", "").setVisible(false));
×
318
        }
319

320
        final Nanopub improveNp;
321
        if (!pageParams.get("improve").isNull()) {
×
322
            improveNp = Utils.getNanopub(pageParams.get("improve").toString());
×
323
        } else {
324
            improveNp = null;
×
325
        }
326

327
        final List<Statement> unusedStatementList = new ArrayList<>();
×
328
        final List<Statement> unusedPrStatementList = new ArrayList<>();
×
329
        final List<Statement> unusedPiStatementList = new ArrayList<>();
×
330
        if (fillNp != null) {
×
331
            ValueFiller filler = new ValueFiller(fillNp, ContextType.ASSERTION, true, fillMode);
×
332
            filler.fill(assertionContext);
×
333
            unusedStatementList.addAll(filler.getUnusedStatements());
×
334

335
            if (!fillOnlyAssertion) {
×
336
                ValueFiller prFiller = new ValueFiller(fillNp, ContextType.PROVENANCE, true);
×
337
                prFiller.fill(provenanceContext);
×
338
                unusedPrStatementList.addAll(prFiller.getUnusedStatements());
×
339

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

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

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

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

399
        });
400
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
401

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

407
        });
408

409
        // Finalize statements, which picks up parameter values in repetitions:
410
        assertionContext.finalizeStatements();
×
411
        provenanceContext.finalizeStatements();
×
412
        for (TemplateContext c : pubInfoContexts) {
×
413
            c.finalizeStatements();
×
414
        }
×
415

416
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
417
        consentCheck.add(new InvalidityHighlighting());
×
418

419
        form = new Form<Void>("form") {
×
420

421
            @Override
422
            protected void onConfigure() {
423
                super.onConfigure();
×
424
                form.getFeedbackMessages().clear();
×
425
//                                formComponents.clear();
426
            }
×
427

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

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

503
            private void processFeedback(Component c) {
504
                if (c instanceof FormComponent) {
×
505
                    ((FormComponent<?>) c).processInput();
×
506
                }
507
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
508
                    form.getFeedbackMessages().add(fm);
×
509
                }
×
510
            }
×
511

512
        };
513
        form.setOutputMarkupId(true);
×
514

515
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
516

517
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
518
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
519
        String description = assertionContext.getTemplate().getLabel();
×
520
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
521

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

524
            protected void populateItem(ListItem<StatementItem> item) {
525
                item.add(item.getModelObject());
×
526
            }
×
527

528
        });
529

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

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

570
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
571

572
            @Override
573
            public String getDisplayValue(String object) {
574
                if (object == null || object.isEmpty()) return "";
×
575
                Template t = td.getTemplate(object);
×
576
                if (t != null) return t.getLabel();
×
577
                return object;
×
578
            }
579

580
            @Override
581
            public String getIdValue(String object) {
582
                return object;
×
583
            }
584

585
            // Getting strange errors with Tomcat if this method is not overridden:
586
            @Override
587
            public void detach() {
588
            }
×
589

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

623
            @Override
624
            public Collection<String> toChoices(Collection<String> ids) {
625
                return ids;
×
626
            }
627

628
        };
629
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
630
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
631
        prTemplateChoice.setRequired(true);
×
632
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
633
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
634

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

648
        });
649
        form.add(prTemplateChoice);
×
650
        refreshProvenance(null);
×
651

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

670
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
671
            String tid = entry.get("np");
×
672
            if (handledPiTemplates.containsKey(tid)) continue;
×
673
            piTemplateOptionIds.add(tid);
×
674
            handledPiTemplates.put(tid, true);
×
675
        }
×
676

677
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
678

679
            @Override
680
            public String getDisplayValue(String object) {
681
                if (object == null || object.isEmpty()) return "";
×
682
                Template t = td.getTemplate(object);
×
683
                if (t != null) return t.getLabel();
×
684
                return object;
×
685
            }
686

687
            @Override
688
            public String getIdValue(String object) {
689
                return object;
×
690
            }
691

692
            // Getting strange errors with Tomcat if this method is not overridden:
693
            @Override
694
            public void detach() {
695
            }
×
696

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

737
            @Override
738
            public Collection<String> toChoices(Collection<String> ids) {
739
                return ids;
×
740
            }
741

742
        };
743
        final IModel<String> newPiTemplateModel = Model.of();
×
744
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
745
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
746
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
747
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
748

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

765
        });
766
        form.add(piTemplateChoice);
×
767
        refreshPubInfo(null);
×
768

769
        form.add(consentCheck);
×
770

771
        Button previewButton = new Button("preview-button") {
×
772
            @Override
773
            public void onSubmit() {
774
                try {
775
                    Nanopub np = createNanopub();
×
776
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
777
                    Nanopub signedNp = SignNanopub.signAndTransform(np, tc);
×
778
                    String previewId = signedNp.getUri().stringValue();
×
779
                    NanodashSession.get().setFormPageRef(formObjId, getPage().getPageReference());
×
780
                    NanodashSession.get().setPreviewNanopub(previewId,
×
781
                            new NanodashSession.PreviewNanopub(signedNp, pageParams, confirmPageClass, Boolean.TRUE.equals(consentCheck.getModelObject()), formObjId));
×
782
                    throw new RestartResponseException(PreviewPage.class, new PageParameters().set("id", previewId));
×
783
                } catch (RestartResponseException ex) {
×
784
                    throw ex;
×
785
                } catch (Exception ex) {
×
786
                    logger.error("Preview failed: {}", ex.getMessage());
×
787
                    String message = ex.getClass().getName();
×
788
                    if (ex.getMessage() != null) {
×
789
                        message = ex.getMessage();
×
790
                    }
791
                    feedbackPanel.error(message);
×
792
                }
793
            }
×
794
        };
795
        // Inject formobj into the current URL via history.replaceState *before* the
796
        // form submits, so that on browser-back from the preview, the resulting
797
        // /publish?...&formobj=Y request can recover this page from the page store.
798
        previewButton.add(AttributeAppender.replace("onclick",
×
799
                "try{var u=new URL(window.location);u.searchParams.set('formobj','" + formObjId + "');history.replaceState(null,'',u);}catch(e){}"));
800
        form.add(previewButton);
×
801

802
        add(form);
×
803

804
        feedbackPanel = new FeedbackPanel("feedback");
×
805
        feedbackPanel.setOutputMarkupId(true);
×
806
        add(feedbackPanel);
×
807
    }
×
808

809
    private void refreshProvenance(AjaxRequestTarget target) {
810
        if (target != null) {
×
811
            form.remove("prtemplatelink");
×
812
            form.remove("pr-statements");
×
813
            target.add(form);
×
814
            target.appendJavaScript("updateElements();");
×
815
        }
816
        form.add(new BookmarkablePageLink<Void>("prtemplatelink", ExplorePage.class, new PageParameters().set("id", provenanceContext.getTemplate().getId())));
×
817
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
818

819
            protected void populateItem(ListItem<StatementItem> item) {
820
                item.add(item.getModelObject());
×
821
            }
×
822

823
        };
824
        list.setOutputMarkupId(true);
×
825
        form.add(list);
×
826
    }
×
827

828
    private void refreshPubInfo(AjaxRequestTarget target) {
829
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
830

831
            protected void populateItem(ListItem<TemplateContext> item) {
832
                final TemplateContext pic = item.getModelObject();
×
833
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
834
                item.add(new BookmarkablePageLink<Void>("pitemplatelink", ExplorePage.class, new PageParameters().set("id", pic.getTemplate().getId())));
×
835
                Label remove = new Label("piremove", "×");
×
836
                item.add(remove);
×
837
                remove.add(new AjaxEventBehavior("click") {
×
838

839
                    @Override
840
                    protected void onEvent(AjaxRequestTarget target) {
841
                        pubInfoContexts.remove(pic);
×
842
                        target.add(PublishForm.this);
×
843
                        target.appendJavaScript("updateElements();");
×
844
                    }
×
845

846
                });
847
                if (requiredPubInfoContexts.contains(pic)) remove.setVisible(false);
×
848
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
849

850
                    protected void populateItem(ListItem<StatementItem> item) {
851
                        item.add(item.getModelObject());
×
852
                    }
×
853

854
                });
855
            }
×
856

857
        };
858
        list.setOutputMarkupId(true);
×
859
        if (target == null) {
×
860
            form.add(list);
×
861
        } else {
862
            form.remove("pis");
×
863
            form.add(list);
×
864
            target.add(form);
×
865
            target.appendJavaScript("updateElements();");
×
866
        }
867
    }
×
868

869
    private TemplateContext createPubInfoContext(String piTemplateId) {
870
        TemplateContext c;
871
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
872
            c = pubInfoContextMap.get(piTemplateId);
×
873
        } else {
874
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
875
            pubInfoContextMap.put(piTemplateId, c);
×
876
            pubInfoContexts.add(c);
×
877
        }
878
        return c;
×
879
    }
880

881
    private synchronized Nanopub createNanopub() throws MalformedNanopubException, NanopubAlreadyFinalizedException {
882
        assertionContext.getIntroducedIris().clear();
×
883
        NanopubCreator npCreator = new NanopubCreator(targetNamespace);
×
884
        npCreator.setAssertionUri(vf.createIRI(targetNamespace + "assertion"));
×
885
        assertionContext.propagateStatements(npCreator);
×
886
        provenanceContext.propagateStatements(npCreator);
×
887
        for (TemplateContext c : pubInfoContexts) {
×
888
            c.propagateStatements(npCreator);
×
889
        }
×
890
        for (IRI introducedIri : assertionContext.getIntroducedIris()) {
×
891
            npCreator.addPubinfoStatement(NPX.INTRODUCES, introducedIri);
×
892
        }
×
893
        for (IRI embeddedIri : assertionContext.getEmbeddedIris()) {
×
894
            npCreator.addPubinfoStatement(NPX.EMBEDS, embeddedIri);
×
895
        }
×
896
        npCreator.addNamespace("this", targetNamespace);
×
897
        npCreator.addNamespace("sub", targetNamespace + "/");
×
898
        npCreator.addTimestampNow();
×
899
        IRI templateUri = assertionContext.getTemplate().getNanopub().getUri();
×
900
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_TEMPLATE, templateUri);
×
901
        IRI prTemplateUri = provenanceContext.getTemplate().getNanopub().getUri();
×
902
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PROVENANCE_TEMPLATE, prTemplateUri);
×
903
        for (TemplateContext c : pubInfoContexts) {
×
904
            IRI piTemplateUri = c.getTemplate().getNanopub().getUri();
×
905
            npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PUBINFO_TEMPLATE, piTemplateUri);
×
906
        }
×
907
        String nanopubLabel = getNanopubLabel(npCreator);
×
908
        if (nanopubLabel != null) {
×
909
            npCreator.addPubinfoStatement(RDFS.LABEL, vf.createLiteral(nanopubLabel));
×
910
        }
911
        for (IRI type : assertionContext.getTemplate().getTargetNanopubTypes()) {
×
912
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, type);
×
913
        }
×
914
        IRI userIri = NanodashSession.get().getUserIri();
×
915
        if (User.getName(userIri) != null) {
×
916
            npCreator.addPubinfoStatement(userIri, FOAF.NAME, vf.createLiteral(User.getName(userIri)));
×
917
            npCreator.addNamespace("foaf", FOAF.NAMESPACE);
×
918
        }
919
        String websiteUrl = NanodashPreferences.get().getWebsiteUrl();
×
920
        if (websiteUrl != null) {
×
921
            npCreator.addPubinfoStatement(NPX.WAS_CREATED_AT, vf.createIRI(websiteUrl));
×
922
        }
923
        return npCreator.finalizeNanopub();
×
924
    }
925

926
    private String getNanopubLabel(NanopubCreator npCreator) {
927
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
928

929
        Map<IRI, String> labelMap = new HashMap<>();
×
930
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
931
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
932
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
933
            }
934
        }
×
935

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

983
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
984
        try {
985
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
986
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
987
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
988
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
989
        }
990
        return null;
×
991
    }
992

993
    /**
994
     * Returns a hint whether the form is stateless or not.
995
     *
996
     * @return false if the form is stateful, true if it is stateless.
997
     */
998
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
999
    // if the user browses other pages in parallel:
1000
    protected boolean getStatelessHint() {
1001
        return false;
×
1002
    }
1003

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