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

knowledgepixels / nanodash / 29983398040

23 Jul 2026 05:53AM UTC coverage: 29.26% (-0.1%) from 29.361%
29983398040

Pull #562

github

web-flow
Merge cc4285c5c into 809bff55b
Pull Request #562: Superseding/Retracting allowed only when latest version

1988 of 7513 branches covered (26.46%)

Branch coverage included in aggregate %.

3892 of 12583 relevant lines covered (30.93%)

4.56 hits per line

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

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

64
import java.lang.reflect.InvocationTargetException;
65
import java.util.*;
66

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

72
    private static final Logger logger = LoggerFactory.getLogger(PublishForm.class);
×
73

74
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
75

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

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

84
    /**
85
     * Fill modes for the nanopublication to be created.
86
     */
87
    public enum FillMode {
9✔
88
        /**
89
         * Use fill mode
90
         */
91
        USE,
18✔
92
        /**
93
         * Supersede fill mode
94
         */
95
        SUPERSEDE,
18✔
96
        /**
97
         * Derive fill mode
98
         */
99
        DERIVE,
18✔
100
        /**
101
         * Override fill mode: like {@link #DERIVE} in that it records a
102
         * {@code prov:wasDerivedFrom} link, but (like {@link #SUPERSEDE}) it keeps the
103
         * source nanopub's introduced resource IRIs and its root definition nanopub.
104
         */
105
        OVERRIDE
18✔
106
    }
107

108
    protected Form<?> form;
109
    protected FeedbackPanel feedbackPanel;
110
    private final TemplateContext assertionContext;
111
    private TemplateContext provenanceContext;
112
    private final List<TemplateContext> pubInfoContexts = new ArrayList<>();
×
113
    private final Map<String, TemplateContext> pubInfoContextMap = new HashMap<>();
×
114
    private final List<TemplateContext> requiredPubInfoContexts = new ArrayList<>();
×
115
    private String targetNamespace;
116
    private final Class<? extends WebPage> confirmPageClass;
117

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

131
        WebMarkupContainer linkMessageItem = new WebMarkupContainer("link-message-item");
×
132
        if (pageParams.get("link-message").isNull()) {
×
133
            linkMessageItem.add(new Label("link-message", ""));
×
134
            linkMessageItem.setVisible(false);
×
135
        } else {
136
            linkMessageItem.add(new Label("link-message", Utils.sanitizeHtml(pageParams.get("link-message").toString())).setEscapeModelStrings(false));
×
137
        }
138
        add(linkMessageItem);
×
139

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

185
        final TemplateData td = TemplateData.get();
×
186

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

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

287
            String mapping = pageParams.get("values-from-query-mapping").toString();
×
288
            String mapsFrom, mapsTo;
289
            if (mapping.contains(":")) {
×
290
                mapsFrom = mapping.split(":")[0];
×
291
                mapsTo = mapping.split(":")[1];
×
292
            } else {
293
                mapsFrom = mapping;
×
294
                mapsTo = mapping;
×
295
            }
296
            ApiResponse resp = ApiCache.retrieveResponseSync(QueryRef.parseString(querySpec), false);
×
297
            int i = 0;
×
298
            for (ApiResponseEntry e : resp.getData()) {
×
299
                String mapsToSuffix = "";
×
300
                if (i > 0) {
×
301
                    mapsToSuffix = "__" + i;
×
302
                }
303
                assertionContext.setParam(mapsTo + mapsToSuffix, e.get(mapsFrom));
×
304
                i++;
×
305
            }
×
306
        }
307
        for (String k : pageParams.getNamedKeys()) {
×
308
            if (k.startsWith("param_")) {
×
309
                assertionContext.setParam(k.substring(6), pageParams.get(k).toString());
×
310
            }
311
            if (k.startsWith("prparam_")) {
×
312
                provenanceContext.setParam(k.substring(8), pageParams.get(k).toString());
×
313
            }
314
            if (k.matches("piparam[1-9][0-9]*_.*")) {
×
315
                Integer i = Integer.parseInt(k.replaceFirst("^piparam([1-9][0-9]*)_.*$", "$1"));
×
316
                if (!piParamIdMap.containsKey(i)) {
×
317
                    logger.error("Parameter {} of the publication info template not found", i);
×
318
                    continue;
×
319
                }
320
                String n = k.replaceFirst("^piparam[1-9][0-9]*_(.*)$", "$1");
×
321
                logger.info(n);
×
322
                piParamIdMap.get(i).setParam(n, pageParams.get(k).toString());
×
323
            }
324
        }
×
325

326
        final Nanopub improveNp;
327
        if (!pageParams.get("improve").isNull()) {
×
328
            improveNp = Utils.getNanopub(pageParams.get("improve").toString());
×
329
        } else {
330
            improveNp = null;
×
331
        }
332

333
        // Propagate fill source (supersede/derive/improve) so contexts can resolve
334
        // the `local:nanopub`/`local:assertion` sentinels to the fill nanopub's URIs.
335
        Nanopub fillSource = fillNp != null ? fillNp : improveNp;
×
336
        if (fillSource != null) {
×
337
            assertionContext.setFillSource(fillSource);
×
338
            provenanceContext.setFillSource(fillSource);
×
339
            for (TemplateContext c : pubInfoContexts) {
×
340
                c.setFillSource(fillSource);
×
341
            }
×
342
        }
343

