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

knowledgepixels / nanodash / 22618039211

03 Mar 2026 10:05AM UTC coverage: 16.058% (+0.2%) from 15.884%
22618039211

Pull #365

github

web-flow
Merge 1e7e700f0 into a8c4b4a77
Pull Request #365: Refactor of `ResourceWithProfile` and related classes

699 of 5287 branches covered (13.22%)

Branch coverage included in aggregate %.

1721 of 9783 relevant lines covered (17.59%)

2.41 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.domain.User;
6
import com.knowledgepixels.nanodash.Utils;
7
import com.knowledgepixels.nanodash.component.StatementItem.RepetitionGroup;
8
import com.knowledgepixels.nanodash.domain.IndividualAgent;
9
import com.knowledgepixels.nanodash.page.ExplorePage;
10
import com.knowledgepixels.nanodash.page.UserPage;
11
import com.knowledgepixels.nanodash.template.ContextType;
12
import com.knowledgepixels.nanodash.template.Template;
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.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.NanopubUtils;
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 AbstractContextComponent {
49

50
    private static final int LONG_LITERAL_LENGTH = 100;
51
    private static final Logger logger = LoggerFactory.getLogger(ReadonlyItem.class);
×
52
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
×
53

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

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

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

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

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

116
        }));
117

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

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

147
        }, new Model<String>() {
×
148

149
            @Override
150
            public String getObject() {
151
                String obj = getFullValue();
×
152
                if (obj != null && obj.matches("https?://.+")) {
×
153
                    IRI objIri = vf.createIRI(obj);
×
154
                    if (iri.equals(NTEMPLATE.CREATOR_PLACEHOLDER)) {
×
155
                        // TODO We might want to introduce a "(you)" flag here at some point
156
                        return User.getShortDisplayName(objIri);
×
157
                    } else if (isAssertionValue(objIri)) {
×
158
                        if (context.getType() == ContextType.ASSERTION) {
×
159
                            return "this assertion";
×
160
                        } else {
161
                            return "the assertion above";
×
162
                        }
163
                    } else if (isNanopubValue(objIri)) {
×
164
                        return "this nanopublication";
×
165
                    } else if (IndividualAgent.isUser(obj)) {
×
166
                        return User.getShortDisplayName(objIri);
×
167
                    } else if (foafNameMap.containsKey(obj)) {
×
168
                        return foafNameMap.get(obj);
×
169
                    }
170
                    return getLabelString(objIri);
×
171
                }
172
                return obj;
×
173
            }
174

175
        });
176
        if (template.isIntroducedResource(iri) || template.isEmbeddedResource(iri)) {
×
177
            linkComp.add(AttributeAppender.append("class", "introduced"));
×
178
        }
179
        add(linkComp);
×
180
        add(new Label("description", new Model<String>() {
×
181

182
            @Override
183
            public String getObject() {
184
                String obj = getFullValue();
×
185
                if (obj != null && obj.matches("https?://.+")) {
×
186
                    IRI objIri = vf.createIRI(obj);
×
187
                    if (isAssertionValue(objIri)) {
×
188
                        return "This is the identifier for the assertion of this nanopublication.";
×
189
                    } else if (isNanopubValue(objIri)) {
×
190
                        return "This is the identifier for this whole nanopublication.";
×
191
                    } else if (context.isReadOnly() && obj.startsWith(context.getExistingNanopub().getUri().stringValue())) {
×
192
                        return "This is a local identifier minted within the nanopublication.";
×
193
                    }
194
                    String labelString = getLabelString(objIri);
×
195
                    String description = "";
×
196
                    if (labelString.contains(" - ")) description = labelString.replaceFirst("^.* - ", "");
×
197
                    return description;
×
198
                } else if (obj != null && obj.startsWith("\"")) {
×
199
                    return "(this is a literal)";
×
200
                }
201
                return "";
×
202
            }
203

204
        }));
