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

knowledgepixels / nanodash / 17760079101

16 Sep 2025 08:42AM UTC coverage: 13.879% (+0.08%) from 13.799%
17760079101

push

github

ashleycaselli
refactor: replace hardcoded local URI prefix with LocalUri constant and checks with Utils methods

443 of 4012 branches covered (11.04%)

Branch coverage included in aggregate %.

1126 of 7293 relevant lines covered (15.44%)

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

40
import java.net.URISyntaxException;
41
import java.net.URLEncoder;
42
import java.util.HashMap;
43
import java.util.Map;
44

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

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

52
    private static final long serialVersionUID = 1L;
53
    private static final int LONG_LITERAL_LENGTH = 100;
54
    private static final Logger logger = LoggerFactory.getLogger(ReadonlyItem.class);
×
55
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
56

57
    private IModel<String> model;
58
    private TemplateContext context;
59
    private String prefix;
60
    private ExternalLink linkComp;
61
    private Label extraComp, languageComp, datatypeComp;
62
    private IModel<String> extraModel, languageModel, datatypeModel;
63
    private IRI iri;
64
    private RestrictedChoice restrictedChoice;
65
    private Label showMoreLabelLiteral, showMoreLabelHTML;
66
    private final Template template;
67

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

93
        final Map<String, String> foafNameMap;
94
        if (context.getExistingNanopub() == null) {
×
95
            foafNameMap = new HashMap<>();
×
96
        } else {
97
            foafNameMap = Utils.getFoafNameMap(context.getExistingNanopub());
×
98
        }
99

100
        prefix = template.getPrefix(iri);
×
101
        if (prefix == null) prefix = "";
×
102
        if (template.isRestrictedChoicePlaceholder(iri)) {
×
103
            restrictedChoice = new RestrictedChoice(iri, context);
×
104
        }
105
        add(new Label("prefix", new Model<String>() {
×
106

107
            private static final long serialVersionUID = 1L;
108

109
            @Override
110
            public String getObject() {
111
                String prefixLabel = template.getPrefixLabel(iri);
×
112
                String v = getFullValue();
×
113
                if (prefixLabel == null || User.isUser(v) || foafNameMap.containsKey(v)) {
×
114
                    return "";
×
115
                } else {
116
                    if (!prefixLabel.isEmpty() && parentId.equals("subj") && !prefixLabel.matches("https?://.*")) {
×
117
                        // Capitalize first letter of label if at subject position:
118
                        prefixLabel = prefixLabel.substring(0, 1).toUpperCase() + prefixLabel.substring(1);
×
119
                    }
120
                    return prefixLabel;
×
121
                }
122
            }
123

124
        }));
125

126
        linkComp = new ExternalLink("link", new Model<String>() {
×
127

128
            private static final long serialVersionUID = 1L;
129

130
            @Override
131
            public String getObject() {
132
                String obj = getFullValue();
×
133
                if (obj == null) return "";
×
134
                if (obj.equals(LocalUri.PREFIX + "nanopub")) {
×
135
                    if (context.getExistingNanopub() != null) {
×
136
                        obj = context.getExistingNanopub().getUri().stringValue();
×
137
                        return ExplorePage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
138
                    } else {
139
                        return "";
×
140
                    }
141
                } else if (obj.equals(LocalUri.PREFIX + "assertion")) {
×
142
                    if (context.getExistingNanopub() != null) {
×
143
                        obj = context.getExistingNanopub().getAssertionUri().stringValue();
×
144
                        return ExplorePage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
145
                    } else {
146
                        return "";
×
147
                    }
148
                } else if (User.isUser(obj)) {
×
149
                    return UserPage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
150
                } else if (obj.matches("https?://.+")) {
×
151
                    return ExplorePage.MOUNT_PATH + "?id=" + URLEncoder.encode(obj, Charsets.UTF_8);
×
152
                } else {
153
                    return "";
×
154
                }
155
            }
156

157
        }, new Model<String>() {
×
158

159
            private static final long serialVersionUID = 1L;
160

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

190
        });
191
        if (template.isIntroducedResource(iri) || template.isEmbeddedResource(iri)) {
×
192
            linkComp.add(AttributeAppender.append("class", "introduced"));
×
193
        }
194
        add(linkComp);
×
195
        add(new Label("description", new Model<String>() {
×
196

197
            private static final long serialVersionUID = 1L;
198

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

221
        }));