344
        // Init statements only now, in order to pick up parameter values:
345
        assertionContext.initStatements();
×
346
        provenanceContext.initStatements();
×
347
        for (TemplateContext c : pubInfoContexts) {
×
348
            c.initStatements();
×
349
        }
×
350

351
        String latestAssertionId = td.getLatestTemplateId(assertionContext.getTemplateId());
×
352
        if (!assertionContext.getTemplateId().equals(latestAssertionId)) {
×
353
            add(new Label("newversion", "There is a new version of this assertion template:"));
×
354
            PageParameters params = new PageParameters(pageParams);
×
355
            params.set("template", latestAssertionId);
×
356
            add(new BookmarkablePageLink<Void>("newversionlink", publishPageClass, params));
×
357
            if ("latest".equals(pageParams.get("template-version").toString())) {
×
358
                throw new RestartResponseException(publishPageClass, params);
×
359
            }
360
        } else {
×
361
            add(new Label("newversion", "").setVisible(false));
×
362
            add(new Label("newversionlink", "").setVisible(false));
×
363
        }
364

365
        final List<Statement> unusedStatementList = new ArrayList<>();
×
366
        final List<Statement> unusedPrStatementList = new ArrayList<>();
×
367
        final List<Statement> unusedPiStatementList = new ArrayList<>();
×
368
        if (fillNp != null) {
×
369
            ValueFiller filler = new ValueFiller(fillNp, ContextType.ASSERTION, true, fillMode);
×
370
            filler.fill(assertionContext);
×
371
            unusedStatementList.addAll(filler.getUnusedStatements());
×
372

373
            if (!fillOnlyAssertion) {
×
374
                ValueFiller prFiller = new ValueFiller(fillNp, ContextType.PROVENANCE, true);
×
375
                prFiller.fill(provenanceContext);
×
376
                unusedPrStatementList.addAll(prFiller.getUnusedStatements());
×
377

378
                ValueFiller piFiller = new ValueFiller(fillNp, ContextType.PUBINFO, true);
×
379
                if (!assertionContext.getTemplate().getTargetNanopubTypes().isEmpty()) {
×
380
                    for (Statement st : new ArrayList<>(piFiller.getUnusedStatements())) {
×
381
                        if (st.getSubject().stringValue().equals(LocalUri.of("nanopub").stringValue()) && st.getPredicate().equals(NPX.HAS_NANOPUB_TYPE)) {
×
382
                            if (assertionContext.getTemplate().getTargetNanopubTypes().contains(st.getObject())) {
×
383
                                piFiller.removeUnusedStatement(st);
×
384
                            }
385
                        }
386
                    }
×
387
                }
388
                for (TemplateContext c : pubInfoContexts) {
×
389
                    piFiller.fill(c);
×
390
                }
×
391
                piFiller.removeUnusedStatements(NanodashSession.get().getUserIri(), FOAF.NAME, null);
×
392
                if (piFiller.hasUnusedStatements()) {
×
393
                    final String handcodedStatementsTemplateId = "https://w3id.org/np/RAMEgudZsQ1bh1fZhfYnkthqH6YSXpghSE_DEN1I-6eAI";
×
394
                    if (!pubInfoContextMap.containsKey(handcodedStatementsTemplateId)) {
×
395
                        TemplateContext c = createPubInfoContext(handcodedStatementsTemplateId);
×
396
                        c.setFillSource(fillNp);
×
397
                        c.initStatements();
×
398
                        piFiller.fill(c);
×
399
                    }
400
                }
401
                unusedPiStatementList.addAll(piFiller.getUnusedStatements());
×
402
                // TODO: Also use pubinfo templates stated in nanopub to be filled in?
403
//                                Set<IRI> pubinfoTemplateIds = Template.getPubinfoTemplateIds(fillNp);
404
//                                if (!pubinfoTemplateIds.isEmpty()) {
405
//                                        ValueFiller piFiller = new ValueFiller(fillNp, ContextType.PUBINFO);
406
//                                        for (IRI pubinfoTemplateId : pubinfoTemplateIds) {
407
//                                                // TODO: Make smart choice on the ordering in trying to fill in all pubinfo elements
408
//                                                piFiller.fill(pubInfoContextMap.get(pubinfoTemplateId.stringValue()));
409
//                                        }
410
//                                        warningMessage += (piFiller.getWarningMessage() == null ? "" : "Publication info: " + piFiller.getWarningMessage() + " ");
411
//                                }
412
            }
413
        } else if (improveNp != null) {
×
414
            ValueFiller filler = new ValueFiller(improveNp, ContextType.ASSERTION, true);
×
415
            filler.fill(assertionContext);
×
416
            unusedStatementList.addAll(filler.getUnusedStatements());
×
417
        }
418
        if (!unusedStatementList.isEmpty()) {
×
419
            add(new Label("warnings", "Some content from the existing nanopublication could not be filled in:"));
×
420
        } else {
421
            add(new Label("warnings", "").setVisible(false));
×
422
        }