205
        Model<String> uriModel = new Model<String>() {
×
206

207
            @Override
208
            public String getObject() {
209
                String obj = getFullValue();
×
210
                if (obj != null && obj.startsWith("\"")) return "";
×
211
                if (isAssertionValue(obj)) {
×
212
                    return getAssertionValue();
×
213
                } else if (isNanopubValue(obj)) {
×
214
                    return getNanopubValue();
×
215
                }
216
                return obj;
×
217
            }
218

219
        };
220
        add(Utils.getUriLink("uri", uriModel));
×
221
        extraModel = Model.of("");
×
222
        extraComp = new Label("extra", extraModel);
×
223
        extraComp.setVisible(false);
×
224
        add(extraComp);
×
225
        languageModel = Model.of("");
×
226
        languageComp = new Label("language", languageModel);
×
227
        languageComp.setVisible(false);
×
228
        add(languageComp);
×
229
        datatypeModel = Model.of("");
×
230
        datatypeComp = new Label("datatype", datatypeModel);
×
231
        datatypeComp.setVisible(false);
×
232
        add(datatypeComp);
×
233

234
        showMoreLabelLiteral = new Label("show-more-literal", "");
×
235
        add(showMoreLabelLiteral);
×
236
        showMoreLabelLiteral.setVisible(false);
×
237

238
        showMoreLabelHTML = new Label("show-more-html", "");
×
239
        add(showMoreLabelHTML);
×
240
        showMoreLabelHTML.setVisible(false);
×
241
    }
×
242

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

263
    /**
264
     * {@inheritDoc}
265
     */
266
    @Override
267
    public void finalizeValues() {
268
    }
×
269

270
    private String getLabelString(IRI iri) {
271
        if (template.getLabel(iri) != null) {
×
272
            return template.getLabel(iri).replaceFirst(" - .*$", "");
×
273
        } else if (context.getLabel(iri) != null) {
×
274
            return context.getLabel(iri).replaceFirst(" - .*$", "");
×
275
        } else {
276
            return Utils.getShortNameFromURI(iri.stringValue());
×
277
        }
278
    }
279

280
    /**
281
     * {@inheritDoc}
282
     */
283
    @Override
284
    public void removeFromContext() {
285
        // Nothing to be done here.
286
    }
×
287

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

300
    private boolean isNanopubValue(Object obj) {
301
        if (obj == null) return false;
×
302
        if (obj.toString().equals(LocalUri.of("nanopub").stringValue())) return true;
×
303
        if (context.getExistingNanopub() == null) return false;
×
304
        return obj.toString().equals(context.getExistingNanopub().getUri().stringValue());
×
305
    }
306

307
    private String getNanopubValue() {
308
        if (context.getExistingNanopub() != null) {
×
309
            return context.getExistingNanopub().getUri().stringValue();
×
310
        } else {
311
            return LocalUri.of("nanopub").stringValue();
×
312
        }
313
    }
314

315
    private boolean isAssertionValue(Object obj) {
316
        if (obj == null) return false;
×
317
        if (obj.toString().equals(LocalUri.of("assertion").stringValue())) return true;
×
318
        if (context.getExistingNanopub() == null) return false;
×
319
        return obj.toString().equals(context.getExistingNanopub().getAssertionUri().stringValue());
×
320
    }
321

322
    private String getAssertionValue() {
323
        if (context.getExistingNanopub() != null) {
×
324
            return context.getExistingNanopub().getAssertionUri().stringValue();
×
325
        } else {
326
            return LocalUri.of("assertion").stringValue();
×
327
        }
328
    }
329

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

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

439
    /**
440
     * Validator class for validating the input.
441
     */
442
    protected class Validator extends InvalidityHighlighting implements IValidator<String> {
443

444
        /**
445
         * Default constructor for Validator.
446
         */
447
        public Validator() {
×
448
        }
×
449

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

514
    }
515

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

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