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

knowledgepixels / nanodash / 17302137193

28 Aug 2025 04:35PM UTC coverage: 11.965% (-0.4%) from 12.355%
17302137193

Pull #244

github

web-flow
Merge 4e969b0ee into 3323a35f1
Pull Request #244: Use vocabularies with latest version of `nanopub-java`

331 of 3840 branches covered (8.62%)

Branch coverage included in aggregate %.

943 of 6808 relevant lines covered (13.85%)

0.61 hits per line

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

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

3
import com.knowledgepixels.nanodash.RestrictedChoice;
4
import com.knowledgepixels.nanodash.User;
5
import com.knowledgepixels.nanodash.Utils;
6
import com.knowledgepixels.nanodash.component.StatementItem.RepetitionGroup;
7
import com.knowledgepixels.nanodash.page.ExplorePage;
8
import com.knowledgepixels.nanodash.page.UserPage;
9
import com.knowledgepixels.nanodash.template.ContextType;
10
import com.knowledgepixels.nanodash.template.Template;
11
import com.knowledgepixels.nanodash.template.TemplateContext;
12
import com.knowledgepixels.nanodash.template.UnificationException;
13
import net.trustyuri.TrustyUriUtils;
14
import org.apache.commons.codec.Charsets;
15
import org.apache.wicket.behavior.AttributeAppender;
16
import org.apache.wicket.markup.html.basic.Label;
17
import org.apache.wicket.markup.html.link.ExternalLink;
18
import org.apache.wicket.markup.html.panel.Panel;
19
import org.apache.wicket.model.IModel;
20
import org.apache.wicket.model.Model;
21
import org.apache.wicket.validation.IValidatable;
22
import org.apache.wicket.validation.IValidator;
23
import org.apache.wicket.validation.Validatable;
24
import org.apache.wicket.validation.ValidationError;
25
import org.eclipse.rdf4j.common.net.ParsedIRI;
26
import org.eclipse.rdf4j.model.IRI;
27
import org.eclipse.rdf4j.model.Literal;
28
import org.eclipse.rdf4j.model.Value;
29
import org.eclipse.rdf4j.model.ValueFactory;
30
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
31
import org.eclipse.rdf4j.model.util.Literals;
32
import org.eclipse.rdf4j.model.vocabulary.XSD;
33
import org.nanopub.Nanopub;
34
import org.nanopub.SimpleCreatorPattern;
35
import org.nanopub.vocabulary.NTEMPLATE;
36

37
import java.net.URISyntaxException;
38
import java.net.URLEncoder;
39
import java.util.HashMap;
40
import java.util.Map;
41

42
/**
43
 * ReadonlyItem is a component that displays a read-only item in the form.
44
 */
