This repository has been archived by the owner on Jul 18, 2022. It is now read-only.
/
GraphNode.java
720 lines (638 loc) · 22.7 KB
/
GraphNode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.clerezza.utils;
import org.apache.clerezza.*;
import org.apache.clerezza.implementation.TripleImpl;
import org.apache.clerezza.implementation.in_memory.SimpleGraph;
import org.apache.clerezza.implementation.literal.LiteralFactory;
import java.util.*;
import java.util.concurrent.locks.Lock;
/**
* This class represents a node in the context of a graph. It provides
* utility methods to explore and modify its neighbourhood. The method
* modifying the graph will throw an {@link UnsupportedOperationException}
* it the underlying Graph in immutable (i.e. is a {@link ImmutableGraph}.
*
* @author reto, mir
* @since 0.2
*/
public class GraphNode {
private final RDFTerm resource;
private final Graph graph;
/**
* Create a GraphNode representing resource within graph.
*
* @param resource the resource this GraphNode represents
* @param graph the Graph that describes the resource
*/
public GraphNode(RDFTerm resource, Graph graph) {
if (resource == null) {
throw new IllegalArgumentException("resource may not be null");
}
if (graph == null) {
throw new IllegalArgumentException("graph may not be null");
}
this.resource = resource;
this.graph = graph;
}
/**
* Gets the graph the node represented by this instance is in
*
* @return the graph of this GraphNode
*/
public Graph getGraph() {
return graph;
}
/**
* Gets the unwrapped node
*
* @return the node represented by this GraphNode
*/
public RDFTerm getNode() {
return resource;
}
/**
* Deletes the context of a node
*
* @see #getNodeContext()
*/
public void deleteNodeContext() {
for (Triple triple : getNodeContext()) {
graph.remove(triple);
}
}
/**
* The context of a node are the triples containing a node
* as subject or object and recursively the context of the b-nodes in any
* of these statements.
*
* The triples in the ImmutableGraph returned by this method contain the same bnode
* instances as in the original graph.
*
* @return the context of the node represented by the instance
*/
public ImmutableGraph getNodeContext() {
Lock l = readLock();
l.lock();
try {
final HashSet<RDFTerm> dontExpand = new HashSet<RDFTerm>();
dontExpand.add(resource);
if (resource instanceof IRI) {
return getContextOf((IRI) resource, dontExpand).getImmutableGraph();
}
return getContextOf(resource, dontExpand).getImmutableGraph();
} finally {
l.unlock();
}
}
private Graph getContextOf(IRI node, final Set<RDFTerm> dontExpand) {
final String uriPrefix = node.getUnicodeString() + '#';
return getContextOf(node, dontExpand, new Acceptor() {
@Override
public boolean expand(RDFTerm resource) {
if (resource instanceof BlankNode) {
return true;
}
if (resource instanceof IRI) {
return ((IRI) resource).getUnicodeString().startsWith(uriPrefix);
}
return false;
}
});
}
/**
* Returns the context of a <code>BlankNodeOrIRI</code>
*
* @param node
* @param dontExpand a list of bnodes at which to stop expansion, if node
* is a BlankNode it should be contained (potentially faster)
* @return the context of a node
*/
private Graph getContextOf(RDFTerm node, final Set<RDFTerm> dontExpand) {
return getContextOf(node, dontExpand, new Acceptor() {
@Override
public boolean expand(RDFTerm resource) {
if (resource instanceof BlankNode) {
return true;
}
return false;
}
});
}
private interface Acceptor {
boolean expand(RDFTerm resource);
}
private Graph getContextOf(RDFTerm node, final Set<RDFTerm> dontExpand, Acceptor acceptor) {
Graph result = new SimpleGraph();
if (node instanceof BlankNodeOrIRI) {
Iterator<Triple> forwardProperties = graph.filter((BlankNodeOrIRI) node, null, null);
while (forwardProperties.hasNext()) {
Triple triple = forwardProperties.next();
result.add(triple);
RDFTerm object = triple.getObject();
if (acceptor.expand(object) && !dontExpand.contains(object)) {
dontExpand.add(object);
result.addAll(getContextOf(object, dontExpand, acceptor));
}
}
}
Iterator<Triple> backwardProperties = graph.filter(null, null, node);
while (backwardProperties.hasNext()) {
Triple triple = backwardProperties.next();
result.add(triple);
BlankNodeOrIRI subject = triple.getSubject();
if (acceptor.expand(subject) && !dontExpand.contains(subject)) {
dontExpand.add(subject);
result.addAll(getContextOf(subject, dontExpand, acceptor));
}
}
return result;
}
private <T> Iterator<T> getTypeSelectedObjects(IRI property, final Class<T> type) {
final Iterator<RDFTerm> objects = getObjects(property);
return new Iterator<T>() {
T next = prepareNext();
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
T result = next;
next = prepareNext();
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
private T prepareNext() {
while (objects.hasNext()) {
RDFTerm nextObject = objects.next();
if (type.isAssignableFrom(nextObject.getClass())) {
return (T) nextObject;
}
}
return null;
}
};
}
public Iterator<Literal> getLiterals(IRI property) {
final Iterator<RDFTerm> objects = getObjects(property);
return new Iterator<Literal>() {
Literal next = prepareNext();
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Literal next() {
Literal result = next;
next = prepareNext();
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
private Literal prepareNext() {
while (objects.hasNext()) {
RDFTerm nextObject = objects.next();
if (nextObject instanceof Literal) {
return (Literal) nextObject;
}
}
return null;
}
};
}
/**
* Count the number of triples in the underlying triple-collection
* with this node as subject and a specified property as predicate.
*
* @param property the property to be examined
* @return the number of triples in the underlying triple-collection
* which meet the specified condition
*/
public int countObjects(IRI property) {
return countTriples(graph.filter((BlankNodeOrIRI) resource, property, null));
}
private int countTriples(final Iterator<Triple> triples) {
int count = 0;
while (triples.hasNext()) {
triples.next();
count++;
}
return count;
}
/**
* Get the objects of statements with this node as subject and a specified
* property as predicate.
*
* @param property the property
* @return
*/
public Iterator<RDFTerm> getObjects(IRI property) {
if (resource instanceof BlankNodeOrIRI) {
final Iterator<Triple> triples = graph.filter((BlankNodeOrIRI) resource, property, null);
return new Iterator<RDFTerm>() {
@Override
public boolean hasNext() {
return triples.hasNext();
}
@Override
public RDFTerm next() {
final Triple triple = triples.next();
if (triple != null) {
return triple.getObject();
} else {
return null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
} else {
return new Iterator<RDFTerm>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public RDFTerm next() {
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
}
/**
* Checks wether this node has the given property with the given value.
* If the given value is null, then it is checked if this node has the
* specified property regardless of its value.
*
* @param property
* @param object
* @return true if the node represented by this object is the subject of a
* statement with the given prediate and object, false otherwise
*/
public boolean hasProperty(IRI property, RDFTerm object) {
Lock l = readLock();
l.lock();
try {
Iterator<RDFTerm> objects = getObjects(property);
if (object == null) {
return objects.hasNext();
}
while (objects.hasNext()) {
if (objects.next().equals(object)) {
return true;
}
}
return false;
} finally {
l.unlock();
}
}
/**
* Count the number of triples in the underlying triple-collection
* with this node as object and a specified property as predicate.
*
* @param property the property to be examined
* @return the number of triples in the underlying triple-collection
* which meet the specified condition
*/
public int countSubjects(IRI property) {
Lock l = readLock();
l.lock();
try {
return countTriples(graph.filter(null, property, resource));
} finally {
l.unlock();
}
}
/**
* Get the subjects of statements with this node as object and a specified
* property as predicate.
*
* @param property the property
* @return
*/
public Iterator<BlankNodeOrIRI> getSubjects(IRI property) {
final Iterator<Triple> triples = graph.filter(null, property, resource);
return new Iterator<BlankNodeOrIRI>() {
@Override
public boolean hasNext() {
return triples.hasNext();
}
@Override
public BlankNodeOrIRI next() {
return triples.next().getSubject();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
public Iterator<IRI> getIRIObjects(IRI property) {
return getTypeSelectedObjects(property, IRI.class);
}
/**
* Get all available properties as an {@link Iterator}{@literal <}{@link IRI}{@literal >}.
* You can use <code>getObjects(IRI property)</code> to get the values of
* each property
*
* @return an iterator over properties of this node
*/
public Iterator<IRI> getProperties() {
if (resource instanceof BlankNodeOrIRI) {
final Iterator<Triple> triples = graph.filter((BlankNodeOrIRI) resource, null, null);
return getUniquePredicates(triples);
} else {
return new Iterator<IRI>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public IRI next() {
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
}
/**
* Get all inverse properties as an {@link Iterator}{@literal <}{@link IRI}{@literal >}.
* You can use <code>getSubject(IRI property)</code> to get the values of
* each inverse property
*
* @return an iterator over properties pointing to this node
*/
public Iterator<IRI> getInverseProperties() {
final Iterator<Triple> triples = graph.filter(null, null, resource);
return getUniquePredicates(triples);
}
/**
* @param triples
* @returnan {@link Iterator}<{@link IRI}> containing the predicates from
* an {@link Iterator}<{@link Triple}>
*/
private Iterator<IRI> getUniquePredicates(final Iterator<Triple> triples) {
final Set<IRI> resultSet = new HashSet<IRI>();
while (triples.hasNext()) {
resultSet.add(triples.next().getPredicate());
}
return resultSet.iterator();
}
/**
* Adds a property to the node with the specified predicate and object
*
* @param predicate
* @param object
*/
public void addProperty(IRI predicate, RDFTerm object) {
if (resource instanceof BlankNodeOrIRI) {
graph.add(new TripleImpl((BlankNodeOrIRI) resource, predicate, object));
} else {
throw new RuntimeException("Literals cannot be the subject of a statement");
}
}
/**
* Coverts the value into a typed literals and sets it as object of the
* specified property
*
* @param property the predicate of the triple to be created
* @param value the value of the typed literal object
*/
public void addPropertyValue(IRI property, Object value) {
addProperty(property,
LiteralFactory.getInstance().createTypedLiteral(value));
}
/**
* Adds a property to the node with the inverse of the specified predicate and object
* In other words <code>subject</code> will be related via the property <code>relation</code> to this node.
*
* @param predicate
* @param subject
*/
public void addInverseProperty(IRI predicate, RDFTerm subject) {
if (subject instanceof BlankNodeOrIRI) {
graph.add(new TripleImpl((BlankNodeOrIRI) subject, predicate, resource));
} else {
throw new RuntimeException("Literals cannot be the subject of a statement");
}
}
/**
* creates and returns an <code>RdfList</code> for the node and
* Graph represented by this object.
*
* @return a List to easy access the rdf:List represented by this node
*/
public List<RDFTerm> asList() {
if (resource instanceof BlankNodeOrIRI) {
return new RdfList((BlankNodeOrIRI) resource, graph);
} else {
throw new RuntimeException("Literals cannot be the subject of a List");
}
}
/**
* Deletes all statement with the current node as subject and the specified
* predicate
*
* @param predicate
*/
public void deleteProperties(IRI predicate) {
if (resource instanceof BlankNodeOrIRI) {
Iterator<Triple> tripleIter = graph.filter((BlankNodeOrIRI) resource, predicate, null);
Collection<Triple> toDelete = new ArrayList<Triple>();
while (tripleIter.hasNext()) {
Triple triple = tripleIter.next();
toDelete.add(triple);
}
for (Triple triple : toDelete) {
graph.remove(triple);
}
}
}
/**
* Delete property to the node with the specified predicate and object
*
* @param predicate
* @param object
*/
public void deleteProperty(IRI predicate, RDFTerm object) {
if (resource instanceof BlankNodeOrIRI) {
graph.remove(new TripleImpl((BlankNodeOrIRI) resource, predicate, object));
}
}
@Override
public String toString() {
return resource.toString();
}
/**
* Replaces the graph node resouce with the specified <code>BlankNodeOrIRI</code>.
* The resource is only replaced where it is either subject or object.
*
* @param replacement
* @return a GraphNode representing the replecement node
*/
public GraphNode replaceWith(BlankNodeOrIRI replacement) {
return replaceWith(replacement, false);
}
/**
* Replaces the graph node resouce with the specified <code>BlankNodeOrIRI</code>.
* Over the boolean <code>checkPredicate</code> it can be specified if the
* resource should also be replaced where it is used as predicate.
*
* @param replacement
* @param checkPredicates
* @return a GraphNode representing the replecement node
*/
public GraphNode replaceWith(BlankNodeOrIRI replacement, boolean checkPredicates) {
Graph newTriples = new SimpleGraph();
if (!(resource instanceof Literal)) {
Iterator<Triple> subjectTriples = graph.filter((BlankNodeOrIRI) resource, null,
null);
while (subjectTriples.hasNext()) {
Triple triple = subjectTriples.next();
Triple newTriple = new TripleImpl(replacement, triple.getPredicate(),
triple.getObject());
subjectTriples.remove();
newTriples.add(newTriple);
}
graph.addAll(newTriples);
newTriples.clear();
}
Iterator<Triple> objectTriples = graph.filter(null, null, resource);
while (objectTriples.hasNext()) {
Triple triple = objectTriples.next();
Triple newTriple = new TripleImpl(triple.getSubject(),
triple.getPredicate(), replacement);
objectTriples.remove();
newTriples.add(newTriple);
}
graph.addAll(newTriples);
newTriples.clear();
if (checkPredicates && replacement instanceof IRI
&& resource instanceof IRI) {
Iterator<Triple> predicateTriples = graph.filter(null,
(IRI) resource, null);
while (predicateTriples.hasNext()) {
Triple triple = predicateTriples.next();
Triple newTriple = new TripleImpl(triple.getSubject(),
(IRI) replacement, triple.getObject());
predicateTriples.remove();
newTriples.add(newTriple);
}
graph.addAll(newTriples);
}
return new GraphNode(replacement, graph);
}
/**
* Returns a iterator containing all objects of the triples where this
* graph node is the subject and has the specified property. The objects
* are returned as <code>GraphNode</code>s.
*
* @param property
* @return
*/
public Iterator<GraphNode> getObjectNodes(IRI property) {
final Iterator<RDFTerm> objects = this.getObjects(property);
return new Iterator<GraphNode>() {
@Override
public boolean hasNext() {
return objects.hasNext();
}
@Override
public GraphNode next() {
RDFTerm object = objects.next();
return new GraphNode(object, graph);
}
@Override
public void remove() {
objects.remove();
}
};
}
/**
* Returns a iterator containing all subjects of the triples where this
* graph node is the object and has the specified property. The subjects
* are returned as <code>GraphNode</code>s.
*
* @param property
* @return
*/
public Iterator<GraphNode> getSubjectNodes(IRI property) {
final Iterator<BlankNodeOrIRI> subjects = this.getSubjects(property);
return new Iterator<GraphNode>() {
@Override
public boolean hasNext() {
return subjects.hasNext();
}
@Override
public GraphNode next() {
RDFTerm object = subjects.next();
return new GraphNode(object, graph);
}
@Override
public void remove() {
subjects.remove();
}
};
}
/**
* @param obj
* @return true if obj is an instance of the same class represening the same
* node in the same graph, subclasses may have different identity criteria.
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj.getClass().equals(getClass()))) {
return false;
}
GraphNode other = (GraphNode) obj;
return getNode().equals(other.getNode())
&& getGraph().equals(other.getGraph());
}
@Override
public int hashCode() {
return 13 * getNode().hashCode() + getGraph().hashCode();
}
/**
* @return a ReadLock if the underlying ImmutableGraph is a LockableGraph it returns its lock, otherwise null
*/
public Lock readLock() {
return getGraph().getLock().readLock();
}
/**
* @return
*/
public Lock writeLock() {
return (getGraph()).getLock().writeLock();
}
}