hefeixia
2021-02-18 5b8c95c760840f09910730943b21391e47187315
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
package frame.object.data;
 
import chat.server.call.IJSONWriter;
import frame.object.meta.EntityMeta;
 
 
public class EntityTree extends EntitySet {
 
    private EntitySet rootSet;
    
    public EntityTree(EntityMeta tableMeta) {
        super(tableMeta);
        rootSet = new EntitySet(tableMeta);
    }
 
    public EntitySet getChildren(ID parentId) throws DataException {
        Node parent = getNode(parentId);
        
        if (parent == null) {
            return null;
        }
        
        return parent.children;
    }
 
    public Node getNode(ID id) throws DataException {
        Entity result = getEntity(id);
        return (Node) result;
    }
 
    public EntitySet getRootSet() {
        return rootSet;
    }
    
    public void initRelation() throws DataException {
        initFamilyRelation();
        initLevelRelation();
    }
    
    public void initFamilyRelation() throws DataException {
        for (Entity entity: this) {
            Node node = (Node) entity;
            ID parentId = node.getParentId();
            
            if (parentId.isEmpty()) {
                node.level = 0;
                rootSet.append(node);
                continue;
            }
            
            Node parent = getNode(parentId);
            
            if (parent == null) {
                continue;
            }
            
            parent.addChild(node);
        }
    }
    
    public void initLevelRelation() throws DataException {
        for (Entity entity: rootSet) {
            Node node = (Node) entity;
            doInitLevelRelation(node);
        }
    }
 
    private void doInitLevelRelation(Node parent) {
        EntitySet children = parent.getChildren();
        
        for (Entity entity: children) {
            Node child = (Node) entity;
            child.level = parent.level + 1;
            
            EntitySet offsprings = child.getChildren();
            
            for (Entity offspring: offsprings) {
                doInitLevelRelation((Node)offspring);
            }
        }
    }
    
    @Override
    public void writeJSONObject(IJSONWriter writer) {
        writer.beginArray();
        
        for (Entity entity: rootSet) {
            Node node = (Node)entity;
            node.writeJSONObject(writer);
        }
        
        writer.endArray();    
    }
 
}