001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package com.tc.objectserver.managedobject;
005:
006: import com.tc.object.ObjectID;
007:
008: import java.util.HashMap;
009: import java.util.HashSet;
010: import java.util.Iterator;
011: import java.util.Map;
012: import java.util.Set;
013:
014: //TODO::This class doesnt maintain backreferences anymore. Should be renamed.
015: public class BackReferences {
016:
017: private final Map nodes;
018:
019: private final Set parents;
020:
021: public BackReferences() {
022: parents = new HashSet();
023: nodes = new HashMap();
024: }
025:
026: public void addBackReference(ObjectID child, ObjectID parent) {
027: if (child.isNull())
028: return;
029: Node c = getOrCreateNode(child);
030: Node p = getOrCreateNode(parent);
031: p.addChild(c);
032: parents.add(parent);
033: }
034:
035: private Node getOrCreateNode(ObjectID id) {
036: Node n = (Node) nodes.get(id);
037: if (n == null) {
038: n = new Node(id);
039: nodes.put(id, n);
040: }
041: return n;
042: }
043:
044: public Set getAllParents() {
045: return new HashSet(parents);
046: }
047:
048: public Set addReferencedChildrenTo(Set objectIDs,
049: Set interestedParents) {
050: for (Iterator i = interestedParents.iterator(); i.hasNext();) {
051: ObjectID pid = (ObjectID) i.next();
052: Node p = getOrCreateNode(pid);
053: p.addAllReferencedChildrenTo(objectIDs);
054: }
055: return objectIDs;
056: }
057:
058: private static class Node {
059:
060: private final ObjectID id;
061: private final Set children;
062:
063: public Node(ObjectID id) {
064: this .id = id;
065: this .children = new HashSet();
066: }
067:
068: public int hashCode() {
069: return id.hashCode();
070: }
071:
072: public ObjectID getID() {
073: return id;
074: }
075:
076: public boolean equals(Object o) {
077: if (o instanceof Node) {
078: Node other = (Node) o;
079: return this .id.equals(other.id);
080: }
081: return false;
082: }
083:
084: public void addChild(Node c) {
085: children.add(c);
086: }
087:
088: public Set addAllReferencedChildrenTo(Set objectIDs) {
089: for (Iterator i = children.iterator(); i.hasNext();) {
090: Node child = (Node) i.next();
091: if (!objectIDs.contains(child.getID())) {
092: objectIDs.add(child.getID());
093: child.addAllReferencedChildrenTo(objectIDs);
094: }
095: }
096: return objectIDs;
097: }
098:
099: public String toString() {
100: // XXX:: dont just print the contents of children. That might cause a recursive loop
101: return "Node(" + id + ") : children = " + children.size();
102: }
103: }
104:
105: }
|