222
        Model<String> uriModel = new Model<String>() {
×
223

224
            private static final long serialVersionUID = 1L;
225

226
            @Override
227
            public String getObject() {
228
                String obj = getFullValue();
×
229
                if (obj != null && obj.startsWith("\"")) return "";
×
230
                if (isAssertionValue(obj)) {
×
231
                    return getAssertionValue();
×
232
                } else if (isNanopubValue(obj)) {
×
233
                    return getNanopubValue();
×
234
                }
235
                return obj;
×
236
            }
237

238
        };
239
        add(Utils.getUriLink("uri", uriModel));
×
240
        extraModel = Model.of("");
×
241
        extraComp = new Label("extra", extraModel);
×
242
        extraComp.setVisible(false);
×
243
        add(extraComp);
×
244
        languageModel = Model.of("");
×
245
        languageComp = new Label("language", languageModel);
×
246
        languageComp.setVisible(false);
×
247
        add(languageComp);
×
248
        datatypeModel = Model.of("");
×
249
        datatypeComp = new Label("datatype", datatypeModel);
×
250
        datatypeComp.setVisible(false);
×
251
        add(datatypeComp);
×
252

253
        showMoreLabelLiteral = new Label("show-more-literal", "");
×
254
        add(showMoreLabelLiteral);
×
255
        showMoreLabelLiteral.setVisible(false);
×
256

257
        showMoreLabelHTML = new Label("show-more-html", "");
×
258
        add(showMoreLabelHTML);
×
259
        showMoreLabelHTML.setVisible(false);
×
260
    }
×
261

262
    /**
263
     * {@inheritDoc}
264
     */
265
    @Override
266
    public void fillFinished() {
267
        String obj = getFullValue();
×
268
        if (obj != null) {
×
269
            if (isAssertionValue(obj)) {
×
270
                linkComp.add(new AttributeAppender("class", "this-assertion"));
×
271
            } else if (isNanopubValue(obj)) {
×
272
                linkComp.add(new AttributeAppender("class", "this-nanopub"));
×
273
            } else if (context.getExistingNanopub() != null) {
×
274
                Nanopub np = context.getExistingNanopub();
×
275
                if (Utils.getIntroducedIriIds(np).contains(obj) || Utils.getEmbeddedIriIds(np).contains(obj)) {
×
276
                    linkComp.add(AttributeAppender.append("class", "introduced"));
×
277
                }
278
            }
279
        }
280
    }
×
281

282
    /**
283
     * {@inheritDoc}
284
     */
285
    @Override
286
    public void finalizeValues() {
287
    }
×
288

289
    private String getLabelString(IRI iri) {
290
        if (template.getLabel(iri) != null) {
×
291
            return template.getLabel(iri).replaceFirst(" - .*$", "");
×
292
        } else if (context.getLabel(iri) != null) {
×
293
            return context.getLabel(iri).replaceFirst(" - .*$", "");
×
294
        } else {
295
            return IriItem.getShortNameFromURI(iri.stringValue());
×
296
        }
297
    }
298

299
    /**
300
     * {@inheritDoc}
301
     */
302
    @Override
303
    public void removeFromContext() {
304
        // Nothing to be done here.
305
    }
×
306

307
    private String getFullValue() {
308
        String s = model.getObject();
×
309
        if (s == null) return null;
×
310
        if (template.isAutoEscapePlaceholder(iri)) {
×
311
            s = Utils.urlEncode(s);
×
312
        }
313
        if (!prefix.isEmpty()) {
×
314
            s = prefix + s;
×
315
        }
316
        return s;
×
317
    }
318

319
    private boolean isNanopubValue(Object obj) {
320
        if (obj == null) return false;
×
321
        if (obj.toString().equals(LocalUri.PREFIX + "nanopub")) return true;
×
322
        if (context.getExistingNanopub() == null) return false;
×
323
        return obj.toString().equals(context.getExistingNanopub().getUri().stringValue());
×
324
    }
325

326
    private String getNanopubValue() {
327
        if (context.getExistingNanopub() != null) {
×
328
            return context.getExistingNanopub().getUri().stringValue();
×
329
        } else {
330
            return LocalUri.PREFIX + "nanopub";
×
331
        }
332
    }
333

334
    private boolean isAssertionValue(Object obj) {
335
        if (obj == null) return false;
×
336
        if (obj.toString().equals(LocalUri.PREFIX + "assertion")) return true;
×
337
        if (context.getExistingNanopub() == null) return false;
×
338
        return obj.toString().equals(context.getExistingNanopub().getAssertionUri().stringValue());
×
339
    }
340

341
    private String getAssertionValue() {
342
        if (context.getExistingNanopub() != null) {
×
343
            return context.getExistingNanopub().getAssertionUri().stringValue();
×
344
        } else {
345
            return LocalUri.PREFIX + "assertion";
×
346
        }
347
    }
