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

knowledgepixels / nanodash / 29984530242

23 Jul 2026 06:16AM UTC coverage: 28.646% (-0.7%) from 29.361%
29984530242

Pull #562

github

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

1948 of 7513 branches covered (25.93%)

Branch coverage included in aggregate %.

3807 of 12577 relevant lines covered (30.27%)

4.54 hits per line

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

0.5
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 || fillMode == FillMode.OVERRIDE) {
×
469
                    String npUri = fillNp.getUri().stringValue();
×
470
                    if (!canPublishFromSource(npUri)) {
×
471
                        return;
×
472
                    }
473
                }
474

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

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

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

551
        };
552
        form.setOutputMarkupId(true);
×
553

554
        //form.add(new Label("nanopub-namespace", targetNamespaceLabel));
555

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

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

563
            protected void populateItem(ListItem<StatementItem> item) {
564
                item.add(item.getModelObject());
×
565
            }
×
566

567
        });
568

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

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

613
        ChoiceProvider<String> prTemplateChoiceProvider = new ChoiceProvider<String>() {
×
614

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

627
            @Override
628
            public String getIdValue(String object) {
629
                return object;
×
630
            }
631

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

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

672
            @Override
673
            public Collection<String> toChoices(Collection<String> ids) {
674
                return ids;
×
675
            }
676

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

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

697
        });
698
        form.add(prTemplateChoice);
×
699
        refreshProvenance(null);
×
700

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

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

731
        ChoiceProvider<String> piTemplateChoiceProvider = new ChoiceProvider<String>() {
×
732

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

745
            @Override
746
            public String getIdValue(String object) {
747
                return object;
×
748
            }
749

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

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

801
            @Override
802
            public Collection<String> toChoices(Collection<String> ids) {
803
                return ids;
×
804
            }
805

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

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

829
        });
830
        form.add(piTemplateChoice);
×
831
        refreshPubInfo(null);
×
832

833
        form.add(consentCheck);
×
834

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

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

866
        add(form);
×
867

868
        feedbackPanel = new FeedbackPanel("feedback");
×
869
        feedbackPanel.setOutputMarkupId(true);
×
870
        add(feedbackPanel);
×
871
    }
×
872

873
    static EntryActionMenu newSourceMenu(String id, String templateId) {
874
        BookmarkablePageLink<Void> sourceLink = new BookmarkablePageLink<>("link", ExplorePage.class, new PageParameters().set("id", templateId));
×
875
        sourceLink.add(NavigationContext.pageContextFallback());
×
876
        sourceLink.setBody(Model.of("<span class=\"actionmenu-icon\">↗︎</span>source")).setEscapeModelStrings(false);
×
877
        return new EntryActionMenu(id, List.of(sourceLink));
×
878
    }
879

880
    private void refreshProvenance(AjaxRequestTarget target) {
881
        if (target != null) {
×
882
            form.remove("prtemplatelink");
×
883
            form.remove("pr-statements");
×
884
            target.add(form);
×
885
            target.appendJavaScript("updateElements();");
×
886
        }
887
        form.add(newSourceMenu("prtemplatelink", provenanceContext.getTemplate().getId()));
×
888
        ListView<StatementItem> list = new ListView<StatementItem>("pr-statements", provenanceContext.getStatementItems()) {
×
889

890
            protected void populateItem(ListItem<StatementItem> item) {
891
                item.add(item.getModelObject());
×
892
            }
×
893

894
        };
895
        list.setOutputMarkupId(true);
×
896
        form.add(list);
×
897
    }
×
898

