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

knowledgepixels / nanodash / 29395622307

15 Jul 2026 06:54AM UTC coverage: 30.168% (+0.8%) from 29.361%
29395622307

Pull #559

github

web-flow
Merge f07c8a0b6 into 809bff55b
Pull Request #559: feat: language-tag picker for literal placeholders

2086 of 7605 branches covered (27.43%)

Branch coverage included in aggregate %.

4020 of 12635 relevant lines covered (31.82%)

4.8 hits per line

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

72.07
src/main/java/com/knowledgepixels/nanodash/component/StatementItem.java
1
package com.knowledgepixels.nanodash.component;
2

3
import com.knowledgepixels.nanodash.template.ContextType;
4
import com.knowledgepixels.nanodash.template.Template;
5
import com.knowledgepixels.nanodash.template.TemplateContext;
6
import com.knowledgepixels.nanodash.template.UnificationException;
7
import org.apache.wicket.AttributeModifier;
8
import org.apache.wicket.Component;
9
import org.apache.wicket.ajax.AjaxEventBehavior;
10
import org.apache.wicket.ajax.AjaxRequestTarget;
11
import org.apache.wicket.behavior.AttributeAppender;
12
import org.apache.wicket.markup.html.WebMarkupContainer;
13
import org.apache.wicket.markup.html.basic.Label;
14
import org.apache.wicket.markup.html.form.FormComponent;
15
import org.apache.wicket.markup.html.list.ListItem;
16
import org.apache.wicket.markup.html.list.ListView;
17
import org.apache.wicket.markup.html.panel.Panel;
18
import org.apache.wicket.model.IModel;
19
import org.eclipse.rdf4j.model.IRI;
20
import org.eclipse.rdf4j.model.Statement;
21
import org.eclipse.rdf4j.model.Value;
22
import org.eclipse.rdf4j.model.ValueFactory;
23
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
24
import org.nanopub.MalformedNanopubException;
25
import org.nanopub.NanopubAlreadyFinalizedException;
26
import org.nanopub.NanopubCreator;
27
import org.nanopub.vocabulary.NTEMPLATE;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

31
import java.io.Serializable;
32
import java.util.*;
33

34
/**
35
 * Represents a single item in a statement, which can be a subject, predicate, or object.
36
 */