348

349
    /**
350
     * {@inheritDoc}
351
     */
352
    @Override
353
    public boolean isUnifiableWith(Value v) {
354
        if (v == null) return true;
×
355
        if (v instanceof IRI) {
×
356
            String vs = v.stringValue();
×
357
            if (vs.equals(LocalUri.PREFIX + "nanopub")) {
×
358
                vs = getNanopubValue();
×
359
            } else if (vs.equals(LocalUri.PREFIX + "assertion")) {
×
360
                vs = getAssertionValue();
×
361
            }
362
            if (vs.startsWith(prefix)) vs = vs.substring(prefix.length());
×
363
//                        if (Utils.isLocalURI(vs)) vs = vs.replaceFirst("^" + LocalUri.PREFIX, "");
364
            if (template.isAutoEscapePlaceholder(iri)) {
×
365
                vs = Utils.urlDecode(vs);
×
366
            }
367
            Validatable<String> validatable = new Validatable<>(vs);
×
368
//                        if (template.isLocalResource(iri) && !Utils.isUriPostfix(vs)) {
369
//                                vs = Utils.getUriPostfix(vs);
370
//                        }
371
            new Validator().validate(validatable);
×
372
            if (!validatable.isValid()) {
×
373
                return false;
×
374
            }
375
            if (model.getObject().isEmpty()) {
×
376
                return true;
×
377
            }
378
            return vs.equals(model.getObject());
×
379
        } else if (v instanceof Literal vL) {
×
380
            if (template.getRegex(iri) != null && !v.stringValue().matches(template.getRegex(iri))) {
×
381
                return false;
×
382
            }
383
            String languagetag = template.getLanguageTag(iri);
×
384
            IRI datatype = template.getDatatype(iri);
×
385
            if (languagetag != null) {
×
386
                if (vL.getLanguage().isEmpty() || !Literals.normalizeLanguageTag(vL.getLanguage().get()).equals(languagetag)) {
×
387
                    return false;
×
388
                }
389
            } else if (datatype != null) {
×
390
                if (!vL.getDatatype().equals(datatype)) {
×
391
                    return false;
×
392
                }
393
            }
394
            if (linkComp.getDefaultModelObject() == null || linkComp.getDefaultModelObject().toString().isEmpty()) {
×
395
                return true;
×
396
            }
397
            return linkComp.getDefaultModelObject().equals("\"" + v.stringValue() + "\"");
×
398
        }
399
        return false;
×
400
    }
401

402
    /**
403
     * {@inheritDoc}
404
     */
405
    @Override
406
    public void unifyWith(Value v) throws UnificationException {
407
        if (v == null) return;
×
408
        String vs = v.stringValue();
×
409
        if (!isUnifiableWith(v)) {
×
410
            logger.error("Cannot unify {}", v);
×
411
            throw new UnificationException(vs);
×
412
        }
413
        if (v instanceof IRI) {
×
414
            if (vs.equals(LocalUri.PREFIX + "nanopub")) {
×
415
                vs = getNanopubValue();
×
416
            } else if (vs.equals(LocalUri.PREFIX + "assertion")) {
×
417
                vs = getAssertionValue();
×
418
            }
419
            if (!prefix.isEmpty() && vs.startsWith(prefix)) {
×
420
                vs = vs.substring(prefix.length());
×
421
                // With read-only items, we don't need preliminary local identifiers:
422
//                        } else if (Utils.isLocalURI(vs)) {
423
//                                vs = vs.replaceFirst("^" + LocalUri.PREFIX, "");
424
//                        } else if (template.isLocalResource(iri) && !Utils.isUriPostfix(vs)) {
425
//                                vs = Utils.getUriPostfix(vs);
426
            }
427
            if (template.isAutoEscapePlaceholder(iri)) {
×
428
                vs = Utils.urlDecode(vs);
×
429
            }
430
            model.setObject(vs);
×
431
        } else if (v instanceof Literal vL) {
×
432
            if (vs.length() >= LONG_LITERAL_LENGTH) {
×
433
                linkComp.add(AttributeAppender.append("class", "long-literal collapsed"));
×
434
                showMoreLabelLiteral.setVisible(true);
×
435
            }
436
            if (vL.getLanguage().isPresent()) {
×
437
                model.setObject("\"" + vs + "\"");
×
438
                languageModel.setObject("(" + Literals.normalizeLanguageTag(vL.getLanguage().get()) + ")");
×
439
                languageComp.setVisible(true);
×
440
            } else if (!vL.getDatatype().equals(XSD.STRING)) {
×
441
                model.setObject("\"" + vs + "\"");
×
442
                datatypeModel.setObject("(" + vL.getDatatype().stringValue().replace(XSD.NAMESPACE, "xsd:") + ")");
×
443
                datatypeComp.setVisible(true);
×
444
            } else {
445
                model.setObject("\"" + vs + "\"");
×
446
            }
447
            // TODO Didn't manage to encode this into a working regex:
448
            if (vs.startsWith("<p>") || vs.startsWith("<p ") || vs.startsWith("<div>") || vs.startsWith("<div ") || vs.startsWith("<span>") || vs.startsWith("<span ") || vs.startsWith("<img ")) {
×
449
                linkComp.setVisible(false);
×
450
                extraModel.setObject(Utils.sanitizeHtml(vs));
×
451
                extraComp.setEscapeModelStrings(false);
×
452
                extraComp.setVisible(true);
×
453
                showMoreLabelLiteral.setVisible(false);
×
454
                showMoreLabelHTML.setVisible(true);
×
455
            }
456
        }
457
    }
