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

knowledgepixels / nanodash / 21569970831

01 Feb 2026 08:46PM UTC coverage: 14.11% (-0.2%) from 14.273%
21569970831

push

github

tkuhn
style: Remove "beta" from logo and "by Knowledge Pixels" link

549 of 5182 branches covered (10.59%)

Branch coverage included in aggregate %.

1506 of 9382 relevant lines covered (16.05%)

2.11 hits per line

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

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

3
import java.lang.reflect.InvocationTargetException;
4
import java.util.ArrayList;
5
import java.util.Collection;
6
import java.util.HashMap;
7
import java.util.List;
8
import java.util.Map;
9

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

421
        });
422

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

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

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

442
        });
443

444
        form = new Form<Void>("form") {
×
445

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

453
            protected void onSubmit() {
454
                logger.info("Publish form submitted");
×
455
                Nanopub signedNp = null;
×
456
                try {
457
                    Nanopub np = createNanopub();
×
458
                    logger.info("Nanopublication created: {}", np.getUri());
×
459
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
460
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
461
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
462
                    String npUrl = PublishNanopub.publish(signedNp);
×
463
                    logger.info("Nanopublication published: {}", npUrl);
×
464
                } catch (Exception ex) {
×
465
                    signedNp = null;
×
466
                    logger.error("Nanopublication publishing failed: {}", ex);
×
467
                    String message = ex.getClass().getName();
×
468
                    if (ex.getMessage() != null) {
×
469
                        message = ex.getMessage();
×
470
                    }
471
                    feedbackPanel.error(message);
×
472
                }
×
473
                if (!pageParams.get("refresh-upon-publish").isEmpty()) {
×
474
                    String toRefresh = pageParams.get("refresh-upon-publish").toString();
×
475
                    if (toRefresh.equals("spaces")) {
×
476
                        Space.forceRootRefresh(3 * 1000);
×
477
                    } else if (toRefresh.equals("maintainedResources")) {
×
478
                        MaintainedResource.forceRootRefresh(3 * 1000);
×
479
                    } else if (ProfiledResource.isProfiledResource(toRefresh)) {
×
480
                        ProfiledResource.forceRefresh(toRefresh, 3 * 1000);
×
481
                    } else {
482
                        QueryRef queryRef = QueryRef.parseString(toRefresh);
×
483
                        // Make sure the next cache update happens not before 3 seconds from now, at which point the
484
                        // published nanopub should show up in the Nanopub Query instances:
485
                        ApiCache.clearCache(queryRef, 3 * 1000);
×
486
                    }
487
                }
488
                if (signedNp != null) {
×
489
                    String contextId = pageParams.get("context").toString("");
×
490
                    String partId = pageParams.get("part").toString("");
×
491
                    if (!contextId.isEmpty()) {
×
492
                        PageParameters redirectParams = new PageParameters().set("just-published", signedNp.getUri().stringValue());
×
493
                        if (!partId.isEmpty()) {
×
494
                            // User was on a part page (e.g. paper collection); redirect back to the part page
495
                            redirectParams.set("id", partId).set("context", contextId);
×
496
                            throw new RestartResponseException(ResourcePartPage.class, redirectParams);
×
497
                        }
498
                        redirectParams.set("id", contextId);
×
499
                        if (Space.get(contextId) != null) {
×
500
                            throw new RestartResponseException(SpacePage.class, redirectParams);
×
501
                        }
502
                        if (MaintainedResource.get(contextId) != null) {
×
503
                            throw new RestartResponseException(MaintainedResourcePage.class, redirectParams);
×
504
                        }
505
                        if (User.isUser(contextId)) {
×
506
                            throw new RestartResponseException(UserPage.class, redirectParams);
×
507
                        }
508
                    }
509
                    throw new RestartResponseException(getConfirmPage(signedNp, pageParams));
×
510
                } else {
511
                    logger.error("Nanopublication publishing failed");
×
512
                }
513
            }
×
514

515
            @Override
516
            protected void onValidate() {
517
                super.onValidate();
×
518
                for (Component fc : assertionContext.getComponents()) {
×
519
                    processFeedback(fc);
×
520
                }
×
521
                for (Component fc : provenanceContext.getComponents()) {
×
522
                    processFeedback(fc);
×
523
                }
×
524
                for (TemplateContext c : pubInfoContexts) {
×
525
                    for (Component fc : c.getComponents()) {
×
526
                        processFeedback(fc);
×
527
                    }
×
528
                }
×
529
            }
×
530

531
            private void processFeedback(Component c) {
532
                if (c instanceof FormComponent) {
×
533
                    ((FormComponent<?>) c).processInput();
×
534
                }
535
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
536
                    form.getFeedbackMessages().add(fm);
×
537
                }
×
538
            }