45
public class ReadonlyItem extends Panel implements ContextComponent {
46

47
    // TODO: Make ContextComponent an abstract class with superclass Panel, and move the common code of the form items there.
48

49
    private static final long serialVersionUID = 1L;
50

51
    private IModel<String> model;
52
    private TemplateContext context;
53
    private String prefix;
54
    private ExternalLink linkComp;
55
    private Label extraComp, languageComp, datatypeComp;
56
    private IModel<String> extraModel, languageModel, datatypeModel;
57
    private IRI iri;
58
    private RestrictedChoice restrictedChoice;
59
    private final Template template;
60

61
    /**
62
     * Constructor for ReadonlyItem.
63
     *
64
     * @param id              the component id
65
     * @param parentId        the parent id (e.g., "subj", "obj")
66
     * @param iriP            the IRI of the item
67
     * @param objectPosition  whether this is an object position
68
     * @param statementPartId the statement part ID
69
     * @param rg              the repetition group
70
     */
71
    public ReadonlyItem(String id, String parentId, final IRI iriP, boolean objectPosition, IRI statementPartId, final RepetitionGroup rg) {
72
        super(id);
×
73
        context = rg.getContext();
×
74
        this.iri = iriP;
×
75
        template = context.getTemplate();
×
76
        model = context.getComponentModels().get(iri);
×
77
        if (model == null) {
×
78
            model = Model.of("");
×
79
            context.getComponentModels().put(iri, model);
×
80
        }
81
        String postfix = Utils.getUriPostfix(iri);
×
82
        if (context.hasParam(postfix)) {
×
83
            model.setObject(context.getParam(postfix));
×
84
        }
85

86
        final Map<String, String> foafNameMap;
87
        if (context.getExistingNanopub() == null) {
×
88
            foafNameMap = new HashMap<>();
×
89
        } else {
90
            foafNameMap = Utils.getFoafNameMap(context.getExistingNanopub());
×
91
        }
92

93
        prefix = template.getPrefix(iri);
×
94
        if (prefix == null) prefix = "";
×
95
        if (template.isRestrictedChoicePlaceholder(iri)) {
×
96
            restrictedChoice = new RestrictedChoice(iri, context);
×
97
        }
98
        add(new Label("prefix", new Model<String>() {
×
99

100
            private static final long serialVersionUID = 1L;
101

102
            @Override
103
            public String getObject() {
104
                String prefixLabel = template.getPrefixLabel(iri);
×
105
                String v = getFullValue();
×
106
                if (prefixLabel == null || User.isUser(v) || foafNameMap.containsKey(v)) {
×
107
                    return "";
×
108
                } else {
109
                    if (prefixLabel.length() > 0 && parentId.equals("subj") && !prefixLabel.matches("https?://.*")) {
×
110
                        // Capitalize first letter of label if at subject position:
111
                        prefixLabel = prefixLabel.substring(0, 1).toUpperCase() + prefixLabel.substring(1);
×
112
                    }
113
                    return prefixLabel;
×
114
                }
115
            }
116

117
        }));
118

119
        linkComp = new ExternalLink("link", new Model<String>() {
×
120

121
            private static final long serialVersionUID = 1L;
122

123
            @Override
124
            public String getObject() {
125
                String obj = getFullValue();
×
126
                if (obj == null) return "";
×
127
                if (obj.equals("local:nanopub")) {
×
128
                    if (context.getExistingNanopub() != null) {
×
129
                        obj = context.getExistingNanopub().getUri().stringValue();
×
130
                        return ExplorePage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
131
                    } else {
132
                        return "";
×
133
                    }
134
                } else if (obj.equals("local:assertion")) {
×
135
                    if (context.getExistingNanopub() != null) {
×
136
                        obj = context.getExistingNanopub().getAssertionUri().stringValue();
×
137
                        return ExplorePage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
138
                    } else {
139
                        return "";
×
140
                    }
141
                } else if (User.isUser(obj)) {
×
142
                    return UserPage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
143
                } else if (obj.matches("https?://.+")) {
×
144
                    return ExplorePage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
145
                } else {
146
                    return "";
×
147
                }
148
            }
149

150
        }, new Model<String>() {
×
151

152
            private static final long serialVersionUID = 1L;
153

154
            @Override
155
            public String getObject() {
156
                String obj = getFullValue();
×
157
                if (obj != null && obj.matches("https?://.+")) {
×
158
                    IRI objIri = vf.createIRI(obj);
×
159
                    if (iri.equals(NTEMPLATE.CREATOR_PLACEHOLDER)) {
×
160
                        if (objectPosition) {
×
161
                            return "me (" + User.getShortDisplayName(objIri) + ")";
×
162
                        } else {
163
                            return "I (" + User.getShortDisplayName(objIri) + ")";
×
164
                        }
165
                    } else if (isAssertionValue(objIri)) {
×
166
                        if (context.getType() == ContextType.ASSERTION) {
×
167
                            return "this assertion";
×
168
                        } else {
169
                            return "the assertion above";
×
170
                        }
171
                    } else if (isNanopubValue(objIri)) {
×
172
                        return "this nanopublication";
×
173
                    } else if (User.isUser(obj)) {
×
174
                        return User.getShortDisplayName(objIri);
×
175
                    } else if (foafNameMap.containsKey(obj)) {
×
176
                        return foafNameMap.get(obj);
×
177
                    }
178
                    return getLabelString(objIri);
×
179
                }
180
                return obj;
×
181
            }
182

183
        });
184
        if (template.isIntroducedResource(iri) || template.isEmbeddedResource(iri)) {
×
185
            linkComp.add(AttributeAppender.append("class", "introduced"));
×
186
        }
187
        add(linkComp);
×
188
        add(new Label("description", new Model<String>() {
×
189

190
            private static final long serialVersionUID = 1L;
191

192
            @Override
193
            public String getObject() {
194
                String obj = getFullValue();
×
195
                if (obj != null && obj.matches("https?://.+")) {
×
196
                    IRI objIri = vf.createIRI(obj);
×
197
                    if (isAssertionValue(objIri)) {
×
198
                        return "This is the identifier for the assertion of this nanopublication.";
×
199
                    } else if (isNanopubValue(objIri)) {
×
200
                        return "This is the identifier for this whole nanopublication.";
×
201
                    } else if (context.isReadOnly() && obj.startsWith(context.getExistingNanopub().getUri().stringValue())) {
×
202
                        return "This is a local identifier minted within the nanopublication.";
×
203
                    }
204
                    String labelString = getLabelString(objIri);
×
205
                    String description = "";
×
206
                    if (labelString.contains(" - ")) description = labelString.replaceFirst("^.* - ", "");
×
207
                    return description;
×
208
                } else if (obj != null && obj.startsWith("\"")) {
×
209
                    return "(this is a literal)";
×
210
                }
211
                return "";
×
212
            }
213

214
        }));
215
        Model<String> uriModel = new Model<String>() {
×
216

217
            private static final long serialVersionUID = 1L;
218

219
            @Override
220
            public String getObject() {
221
                String obj = getFullValue();
×
222
                if (obj != null && obj.startsWith("\"")) return "";
×
223
                if (isAssertionValue(obj)) {
×
224
                    return getAssertionValue();
×
225
                } else if (isNanopubValue(obj)) {
×
226
                    return getNanopubValue();
×
227
                }
228
                return obj;
×
229
            }
230

231
        };
232
        add(Utils.getUriLink("uri", uriModel));
×
233
        extraModel = Model.of("");
×
234
        extraComp = new Label("extra", extraModel);
×
235
        extraComp.setVisible(false);
×
236
        add(extraComp);
×
237
        languageModel = Model.of("");
×
238
        languageComp = new Label("language", languageModel);
×
239
        languageComp.setVisible(false);
×
240
        add(languageComp);
×
241
        datatypeModel = Model.of("");
×
242
        datatypeComp = new Label("datatype", datatypeModel);
×
243
        datatypeComp.setVisible(false);
×
244
        add(datatypeComp);
×
245
    }
×
246

247
    /**
248
     * {@inheritDoc}
249
     */
250
    @Override
251
    public void fillFinished() {
252
        String obj = getFullValue();
×
253
        if (obj != null) {
×
254
            if (isAssertionValue(obj)) {
×
255
                linkComp.add(new AttributeAppender("class", "this-assertion"));
×
256
            } else if (isNanopubValue(obj)) {
×
257
                linkComp.add(new AttributeAppender("class", "this-nanopub"));
×
258
            } else if (context.getExistingNanopub() != null) {
×
259
                Nanopub np = context.getExistingNanopub();
×
260
                if (Utils.getIntroducedIriIds(np).contains(obj) || Utils.getEmbeddedIriIds(np).contains(obj)) {
×
261
                    linkComp.add(AttributeAppender.append("class", "introduced"));
×
262
                }
263
            }
264
        }
265
    }
×
266

267
    /**
268
     * {@inheritDoc}
269
     */
270
    @Override
271
    public void finalizeValues() {
272
    }
×
273

274
    private String getLabelString(IRI iri) {
275
        if (template.getLabel(iri) != null) {
×
276
            return template.getLabel(iri).replaceFirst(" - .*$", "");
×
277
        } else if (context.getLabel(iri) != null) {
×
278
            return context.getLabel(iri).replaceFirst(" - .*$", "");
×
279
        } else {
280
            return IriItem.getShortNameFromURI(iri.stringValue());
×
281
        }
282
    }
283

284
    /**
285
     * {@inheritDoc}
286
     */
287
    @Override
288
    public void removeFromContext() {
289
        // Nothing to be done here.
290
    }
×
291

292
    private String getFullValue() {
293
        String s = model.getObject();
×
294
        if (s == null) return null;
×
295
        if (template.isAutoEscapePlaceholder(iri)) {
×
296
            s = Utils.urlEncode(s);
×
297
        }
298
        if (!prefix.isEmpty()) {
×
299
            s = prefix + s;
×
300
        }
301
        return s;
×
302
    }
303

304
    private boolean isNanopubValue(Object obj) {
305
        if (obj == null) return false;
×
306
        if (obj.toString().equals("local:nanopub")) return true;
×
307
        if (context.getExistingNanopub() == null) return false;
×
308
        return obj.toString().equals(context.getExistingNanopub().getUri().stringValue());
×
309
    }
310

311
    private String getNanopubValue() {
312
        if (context.getExistingNanopub() != null) {
×
313
            return context.getExistingNanopub().getUri().stringValue();
×
314
        } else {
315
            return "local:nanopub";
×
316
        }
317
    }
318

319
    private boolean isAssertionValue(Object obj) {
320
        if (obj == null) return false;
×
321
        if (obj.toString().equals("local:assertion")) return true;
×
322
        if (context.getExistingNanopub() == null) return false;
×
323
        return obj.toString().equals(context.getExistingNanopub().getAssertionUri().stringValue());
×
324
    }
325

326
    private String getAssertionValue() {
327
        if (context.getExistingNanopub() != null) {
×
328
            return context.getExistingNanopub().getAssertionUri().stringValue();
×
329
        } else {
330
            return "local:assertion";
×
331
        }
332
    }
333

334
    /**
335
     * {@inheritDoc}
336
     */
337
    @Override
338
    public boolean isUnifiableWith(Value v) {
339
        if (v == null) return true;
×
340
        if (v instanceof IRI) {
×
341
            String vs = v.stringValue();
×
342
            if (vs.equals("local:nanopub")) {
×
343
                vs = getNanopubValue();
×
344
            } else if (vs.equals("local:assertion")) {
×
345
                vs = getAssertionValue();
×
346
            }
347
            if (vs.startsWith(prefix)) vs = vs.substring(prefix.length());
×
348
//                        if (vs.startsWith("local:")) vs = vs.replaceFirst("^local:", "");
349
            if (template.isAutoEscapePlaceholder(iri)) {
×
350
                vs = Utils.urlDecode(vs);
×
351
            }
352
            Validatable<String> validatable = new Validatable<>(vs);
×
353
//                        if (template.isLocalResource(iri) && !Utils.isUriPostfix(vs)) {
354
//                                vs = Utils.getUriPostfix(vs);
355
//                        }
356
            new Validator().validate(validatable);
×
357
            if (!validatable.isValid()) {
×
358
                return false;
×
359
            }
360
            if (model.getObject().isEmpty()) {
×
361
                return true;
×
362
            }
363
            return vs.equals(model.getObject());
×
364
        } else if (v instanceof Literal vL) {
×
365
            if (template.getRegex(iri) != null && !v.stringValue().matches(template.getRegex(iri))) {
×
366
                return false;
×
367
            }
368
            String languagetag = template.getLanguageTag(iri);
×
369
            IRI datatype = template.getDatatype(iri);
×
370
            if (languagetag != null) {
×
371
                if (!vL.getLanguage().isPresent() || !Literals.normalizeLanguageTag(vL.getLanguage().get()).equals(languagetag)) {
×
372
                    return false;
×
373
                }
374
            } else if (datatype != null) {
×
375
                if (!vL.getDatatype().equals(datatype)) {
×
376
                    return false;
×
377
                }
378
            }
379
            if (linkComp.getDefaultModelObject() == null || linkComp.getDefaultModelObject().toString().isEmpty()) {
×
380
                return true;
×
381
            }
382
            return linkComp.getDefaultModelObject().equals("\"" + v.stringValue() + "\"");
×
383
        }
384
        return false;
×
385
    }
386

387
    /**
388
     * {@inheritDoc}
389
     */
390
    @Override
391
    public void unifyWith(Value v) throws UnificationException {
392
        if (v == null) return;
×
393
        String vs = v.stringValue();
×
394
        if (!isUnifiableWith(v)) throw new UnificationException(vs);
×
395
        if (v instanceof IRI) {
×
396
            if (vs.equals("local:nanopub")) {
×
397
                vs = getNanopubValue();
×
398
            } else if (vs.equals("local:assertion")) {
×
399
                vs = getAssertionValue();
×
400
            }
401
            if (!prefix.isEmpty() && vs.startsWith(prefix)) {
×
402
                vs = vs.substring(prefix.length());
×
403
                // With read-only items, we don't need preliminary local identifiers:
404
//                        } else if (vs.startsWith("local:")) {
405
//                                vs = vs.replaceFirst("^local:", "");
406
//                        } else if (template.isLocalResource(iri) && !Utils.isUriPostfix(vs)) {
407
//                                vs = Utils.getUriPostfix(vs);
408
            }
409
            if (template.isAutoEscapePlaceholder(iri)) {
×
410
                vs = Utils.urlDecode(vs);
×
411
            }
412
            model.setObject(vs);
×
413
        } else if (v instanceof Literal vL) {
×
414
            if (vL.getLanguage().isPresent()) {
×
415
                model.setObject("\"" + vs + "\"");
×
416
                languageModel.setObject("(" + Literals.normalizeLanguageTag(vL.getLanguage().get()) + ")");
×
417
                languageComp.setVisible(true);
×
418
            } else if (!vL.getDatatype().equals(XSD.STRING)) {
×
419
                model.setObject("\"" + vs + "\"");
×
420
                datatypeModel.setObject("(" + vL.getDatatype().stringValue().replace(XSD.NAMESPACE, "xsd:") + ")");
×
421
                datatypeComp.setVisible(true);
×
422
            } else {
423
                model.setObject("\"" + vs + "\"");
×
424
            }
425
            // TODO Didn't manage to encode this into a working regex:
426
            if (vs.startsWith("<p>") || vs.startsWith("<p ") || vs.startsWith("<div>") || vs.startsWith("<div ") || vs.startsWith("<span>") || vs.startsWith("<span ") || vs.startsWith("<img ")) {
×
427
                linkComp.setVisible(false);
×
428
                extraModel.setObject("<span class=\"internal\">" + Utils.sanitizeHtml(vs) + "</span>");
×
429
                extraComp.setEscapeModelStrings(false);
×
430
                extraComp.setVisible(true);
×
431
            }
432
        }
433
    }
×
434

435

436
    protected class Validator extends InvalidityHighlighting implements IValidator<String> {
437

438
        private static final long serialVersionUID = 1L;
439

440
        /**
441
         * Default constructor for Validator.
442
         */
443
        public Validator() {
×
444
        }
×
445

446
        @Override
447
        public void validate(IValidatable<String> s) {
448
            String sv = s.getValue();
×
449
            String p = prefix;
×
450
            if (template.isAutoEscapePlaceholder(iri)) {
×
451
                sv = Utils.urlEncode(sv);
×
452
            }
453
            if (sv.matches("https?://.+")) {
×
454
                p = "";
×
455
            } else if (sv.contains(":")) {
×
456
                s.error(new ValidationError("Colon character is not allowed in postfix"));
×
457
            }
458
            String iriString = p + sv;
×
459
            if (iriString.matches("[^:# ]+")) {
×
460
                p = "local:";
×
461
                iriString = p + sv;
×
462
            }
463
            try {
464
                ParsedIRI piri = new ParsedIRI(iriString);
×
465
                if (!piri.isAbsolute()) {
×
466
                    s.error(new ValidationError("IRI not well-formed"));
×
467
                }
468
                if (p.isEmpty() && !sv.startsWith("local:") && !sv.matches("https?://.+")) {
×
469
                    s.error(new ValidationError("Only http(s):// IRIs are allowed here"));
×
470
                }
471
            } catch (URISyntaxException ex) {
×
472
                s.error(new ValidationError("IRI not well-formed"));
×
473
            }
×
474
            String regex = template.getRegex(iri);
×
475
            if (regex != null) {
×
476
                if (!sv.matches(regex)) {
×
477
                    s.error(new ValidationError("Value '" + sv + "' doesn't match the pattern '" + regex + "'"));
×
478
                }
479
            }
480
            if (template.isRestrictedChoicePlaceholder(iri)) {
×
481
                if (!restrictedChoice.getPossibleValues().contains(iriString) && !restrictedChoice.hasPossibleRefValues()) {
×
482
                    // not checking the possible ref values can overgenerate, but normally works
483
                    s.error(new ValidationError("Invalid choice"));
×
484
                }
485
            }
486
            if (template.isExternalUriPlaceholder(iri)) {
×
487
                if (!iriString.matches("https?://.+")) {
×
488
                    s.error(new ValidationError("Not an external IRI"));
×
489
                }
490
            }
491
            if (template.isTrustyUriPlaceholder(iri)) {
×
492
                if (!TrustyUriUtils.isPotentialTrustyUri(iriString)) {
×
493
                    s.error(new ValidationError("Not a trusty URI"));
×
494
                }
495
            }
496
            if (iri.equals(NTEMPLATE.CREATOR_PLACEHOLDER) && context.getExistingNanopub() != null) {
×
497
                boolean found = false;
×
498
                for (IRI creator : SimpleCreatorPattern.getCreators(context.getExistingNanopub())) {
×
499
                    if (creator.stringValue().equals(iriString)) {
×
500
                        found = true;
×
501
                        break;
×
502
                    }
503
                }
×
504
                if (!found) {
×
505
                    s.error(new ValidationError("Not a creator of nanopub"));
×
506
                }
507
            }
508
        }
×
509

510
    }
511

512
    /**
513
     * <p>toString.</p>
514
     *
515
     * @return a {@link java.lang.String} object
516
     */
517
    public String toString() {
518
        return "[read-only IRI item: " + iri + "]";
×
519
    }
520

521
    static final ValueFactory vf = SimpleValueFactory.getInstance();
×
522

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

© 2026 Coveralls, Inc