423
        add(new DataView<Statement>("unused-statements", new ListDataProvider<Statement>(unusedStatementList)) {
×
424

425
            @Override
426
            protected void populateItem(Item<Statement> item) {
427
                item.add(new TripleItem("unused-statement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
428
            }
×
429

430
        });
431
        add(new DataView<Statement>("unused-prstatements", new ListDataProvider<Statement>(unusedPrStatementList)) {
×
432

433
            @Override
434
            protected void populateItem(Item<Statement> item) {
435
                item.add(new TripleItem("unused-prstatement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
436
            }
×
437

438
        });
439
        add(new DataView<Statement>("unused-pistatements", new ListDataProvider<Statement>(unusedPiStatementList)) {
×
440

441
            @Override
442
            protected void populateItem(Item<Statement> item) {
443
                item.add(new TripleItem("unused-pistatement", item.getModelObject(), (fillNp != null ? fillNp : improveNp), null));
×
444
            }
×
445

446
        });
447

448
        // Finalize statements, which picks up parameter values in repetitions:
449
        assertionContext.finalizeStatements();
×
450
        provenanceContext.finalizeStatements();
×
451
        for (TemplateContext c : pubInfoContexts) {
×
452
            c.finalizeStatements();
×
453
        }
×
454

455
        final CheckBox consentCheck = new CheckBox("consentcheck", new Model<>(false));
×
456
        consentCheck.add(new InvalidityHighlighting());
×
457

458
        form = new Form<Void>("form") {
×
459

460
            @Override
461
            protected void onConfigure() {
462
                super.onConfigure();
×
463
                form.getFeedbackMessages().clear();
×
464
//                                formComponents.clear();
465
            }
×
466

467
            protected void onSubmit() {
468
                if (fillMode == FillMode.SUPERSEDE) {
×
469
                    String npUri = fillNp.getUri().stringValue();
×
470
                    if (!canPublishFromSource(npUri)) {
×
471
                        return;
×
472
                    }
473
                }
474
                if (!canPublishFromParam(pageParams)) {
×
475
                    return;
×
476
                }
477

478
                if (!Boolean.TRUE.equals(consentCheck.getModelObject())) {
×
479
                    feedbackPanel.error("You need to check the checkbox that you understand the consequences.");
×
480
                    return;
×
481
                }
482
                logger.info("Publish form submitted");
×
483
                Nanopub signedNp;
484
                try {
485
                    Nanopub np = createNanopub();
×
486
                    logger.info("Nanopublication created: {}", np.getUri());
×
487
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
488
                    signedNp = SignNanopub.signAndTransform(np, tc);
×
489
                    logger.info("Nanopublication signed: {}", signedNp.getUri());
×
490
                    String npUrl = PublishNanopub.publish(signedNp);
×
491
                    logger.info("Nanopublication published: {}", npUrl);
×
492
                    Utils.cacheNanopub(signedNp);
×
493
                } catch (Exception ex) {
×
494
                    signedNp = null;
×
495
                    logger.error("Nanopublication publishing failed: {}", ex.getMessage());
×
496
                    String message = ex.getClass().getName();
×
497
                    if (ex.getMessage() != null) {
×
498
                        message = ex.getMessage();
×
499
                    }
500
                    feedbackPanel.error(message);
×
501
                }
×
502
                if (signedNp != null) {
×
503
                    String toRefresh = pageParams.get("refresh-upon-publish").toString("");
×
504
                    if (!toRefresh.isEmpty()) {
×
505
                        WicketApplication.get().notifyNanopubPublished(signedNp, toRefresh, 5 * 1000);
×
506
                    }
507
                    String contextId = pageParams.get("context").toString("");
×
508
                    // Broaden the refresh: also force-refresh the context resource's own
509
                    // data (e.g. a space's roles/members) so the page we redirect to —
510
                    // typically its Content tab — reflects the just-published change, not
511
                    // only the specific view query that was acted on.
512
                    if (!contextId.isEmpty() && !contextId.equals(toRefresh)
×
513
                        && AbstractResourceWithProfile.isResourceWithProfile(contextId)) {
×
514
                        WicketApplication.get().notifyNanopubPublished(signedNp, contextId, 5 * 1000);
×
515
                    }
516
                    if (pageParams.get("postpub-redirect-url").isEmpty() && confirmPageClass == null) {
×
517
                        // Forward to the context resource's page, or home if no context; always throws.
518
                        NavigationContext.redirectAfterPublish(signedNp, pageParams);
×
519
                    }
520
                    // Connector flow: show the connector's own confirmation page.
521
                    NanodashPage confirmPage = getConfirmPage(signedNp, pageParams);
×
522
                    if (confirmPage != null) {
×
523
                        throw new RestartResponseException(confirmPage);
×
524
                    }
525
                    NavigationContext.redirectAfterPublish(signedNp, pageParams);
×
526
                }
527
            }
×
528

529
            @Override
530
            protected void onValidate() {
531
                super.onValidate();
×
532
                for (Component fc : assertionContext.getComponents()) {
×
533
                    processFeedback(fc);
×
534
                }
×
535
                for (Component fc : provenanceContext.getComponents()) {
×
536
                    processFeedback(fc);
×
537
                }
×
538
                for (TemplateContext c : pubInfoContexts) {
×
539
                    for (Component fc : c.getComponents()) {
×
540
                        processFeedback(fc);
×
541
                    }
×
542
                }
×
543
            }
×
544

545
            private void processFeedback(Component c) {
546
                if (c instanceof FormComponent) {
×
547
                    ((FormComponent<?>) c).processInput();
×
548
                }
549
                for (FeedbackMessage fm : c.getFeedbackMessages()) {
×
550
                    form.getFeedbackMessages().add(fm);
×
551
                }
×
552
            }
×
553

554
        };
555
        form.setOutputMarkupId(true);
×
556

557
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
558

559
        form.add(newSourceMenu("templatelink", assertionContext.getTemplate().getId()));
×
560
        form.add(new Label("templatename", assertionContext.getTemplate().getLabel()));
×
561
        String description = assertionContext.getTemplate().getLabel();
×
562
        form.add(new Label("templatedesc", assertionContext.getTemplate().getDescription()).setEscapeModelStrings(false));
×
563

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

566
            protected void populateItem(ListItem<StatementItem> item) {
567
                item.add(item.getModelObject());
×
568
            }
×
569

570
        });
571

572
        final Map<String, Boolean> handledProvTemplates = new HashMap<>();
×
573
        final String defaultProvTemplateId;
574
        if (assertionContext.getTemplate().getDefaultProvenance() != null) {
×
575
            defaultProvTemplateId = assertionContext.getTemplate().getDefaultProvenance().stringValue();
×
576
            handledProvTemplates.put(defaultProvTemplateId, true);
×
577
        } else {
578
            defaultProvTemplateId = null;
×
579
        }
580
        final List<String> recommendedProvTemplateOptionIds = new ArrayList<>();
×
581
        final List<String> provTemplateOptionIds = new ArrayList<>();
×
582
        if (pageParams.get("prtemplate-options").isNull()) {
×
583
            // TODO Make this dynamic and consider updated templates:
584
            recommendedProvTemplateOptionIds.add(DEFAULT_PROV_TEMPLATE);
×
585
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAcTpoh5Ra0ssqmcpOgWdaZ_YiPE6demO6cpw-2RvSNs8");
×
586
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA4LGtuOqTIMqVAkjnfBXk1YDcAPNadP5CGiaJiBkdHCQ");
×
587
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAl_-VTw9Re_uRF8r8y0rjlfnu7FlhTa8xg_8xkcweqiE");
×
588
            recommendedProvTemplateOptionIds.add("https://w3id.org/np/RASORV2mMEVpS4lWh2bwUTEcV-RWjbD9RPbN7J0PIeYAU");
×
589
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAjkBbM5yQm7hKH1l_Jk3HAUqWi3Bd57TPmAOZCsZmi_M");
×
590
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAGXx_k9eQMnXaCbsXMsJbGClwZtQEGNg0GVJu6amdAVw");
×
591
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA1fnITI3Pu1UQ0CHghNpys3JwQrM32LBnjmDLoayp9-4");
×
592
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RAJgbsGeGdTG-zq_gU0TLw4s3raMgoRk-mPlc2DSLXvE0");
×
593
            recommendedProvTemplateOptionIds.add("http://purl.org/np/RA6SXfhUY-xeblZU8HhPddw6tsu-C5NXevG6C_zv4bMxU");
×
594
            for (String s : recommendedProvTemplateOptionIds) {
×
595
                handledProvTemplates.put(s, true);
×
596
            }
×
597

598
            for (ApiResponseEntry t : td.getProvenanceTemplates()) {
×
599
                String tid = t.get("np");
×
600
                if (handledProvTemplates.containsKey(tid)) {
×
601
                    continue;
×
602
                }
603
                provTemplateOptionIds.add(tid);
×
604
                handledProvTemplates.put(tid, true);
×
605
            }
×
606
        } else {
607
            for (String s : pageParams.get("prtemplate-options").toString().split(" ")) {
×
608
                if (handledProvTemplates.containsKey(s)) {
×
609
                    continue;
×
610
                }
611
                recommendedProvTemplateOptionIds.add(s);
×
612
                handledProvTemplates.put(s, true);
×
613
            }
614
        }
615

616
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
617

618
            @Override
619
            public String getDisplayValue(String object) {
620
                if (object == null || object.isEmpty()) {
×
621
                    return "";
×
622
                }
623
                Template t = td.getTemplate(object);
×
624
                if (t != null) {
×
625
                    return t.getLabel();
×
626
                }
627
                return object;
×
628
            }
629

630
            @Override
631
            public String getIdValue(String object) {
632
                return object;
×
633
            }
634

635
            // Getting strange errors with Tomcat if this method is not overridden:
636
            @Override
637
            public void detach() {
638
            }
×
639

640
            @Override
641
            public void query(String term, int page, Response<String> response) {
642
                if (term == null) {
×
643
                    term = "";
×
644
                }
645
                term = term.toLowerCase();
×
646
                if (pageParams.get("prtemplate").toString() != null) {
×
647
                    // Using this work-around with "——" because 'optgroup' is not available through Wicket's Select2 classes
648
                    response.add("—— default for this link ——");
×
649
                    response.add(prTemplateId);
×
650
                }
651
                if (defaultProvTemplateId != null) {
×
652
                    response.add("—— default for this template ——");
×
653
                    response.add(defaultProvTemplateId);
×
654
                }
655
                if (!recommendedProvTemplateOptionIds.isEmpty()) {
×
656
                    if (pageParams.get("prtemplate-options").isNull()) {
×
657
                        response.add("—— recommended ——");
×
658
                    }
659
                    for (String s : recommendedProvTemplateOptionIds) {
×
660
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
661
                            response.add(s);
×
662
                        }
663
                    }
×
664
                }
665
                if (!provTemplateOptionIds.isEmpty()) {
×
666
                    response.add("—— others ——");
×
667
                    for (String s : provTemplateOptionIds) {
×
668
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
669
                            response.add(s);
×
670
                        }
671
                    }
×
672
                }
673
            }
