source: java/main/src/main/java/com/framsticks/core/Instance.java @ 85

Last change on this file since 85 was 85, checked in by psniegowski, 11 years ago

HIGHLIGHTS:

  • upgrade to Java 7
    • use try-multi-catch clauses
    • use try-with-resources were appropriate
  • configure FindBugs? (use mvn site and then navigate in browser to the report)
    • remove most bugs found
  • parametrize Dispatching environment (Dispatcher, RunAt?) to enforce more control on the place of closures actual call

CHANGELOG:
Rework FavouritesXMLFactory.

FindBugs?. Thread start.

FindBugs?. Minor change.

FindBugs?. Iterate over entrySet.

FindBugs?. Various.

FindBug?.

FindBug?. Encoding.

FindBug?. Final fields.

FindBug?.

Remove synchronization bug in ClientConnection?.

Experiments with findbugs.

Finish parametrization.

Make RunAt? an abstract class.

More changes in parametrization.

More changes in parametrizing dispatching.

Several changes to parametrize tasks.

Rename Runnable to RunAt?.

Add specific framsticks Runnable.

Add JSR305 (annotations).

Add findbugs reporting.

More improvements to ParamBuilder? wording.

Make FramsClass? accept also ParamBuilder?.

Change wording of ParamBuilder?.

Change wording of Request creation.

Use Java 7 exception catch syntax.

Add ScopeEnd? class.

Upgrade to Java 7.

