public static void removeSubGraph(MGraph mGraph, TripleCollection subGraph)
throws NoSuchSubGraphException {
//point to triples of mGraph that are to be removed (if something is removed)
final Set<Triple> removingTriples = new HashSet<Triple>();
//we first check only the grounded triples and put the non-grounded in here:
final TripleCollection unGroundedTriples = new SimpleMGraph();
for (Triple triple : subGraph) {
if (isGrounded(triple)) {
if (!mGraph.contains(triple)) {
throw new NoSuchSubGraphException();
}
removingTriples.add(triple);
} else {
unGroundedTriples.add(triple);
}
}
//we first remove the context of bnodes we find in object position
OBJ_BNODE_LOOP: while (true) {
final Triple triple = getTripleWithBNodeObject(unGroundedTriples);
if (triple == null) {
break;
}
final GraphNode objectGN = new GraphNode(triple.getObject(), unGroundedTriples);
NonLiteral subject = triple.getSubject();
Graph context = objectGN.getNodeContext();
Iterator<Triple> potentialIter = mGraph.filter(subject, triple.getPredicate(), null);
while (potentialIter.hasNext()) {
try {
final Triple potentialTriple = potentialIter.next();
BNode potentialMatch = (BNode)potentialTriple.getObject();
final Graph potentialContext = new GraphNode(potentialMatch, mGraph).getNodeContext();
if (potentialContext.equals(context)) {
removingTriples.addAll(potentialContext);
unGroundedTriples.removeAll(context);
continue OBJ_BNODE_LOOP;
}
} catch (ClassCastException e) {
continue;
}
}
throw new NoSuchSubGraphException();
}
SUBJ_BNODE_LOOP: while (true) {
final Triple triple = getTripleWithBNodeSubject(unGroundedTriples);
if (triple == null) {
break;
}
final GraphNode subjectGN = new GraphNode(triple.getSubject(), unGroundedTriples);
Resource object = triple.getObject();
if (object instanceof BNode) {
object = null;
}
Graph context = subjectGN.getNodeContext();
Iterator<Triple> potentialIter = mGraph.filter(null, triple.getPredicate(), object);
while (potentialIter.hasNext()) {
try {
final Triple potentialTriple = potentialIter.next();
BNode potentialMatch = (BNode)potentialTriple.getSubject();
final Graph potentialContext = new GraphNode(potentialMatch, mGraph).getNodeContext();
if (potentialContext.equals(context)) {
removingTriples.addAll(potentialContext);
unGroundedTriples.removeAll(context);
continue SUBJ_BNODE_LOOP;
}
} catch (ClassCastException e) {
continue;
}