×
674

675
            @Override
676
            public Collection<String> toChoices(Collection<String> ids) {
677
                return ids;
×
678
            }
679

680
        };
681
        final IModel<String> prTemplateModel = Model.of(provenanceContext.getTemplate().getId());
×
682
        Select2Choice<String> prTemplateChoice = new Select2Choice<String>("prtemplate", prTemplateModel, prTemplateChoiceProvider);
×
683
        prTemplateChoice.setRequired(true);
×
684
        prTemplateChoice.getSettings().setCloseOnSelect(true);
×
685
        prTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
686

687
            @Override
688
            protected void onUpdate(AjaxRequestTarget target) {
689
                String o = prTemplateModel.getObject();
×
690
                if (o.startsWith("——")) {
×
691
                    o = provenanceContext.getTemplate().getId();
×
692
                    prTemplateModel.setObject(o);
×
693
                }
694
                provenanceContext = new TemplateContext(ContextType.PROVENANCE, prTemplateModel.getObject(), "pr-statement", targetNamespace);
×
695
                provenanceContext.initStatements();
×
696
                refreshProvenance(target);
×
697
                provenanceContext.finalizeStatements();
×
698
            }
×
699

700
        });
701
        form.add(prTemplateChoice);
×
702
        refreshProvenance(null);
