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

knowledgepixels / nanodash / 17837235071

18 Sep 2025 05:58PM UTC coverage: 13.87%. Remained the same
17837235071

push

github

tkuhn
chore: Remove serialVersionUIDs

443 of 4022 branches covered (11.01%)

Branch coverage included in aggregate %.

1133 of 7341 relevant lines covered (15.43%)

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 int LONG_LITERAL_LENGTH = 100;
53
    private static final Logger logger = LoggerFactory.getLogger(ReadonlyItem.class);
×
54
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
55

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

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

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

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

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

121
        }));
122

123
        linkComp = new ExternalLink("link", new Model<String>() {
×
124

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

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

212
        }));
213
        Model<String> uriModel = new Model<String>() {
×
214

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

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

242
        showMoreLabelLiteral = new Label("show-more-literal", "");
×
243
        add(showMoreLabelLiteral);
×
244
        showMoreLabelLiteral.setVisible(false);
×
245

246
        showMoreLabelHTML = new Label("show-more-html", "");
×
247
        add(showMoreLabelHTML);
×
248
        showMoreLabelHTML.setVisible(false);
×
249
    }
×
250

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

271
    /**
272
     * {@inheritDoc}
273
     */
274
    @Override
275
    public void finalizeValues() {
276
    }
×
277

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

288
    /**
289
     * {@inheritDoc}
290
     */
291
    @Override
292
    public void removeFromContext() {
293
        // Nothing to be done here.
294
    }
×
295

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

308
    private boolean isNanopubValue(Object obj) {
309
        if (obj == null) return false;
×
310
        if (obj.toString().equals(LocalUri.PREFIX + "nanopub")) return true;
×
311
        if (context.getExistingNanopub() == null) return false;
×
312
        return obj.toString().equals(context.getExistingNanopub().getUri().stringValue());
×
313
    }
314

315
    private String getNanopubValue() {
316
        if (context.getExistingNanopub() != null) {
×
317
            return context.getExistingNanopub().getUri().stringValue();
×
318
        } else {
319
            return LocalUri.PREFIX + "nanopub";
×
320
        }
321
    }
322

323
    private boolean isAssertionValue(Object obj) {
324
        if (obj == null) return false;
×
325
        if (obj.toString().equals(LocalUri.PREFIX + "assertion")) return true;
×
326
        if (context.getExistingNanopub() == null) return false;
×
327
        return obj.toString().equals(context.getExistingNanopub().getAssertionUri().stringValue());
×
328
    }
329

330
    private String getAssertionValue() {
331
        if (context.getExistingNanopub() != null) {
×
332
            return context.getExistingNanopub().getAssertionUri().stringValue();
×
333
        } else {
334
            return LocalUri.PREFIX + "assertion";
×
335
        }
336
    }
337

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

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

448
    protected class Validator extends InvalidityHighlighting implements IValidator<String> {
449

450
        /**
451
         * Default constructor for Validator.
452
         */
453
        public Validator() {
×
454
        }
×
455

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

520
    }
521

522
    /**
523
     * <p>toString.</p>
524
     *
525
     * @return a {@link java.lang.String} object
526
     */
527
    public String toString() {
528
        return "[read-only IRI item: " + iri + "]";
×
529
    }
530

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