File size: 9.0 KB
Line 
1package com.framsticks.core;
2
3import com.framsticks.communication.*;
4import com.framsticks.params.*;
5import com.framsticks.params.types.ObjectParam;
6import com.framsticks.parsers.Loaders;
7import com.framsticks.parsers.MultiParamLoader;
8import com.framsticks.util.*;
9import com.framsticks.util.UnsupportedOperationException;
10import com.framsticks.util.dispatching.Dispatching;
11import com.framsticks.util.dispatching.Future;
12import com.framsticks.util.lang.Casting;
13import org.apache.log4j.Logger;
14import com.framsticks.util.dispatching.RunAt;
15
16import java.util.*;
17
18/**
19 * @author Piotr Sniegowski
20 */
21public abstract class Instance extends Entity {
22
23        private static final Logger log = Logger.getLogger(Instance.class.getName());
24
25
26        protected Node root;
27
28        public Set<InstanceListener> listeners = new HashSet<InstanceListener>();
29
30        public Instance() {
31        }
32
33        @Override
34        protected void run() {
35                super.run();
36                root = new Node((CompositeParam)Param.build().name("Instance").id(name).type("o").finish(), null);
37                com.framsticks.model.Package.register(registry);
38        }
39
40        protected void fetchInfo(Path path, Future<FramsClass> future) {
41                future.result(null, new UnsupportedOperationException());
42        }
43
44        public void resolve(Path path, Future<Path> future) {
45                assert isActive();
46                assert path.isOwner(this);
47                if (path.getTop().getObject() != null) {
48                        future.result(path, null);
49                        return;
50                }
51                AccessInterface access = bindAccess(path.getUnder());
52                Object object = access.get(path.getTop().getParam(), Object.class);
53                if (object == null) {
54                        future.result(path, null);
55                        return;
56                }
57                future.result(path.appendResolution(object), null);
58        }
59
60        public void fetchValue(Path path, Param param, StateFunctor stateFunctor) {
61                stateFunctor.call(null);
62        }
63
64        public void fetchValues(Path path, StateFunctor stateFunctor) {
65                stateFunctor.call(null);
66        }
67
68        protected void tryRegisterOnChangeEvents(Path path) {
69
70        }
71
72        public void storeValue(Path path, Param param, Object value, final StateFunctor stateFunctor) {
73                assert isActive();
74                invokeLater(new RunAt<Instance>() {
75                        @Override
76                        public void run() {
77                                stateFunctor.call(new UnsupportedOperationException());
78                        }
79                });
80        }
81
82        protected void fireRun(Exception e) {
83                for (InstanceListener l : this.listeners) {
84                        l.onRun(e);
85                }
86        }
87
88        protected void fireStop(Exception e) {
89                for (InstanceListener l : this.listeners) {
90                        l.onStop(e);
91                }
92        }
93
94        public void addListener(final InstanceListener listener) {
95                assert Dispatching.isThreadSafe();
96                Dispatching.invokeLaterOrNow(this, new RunAt<Instance>() {
97                        @Override
98                        public void run() {
99                                listeners.add(listener);
100                        }
101                });
102        }
103
104        public void removeListener(final InstanceListener listener) {
105                assert Dispatching.isThreadSafe();
106                Dispatching.invokeLaterOrNow(this, new RunAt<Instance>() {
107                        @Override
108                        public void run() {
109                                listeners.remove(listener);
110                        }
111                });
112        }
113
114
115        protected void fireListChange(Path path, ListChange change) {
116                assert isActive();
117                for (InstanceListener l : this.listeners) {
118                        l.onListChange(path, change);
119                }
120        }
121
122        protected void fireFetch(Path path) {
123                assert isActive();
124                for (InstanceListener l : this.listeners) {
125                        l.onFetch(path);
126                }
127        }
128
129
130        public final FramsClass getInfoFromCache(Path path) {
131                return getInfoFromCache(path.getTop().getParam().getContainedTypeName());
132        }
133
134
135        public FramsClass getInfoFromCache(String id) {
136                assert isActive();
137                return registry.getInfoFromCache(id);
138        }
139
140        protected Registry registry = new Registry();
141
142        public AccessInterface createAccess(String name) {
143                assert isActive();
144                return registry.createAccess(name);
145        }
146
147
148        // TODO: make ValueParam
149        public <T> T get(Node node, Param childParam, Class<T> type) {
150                return bindAccess(node).get((ValueParam) childParam, type);
151        }
152
153        public void findInfo(final Path path, final Future<FramsClass> future) {
154                assert isActive();
155                final String name = path.getTop().getParam().getContainedTypeName();
156                final FramsClass framsClass = getInfoFromCache(name);
157                if (framsClass != null) {
158                        log.trace("info for " + name + " found in cache");
159                        future.result(framsClass, null);
160                        return;
161                }
162                fetchInfo(path, future);
163        }
164
165        public final AccessInterface bindAccess(Node node) {
166                assert node.getObject() != null;
167                AccessInterface access = registry.prepareAccess(node.getParam());
168                if (access == null) {
169                        log.error("missing access for: " + node.getParam());
170                        return null;
171                }
172                access.select(node.getObject());
173                return access;
174        }
175
176        public final <T> T getParam(Path path, String id, Class<T> type) {
177                return Casting.tryCast(type, registry.prepareAccess(path.getTop().getParam()).getParam(id));
178        }
179
180        public final AccessInterface bindAccess(Path path) {
181                assert path.isResolved();
182                return bindAccess(path.getTop());
183        }
184
185        public void resolve(final String targetPath, final Future<Path> future) {
186                assert isActive();
187                final Path path = getPath(targetPath);
188                resolve(path, new Future<Path>() {
189                        @Override
190                        public void result(Path result, Exception e) {
191                                assert isActive();
192                                if (e != null) {
193                                        future.result(path, e);
194                                        return;
195                                }
196                                if (path.isResolved(targetPath)) {
197                                        future.result(path, null);
198                                        return;
199                                }
200                                if (path.isResolved()) {
201                                        future.result(path, new Exception("testing"));
202                                        return;
203                                }
204                                resolve(targetPath, future);
205                        }
206                });
207        }
208
209        public void resolveAndFetch(final String targetPath, final Future<Path> future) {
210                assert isActive();
211                resolve(targetPath, new Future<Path>() {
212                        @Override
213                        public void result(final Path path, Exception e) {
214                                if (e != null) {
215                                        future.result(path, e);
216                                        return;
217                                }
218                                assert path.isResolved(targetPath);
219                                fetchValues(path, new StateFunctor() {
220                                        @Override
221                                        public void call(Exception e) {
222                                                future.result(path, e);
223                                        }
224                                });
225                        }
226                });
227        }
228
229        public Path createIfNeeded(String path) {
230                Path p;
231                while (!(p = getPath(path)).isResolved(path)) {
232                        create(p);
233                }
234                return p;
235        }
236
237        public Path createIfNeeded(Path path) {
238                assert isActive();
239                if (path.isResolved()) {
240                        return path;
241                }
242                return create(path);
243        }
244
245        public Path create(Path path) {
246                assert isActive();
247                assert !path.isResolved();
248                Path resolved = path.tryFindResolution();
249                if (!resolved.isResolved()) {
250                        log.debug("creating: " + path);
251                        AccessInterface access = registry.prepareAccess(path.getTop().getParam());
252                        assert access != null;
253                        Object child = access.createAccessee();
254                        assert child != null;
255                        if (path.size() == 1) {
256                                root = new Node(root.getParam(), child);
257                        } else {
258                                bindAccess(path.getUnder()).set(path.getTop().getParam(), child);
259                        }
260                        resolved = path.appendResolution(child);
261                }
262                tryRegisterOnChangeEvents(resolved);
263                return resolved;
264        }
265
266
267
268
269        public FramsClass processFetchedInfo(File file) {
270                assert isActive();
271                FramsClass framsClass = Loaders.loadFramsClass(file.getContent());
272                if ("/".equals(file.getPath())) {
273                        if (root.getParam().getContainedTypeName() == null) {
274                                root = new Node((CompositeParam)Param.build().name("Instance").id(name).type("o " + framsClass.getId()).finish(), root.getObject());
275                        }
276                }
277                registry.putInfoIntoCache(framsClass);
278                return framsClass;
279        }
280
281        public void processFetchedValues(Path path, List<File> files) {
282                assert isActive();
283                assert files.size() == 1;
284                assert path.isTheSame(files.get(0).getPath());
285                Node node = path.getTop();
286                MultiParamLoader loader = new MultiParamLoader();
287                loader.setNewSource(files.get(0).getContent());
288                loader.addBreakCondition(MultiParamLoader.Status.AfterObject);
289
290                try {
291                        if (node.getParam() instanceof ObjectParam) {
292                                loader.addAccessInterface(bindAccess(node));
293                                loader.go();
294                                fireFetch(path);
295        //            for (NodeListener l : listeners) {
296        //                l.onChange(this);
297        //            }
298                                return;
299                        }
300
301                        ListAccess listAccess = ((ListAccess)bindAccess(node));
302                        assert listAccess != null;
303                        listAccess.clearValues();
304
305                        AccessInterface elementAccess = listAccess.getElementAccess();
306                        loader.addAccessInterface(elementAccess);
307                        MultiParamLoader.Status status;
308                        while ((status = loader.go()) != MultiParamLoader.Status.Finished) {
309                                if (status == MultiParamLoader.Status.AfterObject) {
310                                        AccessInterface accessInterface = loader.getLastAccessInterface();
311
312                                        String id = listAccess.computeIdentifierFor(accessInterface.getSelected());
313                                        Param param = Param.build().type("o " + accessInterface.getId()).id(id).finish();
314                                        Object child = accessInterface.getSelected();
315                                        accessInterface.select(null);
316                                        assert child != null;
317                                        bindAccess(node).set((ValueParam) param, child);
318                                }
319                        }
320
321                        fireFetch(path);
322        //        for (NodeListener l : listeners) {
323        //            l.onChange(this);
324        //        }
325                } catch (Exception e) {
326                        log.error("exception occurred while loading: " + e);
327                }
328
329        }
330
331        public static Iterator<String> splitPath(String path) {
332                List<String> list = new LinkedList<String>();
333                for (String s : path.split("/")) {
334                        if (!s.isEmpty()) {
335                                list.add(s);
336                        }
337                }
338                return list.iterator();
339        }
340
341        public Registry getRegistry() {
342                return registry;
343        }
344
345        public Path getPath(String textual) {
346                return new Path(this, textual);
347        }
348
349        public Path getRootPath() {
350                return getPath("/");
351        }
352}
353
Note: See TracBrowser for help on using the repository browser.