×
703

704
        final Map<String, Boolean> handledPiTemplates = new HashMap<>();
×
705
        final List<String> recommendedPiTemplateOptionIds = new ArrayList<>();
×
706
        final List<String> piTemplateOptionIds = new ArrayList<>();
×
707
        // TODO Make this dynamic and consider updated templates:
708
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAXflINqt3smqxV5Aq7E9lzje4uLdkKIOefa6Bp8oJ8CY");
×
709
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RARW4MsFkHuwjycNElvEVtuMjpf4yWDL10-0C5l2MqqRQ");
×
710
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RA16U9Wo30ObhrK1NzH7EsmVRiRtvEuEA_Dfc-u8WkUCA");
×
711
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAdyqI6k07V5nAS82C6hvIDtNWk179EIV4DV-sLbOFKg4");
×
712
        recommendedPiTemplateOptionIds.add("https://w3id.org/np/RAjvEpLZUE7rMoa8q6mWSsN6utJDp-5FmgO47YGsbgw3w");
×
713
        recommendedPiTemplateOptionIds.add("http://purl.org/np/RAxuGRKID6yNg63V5Mf0ot2NjncOnodh-mkN3qT_1txGI");
×
714
        for (TemplateContext c : pubInfoContexts) {
×
715
            // Key both ID forms: the "others" dedup below compares against listing
716
            // entries keyed by nanopub URI, which for a template with embedded
717
            // identity differs from its canonical ID.
718
            handledPiTemplates.put(c.getTemplate().getId(), true);
×
719
            handledPiTemplates.put(c.getTemplate().getNanopub().getUri().stringValue(), true);
×
720
        }
×
721
        for (String s : recommendedPiTemplateOptionIds) {
×
722
            handledPiTemplates.put(s, true);
×
723
        }
×
724

725
        for (ApiResponseEntry entry : td.getPubInfoTemplates()) {
×
726
            String tid = entry.get("np");
×
727
            if (handledPiTemplates.containsKey(tid)) {
×
728
                continue;
×
729
            }
730
            piTemplateOptionIds.add(tid);
×
731
            handledPiTemplates.put(tid, true);
×
732
        }
×
733

734
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
735

736
            @Override
737
            public String getDisplayValue(String object) {
738
                if (object == null || object.isEmpty()) {
×
739
                    return "";
×
740
                }
741
                Template t = td.getTemplate(object);
×
742
                if (t != null) {
×
743
                    return t.getLabel();
×
744
                }
745
                return object;
×
746
            }
747

748
            @Override
749
            public String getIdValue(String object) {
750
                return object;
×
751
            }
752

753
            // Getting strange errors with Tomcat if this method is not overridden:
754
            @Override
755
            public void detach() {
756
            }
×
757

758
            @Override
759
            public void query(String term, int page, Response<String> response) {
760
                if (term == null) {
×
761
                    term = "";
×
762
                }
763
                term = term.toLowerCase();
×
764
                if (!recommendedPiTemplateOptionIds.isEmpty()) {
×
765
                    response.add("—— recommended ——");
×
766
                    for (String s : recommendedPiTemplateOptionIds) {
×
767
                        boolean isAlreadyUsed = false;
×
768
                        for (TemplateContext c : pubInfoContexts) {
×
769
                            // TODO: make this more efficient/nicer
770
                            if (c.getTemplate().hasId(s)) {
×
771
                                isAlreadyUsed = true;
×
772
                                break;
×
773
                            }
774
                        }
×
775
                        if (isAlreadyUsed) {
×
776
                            continue;
×
777
                        }
778
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
779
                            response.add(s);
×
780
                        }
781
                    }
×
782
                }
