99526368e8cc3e21e1b92451f4dd915db45d40ba
[simantics/platform.git] / bundles / org.simantics.document.server / src / org / simantics / document / server / request / NodesRequest.java
1 package org.simantics.document.server.request;
2
3 import java.util.Collection;
4 import java.util.Collections;
5 import java.util.Set;
6
7 import org.simantics.db.AsyncReadGraph;
8 import org.simantics.db.ReadGraph;
9 import org.simantics.db.common.request.AsyncReadRequest;
10 import org.simantics.db.exception.DatabaseException;
11 import org.simantics.db.layer0.request.VariableChildren;
12 import org.simantics.db.layer0.request.VariableRead;
13 import org.simantics.db.layer0.variable.Variable;
14 import org.simantics.db.procedure.AsyncProcedure;
15 import org.simantics.structural.stubs.StructuralResource2;
16 import org.simantics.utils.threads.logger.ITask;
17 import org.simantics.utils.threads.logger.ThreadLogger;
18
19 import gnu.trove.set.hash.THashSet;
20
21 public class NodesRequest extends VariableRead<Set<Variable>> {
22
23     public NodesRequest(Variable var) {
24         super(var);
25     }
26
27     @Override
28     public Set<Variable> perform(ReadGraph graph) throws DatabaseException {
29
30         ITask task = DocumentRequest.PROFILE ? ThreadLogger.task(this) : null;
31
32         StructuralResource2.getInstance(graph);
33         if(variable == null)
34             return Collections.emptySet();
35
36         Set<Variable> nodes = new THashSet<Variable>();
37
38         Collection<Variable> children = graph.syncRequest(new VariableChildren(variable));
39
40         graph.syncRequest(new AsyncReadRequest() {
41
42             @Override
43             public void run(AsyncReadGraph graph) throws DatabaseException {
44
45                 for(Variable child : children) {
46                     graph.asyncRequest(new NodesRequest2(child), new AsyncProcedure<Set<Variable>>() {
47
48                         @Override
49                         public void execute(AsyncReadGraph graph, Set<Variable> result) {
50                             synchronized(nodes) {
51                                 nodes.addAll(result);
52                             }
53                         }
54
55                         @Override
56                         public void exception(AsyncReadGraph graph, Throwable throwable) {
57                         }
58                         
59                     });
60                 }
61
62             }
63
64         });
65
66         if(DocumentRequest.PROFILE) task.finish();
67
68         return nodes;
69
70     }
71
72 }