×
539

540
        };
541
        form.setOutputMarkupId(true);
×
542

543
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
544

545
        form.add(new BookmarkablePageLink<Void>("templatelink", ExplorePage.class, new PageParameters().set("id", assertionContext.getTemplate().getId())));
×
546
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
547
        String description = assertionContext.getTemplate().getLabel();
×
548
        if (description == null) description = "";
×
549
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
550

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

553
            protected void populateItem(ListItem<StatementItem> item) {
554
                item.add(item.getModelObject());
×
555
            }
×
556

557
        });
558

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

585
            for (ApiResponseEntry t : td.getProvenanceTemplates()) {
×
586
                String tid = t.get("np");
×
587
                if (handledProvTemplates.containsKey(tid)) continue;
×
588
                provTemplateOptionIds.add(tid);
×
589
                handledProvTemplates.put(tid, true);
×
590
            }
×
591
        } else {
592
            for (String s : pageParams.get("prtemplate-options").toString().split(" ")) {
×
593
                if (handledProvTemplates.containsKey(s)) continue;
×
594
                recommendedProvTemplateOptionIds.add(s);
×
595
                handledProvTemplates.put(s, true);
×
596
            }
597
        }
598

599
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
600

601
            @Override
602
            public String getDisplayValue(String object) {
603
                if (object == null || object.isEmpty()) return "";
×
604
                Template t = td.getTemplate(object);
×
605
                if (t != null) return t.getLabel();
×
606
                return object;
×
607
            }
608

609
            @Override
610
            public String getIdValue(String object) {
611
                return object;
×
612
            }
613

614
            // Getting strange errors with Tomcat if this method is not overridden:
615
            @Override
616
            public void detach() {
617
            }
×
618

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

652
            @Override
653
            public Collection<String> toChoices(Collection<String> ids) {
654
                return ids;
×
655
            }
656

657
        };
658
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
659
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
660
        prTemplateChoice.setRequired(true);
×
661
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
662
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
663

664
            @Override
665
            protected void onUpdate(AjaxRequestTarget target) {
666
                String o = prTemplateModel.getObject();
×
667
                if (o.startsWith("——")) {
×
668
                    o = provenanceContext.getTemplate().getId();
×
669
                    prTemplateModel.setObject(o);
×
670
                }
671
                provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateModel.getObject(), "pr-statement", targetNamespace);
×
672
                provenanceContext.initStatements();
×
673
                refreshProvenance(target);
×
674
                provenanceContext.finalizeStatements();
×
675
            }
×
676

677
        });
678
        form.add(prTemplateChoice);
×
679
        refreshProvenance(null);
×
680

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

699
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
700
            String tid = entry.get("np");
×
701
            if (handledPiTemplates.containsKey(tid)) continue;
×
702
            piTemplateOptionIds.add(tid);
×
703
            handledPiTemplates.put(tid, true);
×
704
        }
×
705

706
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
707

708
            @Override
709
            public String getDisplayValue(String object) {
710
                if (object == null || object.isEmpty()) return "";
×
711
                Template t = td.getTemplate(object);
×
712
                if (t != null) return t.getLabel();
×
713
                return object;
×
714
            }
715

716
            @Override
717
            public String getIdValue(String object) {
718
                return object;
×
719
            }
720

721
            // Getting strange errors with Tomcat if this method is not overridden:
722
            @Override
723
            public void detach() {
724
            }
×
725

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

766
            @Override
767
            public Collection<String> toChoices(Collection<String> ids) {
768
                return ids;
×
769
            }
770

771
        };
772
        final IModel<String> newPiTemplateModel = Model.of();
×
773
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
774
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
775
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
776
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
777

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

794
        });
795
        form.add(piTemplateChoice);
×
796
        refreshPubInfo(null);
×
797

798
        form.add(consentCheck);
×
799
        add(form);
×
800

801
        feedbackPanel = new FeedbackPanel("feedback");
×
802
        feedbackPanel.setOutputMarkupId(true);
×
803
        add(feedbackPanel);
×
804
    }
×
805

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

816
            protected void populateItem(ListItem<StatementItem> item) {
817
                item.add(item.getModelObject());
×
818
            }
×
819

820
        };
821
        list.setOutputMarkupId(true);
×
822
        form.add(list);
×
823
    }
×
824

825
    private void refreshPubInfo(AjaxRequestTarget target) {
826
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
827

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

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

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

847
                    protected void populateItem(ListItem<StatementItem> item) {
848
                        item.add(item.getModelObject());
×
849
                    }
×
850

851
                });
852
            }
×
853

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

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

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

923
    private String getNanopubLabel(NanopubCreator npCreator) {
924
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) return null;
×
925

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

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

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

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

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