783
                if (!piTemplateOptionIds.isEmpty()) {
×
784
                    response.add("—— others ——");
×
785
                    for (String s : piTemplateOptionIds) {
×
786
                        boolean isAlreadyUsed = false;
×
787
                        for (TemplateContext c : pubInfoContexts) {
×
788
                            // TODO: make this more efficient/nicer
789
                            if (c.getTemplate().hasId(s)) {
×
790
                                isAlreadyUsed = true;
×
791
                                break;
×
792
                            }
793
                        }
×
794
                        if (isAlreadyUsed) {
×
795
                            continue;
×
796
                        }
797
                        if (s.toLowerCase().contains(term) || getDisplayValue(s).toLowerCase().contains(term)) {
×
798
                            response.add(s);
×
799
                        }
800
                    }
×
801
                }
802
            }
×
803

804
            @Override
805
            public Collection<String> toChoices(Collection<String> ids) {
806
                return ids;
×
807
            }
808

809
        };
810
        final IModel<String> newPiTemplateModel = Model.of();
×
811
        Select2Choice<String> piTemplateChoice = new Select2Choice<String>("pitemplate", newPiTemplateModel, piTemplateChoiceProvider);
×
812
        piTemplateChoice.getSettings().setCloseOnSelect(true);
×
813
        piTemplateChoice.getSettings().setPlaceholder("add element...");
×
814
        piTemplateChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
×
815

816
            @Override
817
            protected void onUpdate(AjaxRequestTarget target) {
818
                if (newPiTemplateModel.getObject().startsWith("——")) {
×
819
                    newPiTemplateModel.setObject(null);
×
820
                    refreshPubInfo(target);
×
821
                    return;
×
822
                }
823
                String id = newPiTemplateModel.getObject();
×
824
                TemplateContext c = new TemplateContext(ContextType.PUBINFO, id, "pi-statement", targetNamespace);
×
825
                c.initStatements();
×
826
                pubInfoContexts.add(c);
×
827
                newPiTemplateModel.setObject(null);
×
828
                refreshPubInfo(target);
×
829
                c.finalizeStatements();
×
830
            }
×
831

832
        });
833
        form.add(piTemplateChoice);
×
834
        refreshPubInfo(null);
×
835

836
        form.add(consentCheck);
×
837

838
        form.add(new Button("preview-button") {
×
839
            @Override
840
            public void onSubmit() {
841
                try {
842
                    if (fillMode == FillMode.SUPERSEDE) {
×
843
                        String npUri = fillNp.getUri().stringValue();
×
844
                        if (!canPublishFromSource(npUri)) {
×
845
                            return;
×
846
                        }
847
                    }
848

849
                    if (!canPublishFromParam(pageParams)) {
×
850
                        return;
×
851
                    }
852

853
                    Nanopub np = createNanopub();
×
854
                    TransformContext tc = new TransformContext(SignatureAlgorithm.RSA, NanodashSession.get().getKeyPair(), NanodashSession.get().getUserIri(), false, false, false);
×
855
                    Nanopub signedNp = SignNanopub.signAndTransform(np, tc);
×
856
                    String previewId = signedNp.getUri().stringValue();
×
857
                    NanodashSession.get().setPreviewNanopub(previewId,
×
858
                            new NanodashSession.PreviewNanopub(signedNp, pageParams, confirmPageClass, Boolean.TRUE.equals(consentCheck.getModelObject()), getPage().getPageReference()));
×
859
                    throw new RestartResponseException(PreviewPage.class, new PageParameters().set("id", previewId));
×
860
                } catch (RestartResponseException ex) {
×
861
                    throw ex;
×
862
                } catch (Exception ex) {
×
863
                    logger.error("Preview failed: {}", ex.getMessage());
×
864
                    String message = ex.getClass().getName();
×
865
                    if (ex.getMessage() != null) {
×
866
                        message = ex.getMessage();
×
867
                    }
868
                    feedbackPanel.error(message);
×
869
                }
870
            }
×
871
        });
872

873
        add(form);
×
874

875
        feedbackPanel = new FeedbackPanel("feedback");
×
876
        feedbackPanel.setOutputMarkupId(true);
×
877
        add(feedbackPanel);
×
878
    }
×
879

880
    static EntryActionMenu newSourceMenu(String id, String templateId) {
881
        BookmarkablePageLink<Void> sourceLink = new BookmarkablePageLink<>("link", ExplorePage.class, new PageParameters().set("id", templateId));
×
882
        sourceLink.add(NavigationContext.pageContextFallback());
×
883
        sourceLink.setBody(Model.of("<span class=\"actionmenu-icon\">↗︎</span>source")).setEscapeModelStrings(false);
×
884
        return new EntryActionMenu(id, List.of(sourceLink));
×
885
    }
886

887
    private void refreshProvenance(AjaxRequestTarget target) {
888
        if (target != null) {
×
889
            form.remove("prtemplatelink");
×
890
            form.remove("pr-statements");
×
891
            target.add(form);
×
892
            target.appendJavaScript("updateElements();");
×
893
        }
894
        form.add(newSourceMenu("prtemplatelink", provenanceContext.getTemplate().getId()));
×
895
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
896

897
            protected void populateItem(ListItem<StatementItem> item) {
898
                item.add(item.getModelObject());
×
899
            }
×
900

901
        };
902
        list.setOutputMarkupId(true);
×
903
        form.add(list);
×
904
    }
×
905