×
458

459
    protected class Validator extends InvalidityHighlighting implements IValidator<String> {
460

461
        private static final long serialVersionUID = 1L;
462

463
        /**
464
         * Default constructor for Validator.
465
         */
466
        public Validator() {
×
467
        }
×
468

469
        @Override
470
        public void validate(IValidatable<String> s) {
471
            String sv = s.getValue();
×
472
            String p = prefix;
×
473
            if (template.isAutoEscapePlaceholder(iri)) {
×
474
                sv = Utils.urlEncode(sv);
×
475
            }
476
            if (sv.matches("https?://.+")) {
×
477
                p = "";
×
478
            } else if (sv.contains(":")) {
×
479
                s.error(new ValidationError("Colon character is not allowed in postfix"));
×
480
            }
481
            String iriString = p + sv;
×
482
            if (iriString.matches("[^:# ]+")) {
×
483
                p = LocalUri.PREFIX;
×
484
                iriString = p + sv;
×
485
            }
486
            try {
487
                ParsedIRI piri = new ParsedIRI(iriString);
×
488
                if (!piri.isAbsolute()) {
×
489
                    s.error(new ValidationError("IRI not well-formed"));
×
490
                }
491
                if (p.isEmpty() && !Utils.isLocalURI(sv) && !sv.matches("https?://.+")) {
×
492
                    s.error(new ValidationError("Only http(s):// IRIs are allowed here"));
×
493
                }
494
            } catch (URISyntaxException ex) {
×
495
                s.error(new ValidationError("IRI not well-formed"));
×
496
            }
×
497
            String regex = template.getRegex(iri);
×
498
            if (regex != null) {
×
499
                if (!sv.matches(regex)) {
×
500
                    s.error(new ValidationError("Value '" + sv + "' doesn't match the pattern '" + regex + "'"));
×
501
                }
502
            }
503
            if (template.isRestrictedChoicePlaceholder(iri)) {
×
504
                if (!restrictedChoice.getPossibleValues().contains(iriString) && !restrictedChoice.hasPossibleRefValues()) {
×
505
                    // not checking the possible ref values can overgenerate, but normally works
506
                    s.error(new ValidationError("Invalid choice"));
×
507
                }
508
            }
509
            if (template.isExternalUriPlaceholder(iri)) {
×
510
                if (!iriString.matches("https?://.+")) {
×
511
                    s.error(new ValidationError("Not an external IRI"));
×
512
                }
513
            }
514
            if (template.isTrustyUriPlaceholder(iri)) {
×
515
                if (!TrustyUriUtils.isPotentialTrustyUri(iriString)) {
×
516
                    s.error(new ValidationError("Not a trusty URI"));
×
517
                }
518
            }
519
            if (iri.equals(NTEMPLATE.CREATOR_PLACEHOLDER) && context.getExistingNanopub() != null) {
×
520
                boolean found = false;
×
521
                for (IRI creator : SimpleCreatorPattern.getCreators(context.getExistingNanopub())) {
×
522
                    if (creator.stringValue().equals(iriString)) {
×
523
                        found = true;
×
524
                        break;
×
525
                    }
526
                }
×
527
                if (!found) {
×
528
                    s.error(new ValidationError("Not a creator of nanopub"));
×
529
                }
530
            }
531
        }
×
532

533
    }
534

535
    /**
536
     * <p>toString.</p>
537
     *
538
     * @return a {@link java.lang.String} object
539
     */
540
    public String toString() {
541
        return "[read-only IRI item: " + iri + "]";
×
542
    }
543

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