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

knowledgepixels / nanodash / 29307332916

14 Jul 2026 04:59AM UTC coverage: 29.177% (+0.7%) from 28.504%
29307332916

push

github

web-flow
Merge pull request #554 from knowledgepixels/feat/optional-statements-in-groups

feat: support optional statements inside statement groups

1959 of 7463 branches covered (26.25%)

Branch coverage included in aggregate %.

3865 of 12498 relevant lines covered (30.92%)

4.63 hits per line

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

63.55
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;
×
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);
39!
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();
×
530
            for (IRI iriBase : iriSet) {
×
531
                IRI thisIri = vf.createIRI(iriBase + thisSuffix);
×
532
                if (context.getComponentModels().containsKey(thisIri)) {
×
533
                    IModel swapModel1 = (IModel) context.getComponentModels().get(thisIri);
×
534
                    for (int i = getRepeatIndex() + 1; i < repetitionGroups.size(); i++) {
×
535
                        IModel swapModel2 = (IModel) context.getComponentModels().get(vf.createIRI(iriBase + getRepeatSuffix(i)));
×
536
                        if (swapModel1 != null && swapModel2 != null) {
×
537
                            swapModel1.setObject(swapModel2.getObject());
×
538
                        }
539
                        // Drop any retained rawInput so the shifted model value is rendered
540
                        // instead of the user's previous (post-validation-error) entry.
541
                        clearInputForModel(swapModel1);
×
542
                        swapModel1 = swapModel2;
×
543
                    }
544
                    if (swapModel1 != null) {
×
545
                        swapModel1.setObject(null);
×
546
                        clearInputForModel(swapModel1);
×
547
                    }
548
                }
549
            }
×
550
            RepetitionGroup lastGroup = repetitionGroups.get(repetitionGroups.size() - 1);
×
551
            repetitionGroups.remove(lastGroup);
×
552
            for (ValueItem vi : lastGroup.items) {
×
553
                vi.removeFromContext();
×
554
            }
×
555
            repetitionGroupsChanged = true;
×
556
        }
×
557

558
        private void clearInputForModel(IModel<?> model) {
559
            if (model == null) return;
×
560
            for (Component c : context.getComponents()) {
×
561
                if (c instanceof FormComponent && c.getDefaultModel() == model) {
×
562
                    ((FormComponent<?>) c).clearInput();
×
563
                }
564
            }
×
565
        }
×
566

567
        private String getRepeatSuffix() {
568
            return getRepeatSuffix(getRepeatIndex());
15✔
569
        }
570

571
        private String getRepeatSuffix(int i) {
572
            if (i == 0) return "";
6!
573
            // TODO: Check that this double-underscore pattern isn't used otherwise:
574
            return "__" + i;
9✔
575
        }
576

577
        /**
578
         * Returns the template context associated.
579
         *
580
         * @return the TemplateContext
581
         */
582
        public TemplateContext getContext() {
583
            return context;
12✔
584
        }
585

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

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

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

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

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

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

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

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

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

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

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

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

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

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

843
    }
844

845
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
846
    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✔
847

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