906
    private void refreshPubInfo(AjaxRequestTarget target) {
907
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
908

909
            protected void populateItem(ListItem<TemplateContext> item) {
910
                final TemplateContext pic = item.getModelObject();
×
911
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
912
                item.add(newSourceMenu("pitemplatelink", pic.getTemplate().getId()));
×
913
                Label remove = new Label("piremove", "×");
×
914
                item.add(remove);
×
915
                remove.add(new AjaxEventBehavior("click") {
×
916

917
                    @Override
918
                    protected void onEvent(AjaxRequestTarget target) {
919
                        pubInfoContexts.remove(pic);
×
920
                        target.add(PublishForm.this);
×
921
                        target.appendJavaScript("updateElements();");
×
922
                    }
×
923

924
                });
925
                if (requiredPubInfoContexts.contains(pic)) {
×
926
                    remove.setVisible(false);
×
927
                }
928
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
929

930
                    protected void populateItem(ListItem<StatementItem> item) {
931
                        item.add(item.getModelObject());
×
932
                    }
×
933

934
                });
935
            }
×
936

937
        };
938
        list.setOutputMarkupId(true);
×
939
        if (target == null) {
×
940
            form.add(list);
×
941
        } else {
942
            form.remove("pis");
×
943
            form.add(list);
×
944
            target.add(form);
×
945
            target.appendJavaScript("updateElements();");
×
946
        }
947
    }
×
948

949
    private TemplateContext createPubInfoContext(String piTemplateId) {
950
        TemplateContext c;
951
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
952
            c = pubInfoContextMap.get(piTemplateId);
×
953
        } else {
954
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
955
            pubInfoContextMap.put(piTemplateId, c);
×
956
            pubInfoContexts.add(c);
×
957
        }
958
        return c;
×
959
    }
960

961
    private synchronized Nanopub createNanopub() throws MalformedNanopubException, NanopubAlreadyFinalizedException {
962
        assertionContext.getIntroducedIris().clear();
×
963
        assertionContext.getRolePropertyPins().clear();
×
964
        NanopubCreator npCreator = new NanopubCreator(targetNamespace);
×
965
        npCreator.setAssertionUri(vf.createIRI(targetNamespace + "assertion"));
×
966
        assertionContext.propagateStatements(npCreator);
×
967
        provenanceContext.propagateStatements(npCreator);
×
968
        for (TemplateContext c : pubInfoContexts) {
×
969
            c.propagateStatements(npCreator);
×
970
        }
×
971
        for (IRI introducedIri : assertionContext.getIntroducedIris()) {
×
972
            npCreator.addPubinfoStatement(NPX.INTRODUCES, introducedIri);
×
973
        }
×
974
        for (IRI embeddedIri : assertionContext.getEmbeddedIris()) {
×
975
            npCreator.addPubinfoStatement(NPX.EMBEDS, embeddedIri);
×
976
        }
×
977
        Map<IRI, IRI> rolePropertyPins = assertionContext.getRolePropertyPins();
×
978
        if (!rolePropertyPins.isEmpty()) {
×
979
            // A role predicate carrying a direction pin makes this a role-instantiation
980
            // nanopub; nanopub-query's pin-resolution branch is gated on this type (#525).
981
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, KPXL_TERMS.ROLE_INSTANTIATION);
×
982
            for (Map.Entry<IRI, IRI> pin : rolePropertyPins.entrySet()) {
×
983
                npCreator.addPubinfoStatement(pin.getKey(), RDF.TYPE, pin.getValue());
×
984
            }
×
985
        }
986
        npCreator.addNamespace("this", targetNamespace);
×
987
        npCreator.addNamespace("sub", targetNamespace + "/");
×
988
        npCreator.addTimestampNow();
×
989
        // The canonical template ID: the embedded template-node IRI for templates
990
        // with embedded identity, the nanopub URI for legacy ones.
991
        IRI templateUri = vf.createIRI(assertionContext.getTemplate().getId());
×
992
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_TEMPLATE, templateUri);
×
993
        IRI prTemplateUri = vf.createIRI(provenanceContext.getTemplate().getId());
×
994
        npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PROVENANCE_TEMPLATE, prTemplateUri);
×
995
        for (TemplateContext c : pubInfoContexts) {
×
996
            IRI piTemplateUri = vf.createIRI(c.getTemplate().getId());
×
997
            npCreator.addPubinfoStatement(NTEMPLATE.WAS_CREATED_FROM_PUBINFO_TEMPLATE, piTemplateUri);
×
998
        }
×
999
        String nanopubLabel = getNanopubLabel(npCreator);
×
1000
        if (nanopubLabel != null) {
×
1001
            npCreator.addPubinfoStatement(RDFS.LABEL, vf.createLiteral(nanopubLabel));
×
1002
        }
1003
        for (IRI type : assertionContext.getTemplate().getTargetNanopubTypes()) {
×
1004
            npCreator.addPubinfoStatement(NPX.HAS_NANOPUB_TYPE, type);
×
1005
        }
×
1006
        IRI userIri = NanodashSession.get().getUserIri();
×
1007
        if (User.getName(userIri) != null) {
×
1008
            npCreator.addPubinfoStatement(userIri, FOAF.NAME, vf.createLiteral(User.getName(userIri)));
×
1009
            npCreator.addNamespace("foaf", FOAF.NAMESPACE);
×
1010
        }
1011
        String websiteUrl = NanodashPreferences.get().getWebsiteUrl();
×
1012
        if (websiteUrl != null) {
×
1013
            npCreator.addPubinfoStatement(NPX.WAS_CREATED_AT, vf.createIRI(websiteUrl));
×
1014
        }