37
public class StatementItem extends Panel {
38

39
    private TemplateContext context;
40
    private IRI statementId;
41
    private List<IRI> statementPartIds = new ArrayList<>();
15✔
42
    private List<WebMarkupContainer> viewElements = new ArrayList<>();
15✔
43
    private List<RepetitionGroup> repetitionGroups = new ArrayList<>();
15✔
44
    private boolean repetitionGroupsChanged = true;
9✔
45
    private Set<IRI> iriSet = new HashSet<>();
15✔
46
    private boolean isMatched = false;
9✔
47
    private static final Logger logger = LoggerFactory.getLogger(StatementItem.class);
9✔
48

49
    /**
50
     * Constructor for creating a StatementItem with a specific ID and statement ID.
51
     *
52
     * @param id          the Wicket component ID
53
     * @param statementId the IRI of the statement this item represents
54
     * @param context     the template context containing information about the template and its items
55
     */
56
    public StatementItem(String id, IRI statementId, TemplateContext context) {
57
        super(id);
9✔
58

59
        this.statementId = statementId;
9✔
60
        this.context = context;
9✔
61
        setOutputMarkupId(true);
12✔
62

63
        if (isGrouped()) {
9✔
64
            statementPartIds.addAll(getTemplate().getStatementIris(statementId));
27✔
65
        } else {
66
            statementPartIds.add(statementId);
15✔
67
        }
68

69
        addRepetitionGroup();
6✔
70

71
        ListView<WebMarkupContainer> v = new ListView<WebMarkupContainer>("statement-group", viewElements) {
48✔
72

73
            @Override
74
            protected void populateItem(ListItem<WebMarkupContainer> item) {
75
                item.add(item.getModelObject());
×
76
            }
×
77

78
        };
79
        v.setOutputMarkupId(true);
12✔
80
        add(v);
27✔
81
    }
3✔
82

83
    /**
84
     * Adds a new repetition group to this StatementItem with a default RepetitionGroup.
85
     */
86
    public void addRepetitionGroup() {
87
        addRepetitionGroup(new RepetitionGroup());
18✔
88
    }
3✔
89

90
    /**
91
     * Adds a new repetition group to this StatementItem.
92
     *
93
     * @param rg the RepetitionGroup to add
94
     */
95
    public void addRepetitionGroup(RepetitionGroup rg) {
96
        repetitionGroups.add(rg);
15✔
97
        repetitionGroupsChanged = true;
9✔
98
    }
3✔
99

100
    /**
101
     * {@inheritDoc}
102
     */
103
    @Override
104
    protected void onBeforeRender() {
105
        if (repetitionGroupsChanged) {
×
106
            updateViewElements();
×
107
            finalizeValues();
×
108
        }
109
        repetitionGroupsChanged = false;
×
110
        super.onBeforeRender();
×
111
    }
×
112

113
    private void updateViewElements() {
114
        viewElements.clear();
×
115
        boolean first = true;
×
116
        for (RepetitionGroup r : repetitionGroups) {
×
117
            if (isGrouped() && !first) {
×
118
                viewElements.add(new HorizontalLine("statement"));
×
119
            }
120
            viewElements.addAll(r.getShownStatementParts());
×
121
            boolean isOnly = repetitionGroups.size() == 1;
×
122
            boolean isLast = repetitionGroups.get(repetitionGroups.size() - 1) == r;
×
123
            r.addRepetitionButton.setVisible(!context.isReadOnly() && isRepeatable() && isLast);
×
124
            r.removeRepetitionButton.setVisible(!context.isReadOnly() && isRepeatable() && !isOnly);
×
125
            r.optionalMark.setVisible(isOnly);
×
126
            first = false;
×
127
        }
×
128
        String htmlClassString = "";
×
129
        if (!context.isReadOnly()) {
×
130
            if (isOptional()) {
×
131
                htmlClassString += "nanopub-optional ";
×
132
            }
133
            if (isAdvanced()) {
×
134
                htmlClassString += "advanced ";
×
135
            }
136
        }
137
        boolean singleItem = context.getStatementItems().size() == 1;
×
138
        boolean repeatableOrRepeated = (!context.isReadOnly() && isRepeatable()) || (context.isReadOnly() && getRepetitionCount() > 1);
×
139
        if ((isGrouped() || repeatableOrRepeated) && !singleItem) {
×
140
            htmlClassString += "nanopub-group ";
×
141
        }
142
        if (!htmlClassString.isEmpty()) {
×
143
            add(new AttributeModifier("class", htmlClassString));
×
144
        }
145
    }
×
146

147
    /**
148
     * Adds the triples of this statement item to the given NanopubCreator.
149
     *
150
     * @param npCreator the NanopubCreator to which the triples will be added
151
     * @throws org.nanopub.MalformedNanopubException        if the statement item is not properly set up
152
     * @throws org.nanopub.NanopubAlreadyFinalizedException if the NanopubCreator has already been finalized
153
     */
154
    public void addTriplesTo(NanopubCreator npCreator) throws MalformedNanopubException, NanopubAlreadyFinalizedException {
155
        if (hasEmptyElements()) {
9✔
156
            if (isOptional()) {
9✔
157
                return;
3✔
158
            } else {
159
                throw new MalformedNanopubException("Field of statement not set.");
15✔
160
            }
161
        }
162
        for (RepetitionGroup rg : repetitionGroups) {
33✔
163
            rg.addTriplesTo(npCreator);
9✔
164
        }
3✔
165
    }
3✔
166

167
    private Template getTemplate() {
168
        return context.getTemplate();
12✔
169
    }
170

171
    /**
172
     * Returns the number of the repetition groups for this statement item.
173
     *
174
     * @return the number of repetition groups
175
     */
176
    public int getRepetitionCount() {
177
        return repetitionGroups.size();
12✔
178
    }
179

180
    /**
181
     * Returns whether the statement is optional.
182
     */
183
    public boolean isOptional() {
184
        return repetitionGroups.size() == 1 && getTemplate().isOptionalStatement(statementId);
45!
185
    }
186

187
    /**
188
     * Returns whether the statement is advanced.
189
     */
190
    public boolean isAdvanced() {
191
        return getTemplate().isAdvancedStatement(statementId);
×
192
    }
193

194
    /**
195
     * Checks if this statement item is grouped.
196
     *
197
     * @return true if the statement item is grouped, false otherwise
198
     */
199
    public boolean isGrouped() {
200
        return getTemplate().isGroupedStatement(statementId);
18✔
201
    }
202

203
    /**
204
     * Checks if this statement item is repeatable.
205
     *
206
     * @return true if the statement item is repeatable, false otherwise
207
     */
208
    public boolean isRepeatable() {
209
        return getTemplate().isRepeatableStatement(statementId);
18✔
210
    }
211

212
    /**
213
     * Checks if this statement item has empty elements.
214
     *
215
     * @return true if any of the repetition groups has empty elements, false otherwise
216
     */
217
    public boolean hasEmptyElements() {
218
        return repetitionGroups.get(0).hasEmptyElements();
21✔
219
    }
220

221
    /**
222
     * Returns the set of IRIs associated with this statement item.
223
     *
224
     * @return a set of IRIs
225
     */
226
    public Set<IRI> getIriSet() {
227
        return iriSet;
9✔
228
    }
229

230
    /**
231
     * Checks if this statement item will match any triple.
232
     *
233
     * @return true if it will match any triple, false otherwise
234
     */
235
    public boolean willMatchAnyTriple() {
236
        return repetitionGroups.get(0).matches(dummyStatementList);
×
237
    }
238

239
    /**
240
     * Fills this statement item with the provided list of statements, matching them against the repetition groups.
241
     *
242
     * @param statements the list of statements to match against
243
     * @throws com.knowledgepixels.nanodash.template.UnificationException if the statements cannot be unified with this statement item
244
     */
245
    public void fill(List<Statement> statements) throws UnificationException {
246
        if (isMatched) return;
9!
247
        if (repetitionGroups.size() == 1) {
15!
248
            RepetitionGroup rg = repetitionGroups.get(0);
18✔
249
            if (rg.matches(statements)) {
12✔
250
                rg.fill(statements);
12✔
251
            } else {
252
                return;
3✔
253
            }
254
        } else {
3✔
255
            return;
×
256
        }
257
        isMatched = true;
9✔
258
        if (!isRepeatable()) return;
12✔
259
        while (true) {
260
            Set<IRI> modelsBefore = new HashSet<>(context.getComponentModels().keySet());
24✔
261
            List<Statement> statementsBefore = new ArrayList<>(statements);
15✔
262
            RepetitionGroup newGroup = new RepetitionGroup();
15✔
263
            boolean filled;
264
            if (newGroup.matches(statements)) {
12✔
265
                try {
266
                    newGroup.fill(statements);
9✔
267
                    filled = true;
6✔
268
                } catch (UnificationException ex) {
×
269
                    // matches() validates unifiability statelessly, but fill() mutates shared
270
                    // placeholder models via unifyWith as it goes, so binding an earlier part can
271
                    // make a later one non-unifiable ("seemed to work but then didn't"). Treat this
272
                    // like end-of-repetitions rather than letting it abort the whole template fill:
273
                    // roll back the partial statement consumption and discard the trial group.
274
                    logger.warn("Repetition fill failed after matches() succeeded for {}; stopping repetitions of this statement", statementId, ex);
×
275
                    statements.clear();
×
276
                    statements.addAll(statementsBefore);
×
277
                    filled = false;
×
278
                }
3✔
279
            } else {
280
                filled = false;
6✔
281
            }
282
            if (!filled) {
6✔
283
                newGroup.disconnect();
6✔
284
                // The trial group's constructor registered fresh (empty) component
285
                // models for its narrow-scope placeholders (e.g. public-key__N). If
286
                // left behind, a later real repetition group at the same index reuses
287
                // the stale empty model and skips param seeding — the "derive new
288
                // introduction" empty-fields bug. Drop exactly the models this trial
289
                // group added; shared (wide-scope) models existed before and stay.
290
                context.getComponentModels().keySet().retainAll(modelsBefore);
21✔
291
                return;
3✔
292
            }
293
            addRepetitionGroup(newGroup);
9✔
294
        }
3✔
295
    }
296

297
    /**
298
     * Marks the filling of this statement item as finished, indicating that all values have been filled.
299
     */
300
    public void fillFinished() {
301
        for (RepetitionGroup rg : repetitionGroups) {
33✔
302
            rg.fillFinished();
6✔
303
        }
3✔
304
    }
3✔
305

306
    /**
307
     * Finalizes the values of all ValueItems in this statement item.
308
     */
309
    public void finalizeValues() {
310
        for (RepetitionGroup rg : repetitionGroups) {
33✔
311
            rg.finalizeValues();
6✔
312
        }
3✔
313
    }
3✔
314

315
    /**
316
     * Returns true if the statement item has been matched with a set of statements.
317
     *
318
     * @return true if matched, false otherwise
319
     */
320
    public boolean isMatched() {
321
        return isMatched;
9✔
322
    }
323

324
    /**
325
     * Checks if this statement item is empty, meaning it has no filled repetition groups.
326
     *
327
     * @return true if the statement item is empty, false otherwise
328
     */
329
    public boolean isEmpty() {
330
        return repetitionGroups.size() == 1 && repetitionGroups.get(0).isEmpty();
48✔
331
    }
332

333
    /**
334
     * Represents a group of repetitions for a statement item, containing multiple statement parts.
335
     */
336
    public class RepetitionGroup implements Serializable {
337

338
        private List<StatementPartItem> statementParts;
339
        private List<ValueItem> localItems = new ArrayList<>();
15✔
340
        private boolean filled = false;
9✔
341
        // Optional group members that were left unassigned by a successful fill();
342
        // read-only rendering hides these rows:
343
        private Set<IRI> unmatchedParts = new HashSet<>();
15✔
344

345
        private List<ValueItem> items = new ArrayList<>();
15✔
346

347
        Label addRepetitionButton, removeRepetitionButton, optionalMark;
348

349
        /**
350
         * Constructor for creating a RepetitionGroup.
351
         */
352
        public RepetitionGroup() {
15✔
353
            statementParts = new ArrayList<>();
15✔
354
            for (IRI s : statementPartIds) {
33✔
355
                StatementPartItem statement = new StatementPartItem("statement",
18✔
356
                        makeValueItem("subj", getTemplate().getSubject(s), s),
24✔
357
                        makeValueItem("pred", getTemplate().getPredicate(s), s),
24✔
358
                        makeValueItem("obj", getTemplate().getObject(s), s)
21✔
359
                );
360
                statementParts.add(statement);
15✔
361

362
                // Some of the methods of StatementItem and RepetitionGroup don't work properly before this
363
                // object is fully instantiated:
364
                boolean isFirstGroup = repetitionGroups.isEmpty();
12✔
365
                boolean isFirstLine = statementParts.size() == 1;
27✔
366
                boolean isLastLine = statementParts.size() == statementPartIds.size();
33✔
367
                boolean isOptional = getTemplate().isOptionalStatement(statementId);
18✔
368

369
                if (statementParts.size() == 1 && !isFirstGroup) {
21✔
370
                    statement.add(new AttributeAppender("class", " separate-statement"));
39✔
371
                }
372

373
                // This code adds "advanced" marks similar to "optional":
374
//                if (!context.isReadOnly()) {
375
//                    if (isOptional && isLastLine) {
376
//                        if (isAdvanced()) {
377
//                            optionalMark = new Label("label", "(optional, advanced)");
378
//                        } else {
379
//                            optionalMark = new Label("label", "(optional)");
380
//                        }
381
//                    } else if (isAdvanced()) {
382
//                        optionalMark = new Label("label", "(advanced)");
383
//                    } else {
384
//                        optionalMark = new Label("label", "");
385
//                        optionalMark.setVisible(false);
386
//                    }
387
//                } else {
388
//                    optionalMark = new Label("label", "");
389
//                    optionalMark.setVisible(false);
390
//                }
391

392
                boolean isMemberOptional = isGrouped() && getTemplate().isOptionalStatement(s);
36✔
393

394
                if (!context.isReadOnly() && isOptional && isLastLine) {
24✔
395
                    optionalMark = new Label("label", "(optional)");
24✔
396
                } else {
397
                    optionalMark = new Label("label", "");
21✔
398
                    optionalMark.setVisible(false);
15✔
399
                }
400
                statement.add(optionalMark);
30✔
401
                // Member-level mark, rendered inline on the member's own line; unlike the
402
                // group-level mark it holds per repetition, so it is never toggled off:
403
                Label partOptionalMark = new Label("part-label", "(optional)");
18✔
404
                partOptionalMark.setVisible(!context.isReadOnly() && isMemberOptional);
36✔
405
                statement.add(partOptionalMark);
27✔
406
                if (!context.isReadOnly() && isMemberOptional) {
18✔
407
                    statement.add(new AttributeAppender("class", " nanopub-optional-part"));
39✔
408
                }
409
                if (isLastLine) {
6✔
410
                    addRepetitionButton = new Label("add-repetition", "+");
21✔
411
                    statement.add(addRepetitionButton);
30✔
412
                    addRepetitionButton.add(new AjaxEventBehavior("click") {
74✔
413

414
                        @Override
415
                        protected void onEvent(AjaxRequestTarget target) {
416
                            addRepetitionGroup(new RepetitionGroup());
×
417
                            target.add(StatementItem.this);
×
418
                            target.appendJavaScript("updateElements();");
×
419
                        }
×
420

421
                    });
422
                } else {
423
                    statement.add(new Label("add-repetition", "").setVisible(false));
45✔
424
                }
425
                if (isFirstLine) {
6✔
426
                    removeRepetitionButton = new Label("remove-repetition", "-");
21✔
427
                    statement.add(removeRepetitionButton);
30✔
428
                    removeRepetitionButton.add(new AjaxEventBehavior("click") {
74✔
429

430
                        @Override
431
                        protected void onEvent(AjaxRequestTarget target) {
432
                            RepetitionGroup.this.remove();
×
433
                            target.appendJavaScript("updateElements();");
×
434
                            target.add(StatementItem.this);
×
435
                        }
×
436

437
                    });
438
                } else {
439
                    statement.add(new Label("remove-repetition", "").setVisible(false));
45✔
440
                }
441
            }
3✔
442
        }
3✔
443

444
        private ValueItem makeValueItem(String id, Value value, IRI statementPartId) {
445
            if (isFirst() && value instanceof IRI) {
18✔
446
                iriSet.add((IRI) value);
21✔
447
            }
448
            ValueItem vi = new ValueItem(id, transform(value), statementPartId, this);
30✔
449
            localItems.add(vi);
15✔
450
            items.add(vi);
15✔
451
            return vi;
6✔
452
        }
453

454
        private void disconnect() {
455
            for (ValueItem vi : new ArrayList<>(localItems)) {
42✔
456
                // TODO These remove operations on list are slow. Improve:
457
                localItems.remove(vi);
15✔
458
                items.remove(vi);
15✔
459
                vi.removeFromContext();
6✔
460
            }
3✔
461
        }
3✔
462

463
        /**
464
         * Returns the statement parts.
465
         *
466
         * @return a list of StatementPartItem objects representing the statement parts
467
         */
468
        public List<StatementPartItem> getStatementParts() {
469
            return statementParts;
×
470
        }
471

472
        /**
473
         * Returns the statement parts to render: in read-only contexts, optional group
474
         * members that were left unassigned by fill() are hidden; in editable contexts
475
         * (fresh publish, derive, update) all parts are shown, with skipped members
476
         * rendering as empty fields.
477
         *
478
         * @return a list of StatementPartItem objects to render
479
         */
480
        private List<StatementPartItem> getShownStatementParts() {
481
            if (!context.isReadOnly() || unmatchedParts.isEmpty()) return statementParts;
×
482
            List<StatementPartItem> shown = new ArrayList<>();
×
483
            for (int i = 0; i < statementParts.size(); i++) {
×
484
                if (!unmatchedParts.contains(statementPartIds.get(i))) {
×
485
                    shown.add(statementParts.get(i));
×
486
                }
487
            }
488
            return shown;
×
489
        }
490

491
        /**
492
         * Returns the index of this repetition group in the list of repetition groups.
493
         *
494
         * @return the index of this repetition group
495
         */
496
        public int getRepeatIndex() {
497
            if (!repetitionGroups.contains(this)) return repetitionGroups.size();
33✔
498
            return repetitionGroups.indexOf(this);
18✔
499
        }
500

501
        /**
502
         * Returns the total number of repetition groups for this statement.
503
         *
504
         * @return the number of repetition groups
505
         */
506
        public int getRepetitionCount() {
507
            return StatementItem.this.getRepetitionCount();
×
508
        }
509

510
        /**
511
         * Returns true if the repeat index if the first one.
512
         *
513
         * @return true if the repeat index is 0, false otherwise
514
         */
515
        public boolean isFirst() {
516
            return getRepeatIndex() == 0;
21✔
517
        }
518

519
        /**
520
         * Returns true if the repeat index is the last one.
521
         *
522
         * @return true if the repeat index is the last one, false otherwise
523
         */
524
        public boolean isLast() {
525
            return getRepeatIndex() == repetitionGroups.size() - 1;
×
526
        }
527

528
        private void remove() {
529
            String thisSuffix = getRepeatSuffix();
9✔
530
            for (IRI iriBase : iriSet) {
36✔
531
                // Shift the value model and any derived model (e.g. the language-tag
532
                // model of a language-tag-selectable literal placeholder) alike.
533
                for (String derived : new String[]{"", TemplateContext.LANGUAGE_SUFFIX}) {
75✔
534
                    IRI thisIri = vf.createIRI(iriBase + thisSuffix + derived);
24✔
535
                    if (context.getComponentModels().containsKey(thisIri)) {
21✔
536
                        IModel swapModel1 = (IModel) context.getComponentModels().get(thisIri);
24✔
537
                        for (int i = getRepeatIndex() + 1; i < repetitionGroups.size(); i++) {
39✔
538
                            IModel swapModel2 = (IModel) context.getComponentModels().get(vf.createIRI(iriBase + getRepeatSuffix(i) + derived));
48✔
539
                            if (swapModel1 != null && swapModel2 != null) {
12!
540
                                swapModel1.setObject(swapModel2.getObject());
12✔
541
                            }
542
                            // Drop any retained rawInput so the shifted model value is rendered
543
                            // instead of the user's previous (post-validation-error) entry.
544
                            clearInputForModel(swapModel1);
9✔
545
                            swapModel1 = swapModel2;
6✔
546
                        }
547
                        if (swapModel1 != null) {
6!
548
                            swapModel1.setObject(null);
9✔
549
                            clearInputForModel(swapModel1);
9✔
550
                        }
551
                    }
552
                }
553
            }
3✔
554
            RepetitionGroup lastGroup = repetitionGroups.get(repetitionGroups.size() - 1);
36✔
555
            repetitionGroups.remove(lastGroup);
18✔
556
            for (ValueItem vi : lastGroup.items) {
33✔
557
                vi.removeFromContext();
6✔
558
            }
3✔
559
            repetitionGroupsChanged = true;
12✔
560
        }
3✔
561

562
        private void clearInputForModel(IModel<?> model) {
563
            if (model == null) return;
6!
564
            for (Component c : context.getComponents()) {
39✔
565
                if (c instanceof FormComponent && c.getDefaultModel() == model) {
21!
566
                    ((FormComponent<?>) c).clearInput();
9✔
567
                }
568
            }
3✔
569
        }
3✔
570

571
        private String getRepeatSuffix() {
572
            return getRepeatSuffix(getRepeatIndex());
15✔
573
        }
574

575
        private String getRepeatSuffix(int i) {
576
            if (i == 0) return "";
12✔
577
            // TODO: Check that this double-underscore pattern isn't used otherwise:
578
            return "__" + i;
9✔
579
        }
580

581
        /**
582
         * Returns the template context associated.
583
         *
584
         * @return the TemplateContext
585
         */
586
        public TemplateContext getContext() {
587
            return context;
12✔
588
        }
589

590
        /**
591
         * Checks if this repetition group is optional.
592
         *
593
         * @return true if the repetition group is optional, false otherwise
594
         */
595
        public boolean isOptional() {
596
            if (!getTemplate().isOptionalStatement(statementId)) return false;
30✔
597
            if (repetitionGroups.size() == 0) return true;
21✔
598
            if (repetitionGroups.size() == 1 && repetitionGroups.get(0) == this) return true;
39!
599
            return false;
6✔
600
        }
601

602
        /**
603
         * Checks if the given member statement is effectively optional in this repetition group:
604
         * either the whole group is optional or the member itself carries the optional flag.
605
         * Unlike group-level optionality, the member-level flag holds per repetition, so it is
606
         * not affected by the number of repetition groups.
607
         *
608
         * @param partId the IRI of the member statement to check
609
         * @return true if the member statement is effectively optional, false otherwise
610
         */
611
        public boolean isOptionalPart(IRI partId) {
612
            return isOptional() || getTemplate().isOptionalStatement(partId);
39✔
613
        }
614

615
        private Value transform(Value value) {
616
            if (!(value instanceof IRI)) {
9✔
617
                return value;
6✔
618
            }
619
            IRI iri = (IRI) value;
9✔
620
            String iriString = iri.stringValue();
9✔
621
            iriString = iriString.replaceAll("~~ARTIFACTCODE~~", "~~~ARTIFACTCODE~~~");
15✔
622
            // Only add "__N" to URI from second repetition group on; for the first group, information about
623
            // narrow scopes is not yet complete.
624
            if (getRepeatIndex() > 0 && context.hasNarrowScope(iri)) {
27✔
625
                if (context.getTemplate().isPlaceholder(iri) || context.getTemplate().isLocalResource(iri)) {
42!
626
                    iriString += getRepeatSuffix();
15✔
627
                }
628
            }
629
            return vf.createIRI(iriString);
12✔
630
        }
631

632
        /**
633
         * Adds the triples of this repetition group to the given NanopubCreator.
634
         *
635
         * @param npCreator the NanopubCreator to which the triples will be added
636
         * @throws org.nanopub.NanopubAlreadyFinalizedException if the NanopubCreator has already been finalized
637
         */
638
        public void addTriplesTo(NanopubCreator npCreator) throws NanopubAlreadyFinalizedException {
639
            Template t = getTemplate();
12✔
640
            for (IRI s : statementPartIds) {
36✔
641
                IRI subj = context.processIri((IRI) transform(t.getSubject(s)));
33✔
642
                IRI pred = context.processIri((IRI) transform(t.getPredicate(s)));
33✔
643
                Value obj = context.processValue(transform(t.getObject(s)));
30✔
644
                if (isGrouped() && t.isOptionalStatement(s) && (subj == null || pred == null || obj == null)) {
42!
645
                    // Optional group member without all elements resolved: drop just this
646
                    // triple; the rest of the group is still emitted.
647
                    continue;
3✔
648
                }
649
                if (context.getType() == ContextType.ASSERTION) {
18!
650
                    npCreator.addAssertionStatement(subj, pred, obj);
18✔
651
                } else if (context.getType() == ContextType.PROVENANCE) {
×
652
                    npCreator.addProvenanceStatement(subj, pred, obj);
×
653
                } else if (context.getType() == ContextType.PUBINFO) {
×
654
                    npCreator.addPubinfoStatement(subj, pred, obj);
×
655
                }
656
            }
3✔
657
            for (ValueItem vi : items) {
33✔
658
                if (vi.getComponent() instanceof GuidedChoiceItem) {
12!
659
                    String value = ((GuidedChoiceItem) vi.getComponent()).getModel().getObject();
×
660
                    if (value != null && GuidedChoiceItem.getLabel(value) != null) {
×
661
                        String label = GuidedChoiceItem.getLabel(value);
×
662
                        if (label.length() > 1000) label = label.substring(0, 997) + "...";
×
663
                        try {
664
                            npCreator.addPubinfoStatement(vf.createIRI(value), NTEMPLATE.HAS_LABEL_FROM_API, vf.createLiteral(label));
×
665
                        } catch (IllegalArgumentException ex) {
×
666
                            logger.error("Could not create IRI from value: {}", value, ex);
×
667
                        }
×
668
                    }
669
                }
670
            }
3✔
671
        }
3✔
672

673
        private boolean hasEmptyElements() {
674
            for (IRI s : statementPartIds) {
36✔
675
                // Optional group members may stay empty; they are dropped at triple-creation
676
                // time and must not block or drop the rest of the group:
677
                if (isGrouped() && getTemplate().isOptionalStatement(s)) continue;
33✔
678
                if (context.processIri((IRI) transform(getTemplate().getSubject(s))) == null) return true;
45✔
679
                if (context.processIri((IRI) transform(getTemplate().getPredicate(s))) == null) return true;
39!
680
                if (context.processValue(transform(getTemplate().getObject(s))) == null) return true;
42✔
681
            }
3✔
682
            return false;
6✔
683
        }
684

685
        /**
686
         * Checks if this repetition group is empty, meaning it has no filled items.
687
         *
688
         * @return true if the repetition group is empty, false otherwise
689
         */
690
        public boolean isEmpty() {
691
            for (IRI s : statementPartIds) {
36✔
692
                Template t = getTemplate();
12✔
693
                IRI subj = t.getSubject(s);
12✔
694
                if (t.isPlaceholder(subj) && context.hasNarrowScope(subj) && context.processIri((IRI) transform(subj)) != null)
57!
695
                    return false;
6✔
696
                IRI pred = t.getPredicate(s);
12✔
697
                if (t.isPlaceholder(pred) && context.hasNarrowScope(pred) && context.processIri((IRI) transform(pred)) != null)
12!
698
                    return false;
×
699
                Value obj = t.getObject(s);
12✔
700
                if (obj instanceof IRI && t.isPlaceholder((IRI) obj) && context.hasNarrowScope((IRI) obj) && context.processValue(transform(obj)) != null)
69!
701
                    return false;
6✔
702
            }
3✔
703
            return true;
6✔
704
        }
705

706
        /**
707
         * Checks if this repetition group matches the provided list of statements.
708
         *
709
         * @param statements the list of statements to match against
710
         * @return true if the repetition group matches, false otherwise
711
         */
712
        public boolean matches(List<Statement> statements) {
713
            if (filled) return false;
9!
714
            // matches() must agree with fill(): because fill() binds shared placeholder models as it
715
            // goes, a valid assignment can only be confirmed by actually simulating those bindings.
716
            // We do exactly that (with backtracking) but on a copy and then restore the models, so
717
            // matches() stays side-effect free.
718
            Map<IRI, Object> snapshot = snapshotModels();
9✔
719
            Set<IRI> unmatchedBefore = new HashSet<>(unmatchedParts);
18✔
720
            try {
721
                List<Statement> copy = new ArrayList<>(statements);
15✔
722
                // A match must consume at least one statement: with optional members, an
723
                // assignment that skips every part would otherwise "match" without evidence,
724
                // which would also keep the repetition loop in fill() spinning forever.
725
                return assignParts(0, copy) && copy.size() < statements.size();
48!
726
            } finally {
727
                restoreModels(snapshot);
9✔
728
                unmatchedParts.clear();
9✔
729
                unmatchedParts.addAll(unmatchedBefore);
15✔
730
            }
731
        }
732

733
        /**
734
         * Fills this repetition group with the provided list of statements, unifying them with the statement parts.
735
         *
736
         * @param statements the list of statements to match against
737
         * @throws UnificationException if the statements cannot be unified with this repetition group
738
         */
739
        public void fill(List<Statement> statements) throws UnificationException {
740
            if (filled) throw new UnificationException("Already filled");
9!
741
            // Backtracking assignment: a greedy first-match can bind a shared placeholder in a way
742
            // that blocks a later part even though a consistent assignment exists. assignParts tries
743
            // alternatives and rolls back the model bindings between attempts. On success the matched
744
            // statements are removed from the list and the winning bindings are kept.
745
            unmatchedParts.clear();
9✔
746
            int sizeBefore = statements.size();
9✔
747
            if (!assignParts(0, statements) || statements.size() == sizeBefore) {
27!
748
                throw new UnificationException("Unification seemed to work but then didn't");
×
749
            }
750
            filled = true;
9✔
751
        }
3✔
752

753
        /**
754
         * Tries to assign each remaining statement part (from index {@code partIndex} on) to a distinct
755
         * statement in {@code available} such that all bindings of shared placeholder models are mutually
756
         * consistent. Uses backtracking: on a failed branch the model bindings are restored and the next
757
         * candidate is tried. On success the chosen statements are removed from {@code available} and the
758
         * winning bindings remain applied to the component models.
759
         *
760
         * @param partIndex the index of the next statement part to assign
761
         * @param available the statements still available for assignment (mutated in place)
762
         * @return true if all remaining parts could be assigned consistently
763
         */
764
        private boolean assignParts(int partIndex, List<Statement> available) {
765
            if (partIndex == statementParts.size()) return true;
21✔
766
            StatementPartItem p = statementParts.get(partIndex);
18✔
767
            for (int i = 0; i < available.size(); i++) {
24✔
768
                Statement s = available.get(i);
15✔
769
                Map<IRI, Object> snapshot = snapshotModels();
9✔
770
                if (unifyPart(p.getPredicate(), s.getPredicate())  // checking predicate first optimizes performance
27✔
771
                        && unifyPart(p.getSubject(), s.getSubject())
21✔
772
                        && unifyPart(p.getObject(), s.getObject())) {
15✔
773
                    available.remove(i);
12✔
774
                    if (assignParts(partIndex + 1, available)) return true;
27✔
775
                    available.add(i, s);
12✔
776
                }
777
                restoreModels(snapshot);
9✔
778
            }
779
            IRI partId = statementPartIds.get(partIndex);
21✔
780
            if (isGrouped() && getTemplate().isOptionalStatement(partId)) {
30✔
781
                // Optional group member with no consistent candidate: leave it unassigned and
782
                // move on. Trying all candidates first (above) keeps fills maximal — a member
783
                // is only skipped when no consistent assignment exists.
784
                unmatchedParts.add(partId);
15✔
785
                if (assignParts(partIndex + 1, available)) return true;
27!
786
                unmatchedParts.remove(partId);
×
787
            }
788
            return false;
6✔
789
        }
790

791
        /**
792
         * Checks unifiability and, if unifiable, applies the binding. Returns false instead of throwing,
793
         * so the caller can backtrack. (A partial binding left behind here is rolled back by the caller's
794
         * model snapshot.)
795
         */
796
        private boolean unifyPart(ValueItem item, Value v) {
797
            if (!item.isUnifiableWith(v)) return false;
18✔
798
            try {
799
                item.unifyWith(v);
9✔
800
                return true;
6✔
801
            } catch (UnificationException ex) {
×
802
                return false;
×
803
            }
804
        }
805

806
        /**
807
         * Snapshots the current values of all shared component models, so a trial binding can be rolled back.
808
         */
809
        private Map<IRI, Object> snapshotModels() {
810
            Map<IRI, Object> snapshot = new HashMap<>();
12✔
811
            for (Map.Entry<IRI, IModel<?>> e : context.getComponentModels().entrySet()) {
42✔
812
                snapshot.put(e.getKey(), e.getValue().getObject());
30✔
813
            }
3✔
814
            return snapshot;
6✔
815
        }
816

817
        /**
818
         * Restores component model values captured by {@link #snapshotModels()}.
819
         */
820
        @SuppressWarnings("unchecked")
821
        private void restoreModels(Map<IRI, Object> snapshot) {
822
            Map<IRI, IModel<?>> models = context.getComponentModels();
15✔
823
            for (Map.Entry<IRI, Object> e : snapshot.entrySet()) {
33✔
824
                IModel<?> m = models.get(e.getKey());
18✔
825
                if (m != null) ((IModel<Object>) m).setObject(e.getValue());
18!
826
            }
3✔
827
        }
3✔
828

829
        /**
830
         * Marks the filling of this repetition group as finished, indicating that all values have been filled.
831
         */
832
        public void fillFinished() {
833
            for (ValueItem vi : items) {
33✔
834
                vi.fillFinished();
6✔
835
            }
3✔
836
        }
3✔
837

838
        /**
839
         * Finalizes the values of all ValueItems in this repetition group.
840
         */
841
        public void finalizeValues() {
842
            for (ValueItem vi : items) {
33✔
843
                vi.finalizeValues();
6✔
844
            }
3✔
845
        }
3✔
846

847
    }
848

849
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
850
    private static final List<Statement> dummyStatementList = new ArrayList<Statement>(Collections.singletonList(vf.createStatement(vf.createIRI("http://dummy.com/"), vf.createIRI("http://dummy.com/"), vf.createIRI("http://dummy.com/"))));
51✔
851

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