899
    private void refreshPubInfo(AjaxRequestTarget target) {
900
        ListView<TemplateContext> list = new ListView<TemplateContext>("pis", pubInfoContexts) {
×
901

902
            protected void populateItem(ListItem<TemplateContext> item) {
903
                final TemplateContext pic = item.getModelObject();
×
904
                item.add(new Label("pitemplatename", pic.getTemplate().getLabel()));
×
905
                item.add(newSourceMenu("pitemplatelink", pic.getTemplate().getId()));
×
906
                Label remove = new Label("piremove", "×");
×
907
                item.add(remove);
×
908
                remove.add(new AjaxEventBehavior("click") {
×
909

910
                    @Override
911
                    protected void onEvent(AjaxRequestTarget target) {
912
                        pubInfoContexts.remove(pic);
×
913
                        target.add(PublishForm.this);
×
914
                        target.appendJavaScript("updateElements();");
×
915
                    }
×
916

917
                });
918
                if (requiredPubInfoContexts.contains(pic)) {
×
919
                    remove.setVisible(false);
×
920
                }
921
                item.add(new ListView<StatementItem>("pi-statements", pic.getStatementItems()) {
×
922

923
                    protected void populateItem(ListItem<StatementItem> item) {
924
                        item.add(item.getModelObject());
×
925
                    }
×
926

927
                });
928
            }
×
929

930
        };
931
        list.setOutputMarkupId(true);
×
932
        if (target == null) {
×
933
            form.add(list);
×
934
        } else {
935
            form.remove("pis");
×
936
            form.add(list);
×
937
            target.add(form);
×
938
            target.appendJavaScript("updateElements();");
×
939
        }
940
    }
×
941

942
    private TemplateContext createPubInfoContext(String piTemplateId) {
943
        TemplateContext c;
944
        if (pubInfoContextMap.containsKey(piTemplateId)) {
×
945
            c = pubInfoContextMap.get(piTemplateId);
×
946
        } else {
947
            c = new TemplateContext(ContextType.PUBINFO, piTemplateId, "pi-statement", targetNamespace);
×
948
            pubInfoContextMap.put(piTemplateId, c);
×
949
            pubInfoContexts.add(c);
×
950
        }
951
        return c;
×
952
    }
953

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

1011
    private String getNanopubLabel(NanopubCreator npCreator) {
1012
        if (assertionContext.getTemplate().getNanopubLabelPattern() == null) {
×
1013
            return null;
×
1014
        }
1015

1016
        Map<IRI, String> labelMap = new HashMap<>();
×
1017
        for (Statement st : npCreator.getCurrentPubinfoStatements()) {
×
1018
            if (st.getPredicate().equals(RDFS.LABEL) && st.getObject() instanceof Literal objL) {
×
1019
                labelMap.put((IRI) st.getSubject(), objL.stringValue());
×
1020
            }
1021
        }
×
1022

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

1080
    private NanodashPage getConfirmPage(Nanopub signedNp, PageParameters pageParams) {
1081
        if (confirmPageClass == null) {
×
1082
            return null;
×
1083
        }
1084
        try {
1085
            return (NanodashPage) confirmPageClass.getConstructor(Nanopub.class, PageParameters.class).newInstance(signedNp, pageParams);
×
1086
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
×
1087
                 InvocationTargetException | NoSuchMethodException | SecurityException ex) {
1088
            logger.error("Could not create instance of confirmation page: {}", ex.getMessage());
×
1089
        }
1090
        return null;
×
1091
    }
1092

1093
    /**
1094
     * Returns a hint whether the form is stateless or not.
1095
     *
1096
     * @return false if the form is stateful, true if it is stateless.
1097
     */
1098
    // This is supposed to solve the problem that sometimes (but only sometimes) form content is reset
1099
    // if the user browses other pages in parallel:
1100
    protected boolean getStatelessHint() {
1101
        return false;
×
1102
    }
1103

1104
    private boolean canPublishFromSource(String sourceNpId) {
1105
        String latestNpId = QueryApiAccess.getLatestVersionId(sourceNpId);
×
1106
        if (!sourceNpId.equals(latestNpId)) {
×
1107
            feedbackPanel.error("The nanopublication you are trying to supersede or override is not the latest version.");
×
1108
            return false;
×
1109
        }
1110
        return true;
×
1111
    }
1112

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