1015
        return npCreator.finalizeNanopub();
×
1016
    }
1017

1018
    private String getNanopubLabel(NanopubCreator npCreator) {
1019
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) {
×
1020
            return null;
×
1021
        }
1022

1023
        Map<IRI, String> labelMap = new HashMap<>();
×
1024
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
1025
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
1026
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
1027
            }
1028
        }
×
1029

1030
        String nanopubLabel = assertionContext.getTemplate().getNanopubLabelPattern();
×
1031
        while (nanopubLabel.matches(".*\\$\\{[_a-zA-Z0-9-]+\\}.*")) {
×
1032
            String placeholderPostfix = nanopubLabel.replaceFirst("^.*\\$\\{([_a-zA-Z0-9-]+)\\}.*$", "$1");
×
1033
            IRI placeholderIriHash = vf.createIRI(assertionContext.getTemplateNanopubUri() + "#" + placeholderPostfix);
×
1034
            IRI placeholderIriSlash = vf.createIRI(assertionContext.getTemplateNanopubUri() + "/" + placeholderPostfix);
×
1035
            IRI placeholderIri;
1036
            String placeholderValue = "";
×
1037
            if (assertionContext.getComponentModels().get(placeholderIriSlash) != null) {
×
1038
                placeholderIri = placeholderIriSlash;
×
1039
            } else {
1040
                placeholderIri = placeholderIriHash;
×
1041
            }
1042
            IModel<String> m = (IModel<String>) assertionContext.getComponentModels().get(placeholderIri);
×
1043
            if (m != null) {
×
1044
                placeholderValue = m.orElse("").getObject();
×
1045
            }
1046
            if (placeholderValue == null) {
×
1047
                placeholderValue = "";
×
1048
            }
1049
            String placeholderLabel = placeholderValue;
×
1050
            if (assertionContext.getTemplate().isUriPlaceholder(placeholderIri)) {
×
1051
                try {
1052
                    // TODO Fix this. It doesn't work for placeholders with auto-encode placeholders, etc.
1053
                    //      Not sure we need labels for these, but this code should be improved anyway.
1054
                    String prefix = assertionContext.getTemplate().getPrefix(placeholderIri);
×
1055
                    if (prefix != null) {
×
1056
                        placeholderValue = prefix + placeholderValue;
×
1057
                    }
1058
                    IRI placeholderValueIri = vf.createIRI(placeholderValue);
×
1059
                    String l = assertionContext.getTemplate().getLabel(placeholderValueIri);
×
1060
                    if (labelMap.containsKey(placeholderValueIri)) {
×
1061
                        l = labelMap.get(placeholderValueIri);
×
1062
                    }
1063
                    if (l == null) {
×
1064
                        l = GuidedChoiceItem.getLabel(placeholderValue);
×
1065
                    }
1066
                    if (assertionContext.getTemplate().isAgentPlaceholder(placeholderIri) && !placeholderValue.isEmpty()) {
×
1067
                        l = User.getName(vf.createIRI(placeholderValue));
×
1068
                    }
1069
                    if (l != null && !l.isEmpty()) {
×
1070
                        placeholderLabel = l.replaceFirst(" - .*$", "");
×
1071
                    } else {
1072
                        placeholderLabel = Utils.getShortNameFromURI(placeholderValueIri);
×
1073
                    }
1074
                } catch (Exception ex) {
×
1075
                    logger.error("Nanopub label placeholder IRI error: {}", ex.getMessage());
×
1076
                }
×
1077
            }
1078
            placeholderLabel = placeholderLabel.replaceAll("\\s+", " ");
×
1079
            if (placeholderLabel.length() > 100) {
×
1080
                placeholderLabel = placeholderLabel.substring(0, 97) + "...";
×
1081
            }
1082
            nanopubLabel = Strings.CS.replace(nanopubLabel, "${" + placeholderPostfix + "}", placeholderLabel);
×
1083
        }
×
1084
        return nanopubLabel;
×
1085
    }
1086

1087
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
1088
        if (confirmPageClass == null) {
×
1089
            return null;
×
1090
        }
1091
        try {
1092
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
1093
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
1094
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
1095
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
1096
        }
1097
        return null;
×
1098
    }
1099

1100
    /**
1101
     * Returns a hint whether the form is stateless or not.
1102
     *
1103
     * @return false if the form is stateful, true if it is stateless.
1104
     */
1105
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
1106
    // if the user browses other pages in parallel:
1107
    protected boolean getStatelessHint() {
1108
        return false;
×
1109
    }
1110

1111
    private boolean canPublishFromSource(String sourceNpId) {
1112
        String latestNpId = QueryApiAccess.getLatestVersionId(sourceNpId);
×
1113
        if (!sourceNpId.equals(latestNpId)) {
×
1114
            feedbackPanel.error("The nanopublication you are trying to supersede or retract is not the latest version.");
×
1115
            return false;
×
1116
        }
1117
        return true;
×
1118
    }
1119

1120
    private boolean canPublishFromParam(PageParameters pageParams) {
1121
        String npUri = pageParams.get("param_nanopubToBeRetracted").toString("");
×
1122
        if (npUri.isEmpty()) {
×
1123
            return true;
×
1124
        }
1125
        return canPublishFromSource(npUri);
×
1126
    }
1127

1128
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc