source: java/main/src/main/java/com/framsticks/core/InstanceUtils.java @ 96

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

HIGHLIGHTS:

  • cleanup Instance management
    • extract Instance interface
    • extract Instance common algorithms to InstanceUtils?
  • fix closing issues: Ctrl+C or window close button

properly shutdown whole program

by Java Framsticks framework

  • fix parsing and printing of all request types
  • hide exception passing in special handle method of closures
    • substantially improve readability of closures
    • basically enable use of exception in asynchronous closures

(thrown exception is transported back to the caller)

  • implement call request on both sides

CHANGELOG:
Further improve calling.

Improve instance calling.

Calling is working on both sides.

Improve exception handling in testing.

Waiters do not supercede other apllication exception being thrown.

Finished parsing and printing of all request types (with tests).

Move implementation and tests of request parsing to Request.

Add tests for Requests.

Improve waits in asynchronours tests.

Extract more algorithms to InstanceUtils?.

Extract Instance.resolve to InstanceUtils?.

Improve naming.

Improve passing exception in InstanceClient?.

Hide calling of passed functor in StateCallback?.

Hide Exception passing in asynchronous closures.

Hide exception passing in Future.

Make ResponseCallback? an abstract class.

Make Future an abstract class.

Minor change.

Move getPath to Path.to()

Move bindAccess to InstanceUtils?.

Extract common things to InstanceUtils?.

Fix synchronization bug in Connection.

Move resolve to InstanceUtils?.

Allow names of Joinable to be dynamic.

Add support for set request server side.

More fixes in communication.

Fix issues with parsing in connection.

Cut new line characters when reading.

More improvements.

Migrate closures to FramsticksException?.

Several changes.

Extract resolveAndFetch to InstanceUtils? algorithms.

Test resolving and fetching.

More fixes with function signature deduction.

Do not print default values in SimpleAbstractAccess?.

Add test of FramsClass? printing.

Improve FramsticksException? messages.

Add explicit dispatcher synchronization feature.

Rework assertions in tests.

Previous solution was not generic enough.

Allow addition of joinables to collection after start.

Extract SimulatorInstance? from RemoteInstance?.

Remove PrivateJoinableCollection?.

Improve connections.

Move shutdown hook to inside the Monitor.

It should work in TestNG tests, but it seems that
hooks are not called.

In ServerTest? client connects to testing server.

Move socket initialization to receiver thread.

Add proper closing on Ctrl+C (don't use signals).

Fix bugs with server accepting connections.

Merge Entity into Joinable.

Reworking ServerInstance?.

Extract more algorithm to InstanceUtils?.

Extract some common functionality from AbstractInstance?.

Functions were placed in InstanceUtils?.

Hide registry of Instance.

Use ValueParam? in Instance interface.

Minor change.

Extract Instance interface.

Old Instance is now AbstractInstance?.

File size: 7.7 KB
Line 
1package com.framsticks.core;
2
3import java.util.List;
4
5import javax.annotation.Nonnull;
6
7import org.apache.log4j.Logger;
8
9import com.framsticks.communication.File;
10import com.framsticks.params.AccessInterface;
11import com.framsticks.params.CompositeParam;
12import com.framsticks.params.FramsClass;
13import com.framsticks.params.ListAccess;
14import com.framsticks.params.Param;
15import com.framsticks.params.ValueParam;
16import com.framsticks.params.types.ObjectParam;
17import com.framsticks.params.types.ProcedureParam;
18import com.framsticks.parsers.Loaders;
19import com.framsticks.parsers.MultiParamLoader;
20import com.framsticks.util.AbstractStateFunctor;
21import com.framsticks.util.FramsticksException;
22import com.framsticks.util.StateFunctor;
23import com.framsticks.util.dispatching.Future;
24import com.framsticks.util.dispatching.RunAt;
25
26import static com.framsticks.util.dispatching.Dispatching.*;
27
28public final class InstanceUtils {
29
30        private static final Logger log = Logger.getLogger(InstanceUtils.class.getName());
31
32        private InstanceUtils() {
33        }
34
35        public static @Nonnull FramsClass processFetchedInfo(Instance instance, File file) {
36                assert instance.isActive();
37                FramsClass framsClass = Loaders.loadFramsClass(file.getContent());
38                if ("/".equals(file.getPath())) {
39                        if (instance.getRoot().getParam().getContainedTypeName() == null) {
40                                instance.setRoot(new Node(Param.build().name("Instance").id(instance.getName()).type("o " + framsClass.getId()).finish(CompositeParam.class), instance.getRoot().getObject()));
41                        }
42                }
43                instance.putInfoIntoCache(framsClass);
44                return framsClass;
45        }
46
47        public static void findInfo(final Path path, final Future<FramsClass> future) {
48                Instance instance = path.getInstance();
49                assert instance.isActive();
50                final String name = path.getTop().getParam().getContainedTypeName();
51                final FramsClass framsClass = instance.getInfoFromCache(name);
52                if (framsClass != null) {
53                        log.trace("info for " + name + " found in cache");
54                        future.pass(framsClass);
55                        return;
56                }
57                instance.fetchInfo(path, future);
58        }
59
60        public static void processFetchedValues(Path path, List<File> files) {
61                Instance instance = path.getInstance();
62                assert instance.isActive();
63                assert files.size() == 1;
64                assert path.isTheSame(files.get(0).getPath());
65                Node node = path.getTop();
66                MultiParamLoader loader = new MultiParamLoader();
67                loader.setNewSource(files.get(0).getContent());
68                loader.addBreakCondition(MultiParamLoader.Status.AfterObject);
69
70                try {
71                        if (node.getParam() instanceof ObjectParam) {
72                                loader.addAccessInterface(InstanceUtils.bindAccess(instance, node));
73                                loader.go();
74                                instance.notifyOfFetch(path);
75                                return;
76                        }
77
78                        ListAccess listAccess = ((ListAccess) InstanceUtils.bindAccess(instance, node));
79                        assert listAccess != null;
80                        listAccess.clearValues();
81
82                        AccessInterface elementAccess = listAccess.getElementAccess();
83                        loader.addAccessInterface(elementAccess);
84                        MultiParamLoader.Status status;
85                        while ((status = loader.go()) != MultiParamLoader.Status.Finished) {
86                                if (status == MultiParamLoader.Status.AfterObject) {
87                                        AccessInterface accessInterface = loader.getLastAccessInterface();
88
89                                        String id = listAccess.computeIdentifierFor(accessInterface.getSelected());
90                                        //TODO listAccessParam
91                                        Param param = Param.build().forAccess(accessInterface).id(id).finish();
92                                        Object child = accessInterface.getSelected();
93                                        accessInterface.select(null);
94                                        assert child != null;
95                                        InstanceUtils.bindAccess(instance, node).set((ValueParam) param, child);
96                                }
97                        }
98
99                        instance.notifyOfFetch(path);
100                } catch (Exception e) {
101                        log.error("exception occurred while loading: " + e);
102                }
103
104        }
105
106        public static void resolveAndFetch(final Instance instance, final String targetPath, final Future<Path> future) {
107                assert instance.isActive();
108                InstanceUtils.resolve(instance, targetPath, new Future<Path>(future) {
109                        @Override
110                        protected void result(final Path path) {
111                                assert path.isResolved(targetPath);
112                                //TODO Future
113                                instance.fetchValues(path, new AbstractStateFunctor(future) {
114                                        @Override
115                                        public void call() {
116                                                future.pass(path);
117                                        }
118                                });
119                        }
120                });
121        }
122
123
124        public static void resolve(final Path path, final Future<Path> future) {
125                final Instance instance = path.getInstance();
126                assert instance.isActive();
127                if (path.getTop().getObject() != null) {
128                        if (getInfoFromCache(path) != null) {
129                                future.pass(path);
130                                return;
131                        }
132                        InstanceUtils.findInfo(path, new Future<FramsClass>(future) {
133                                @Override
134                                protected void result(FramsClass result) {
135                                        future.pass(path);
136                                }
137                        });
138                        return;
139                }
140                InstanceUtils.findInfo(path, new Future<FramsClass>(future) {
141                        @Override
142                        protected void result(FramsClass result) {
143                                assert instance.isActive();
144                                assert path.getTop().getParam().isMatchingContainedName(result.getId());
145                                Path p = (path.getTop().getParam().getContainedTypeName() != null ? path : path.tryFindResolution());
146                                future.pass(InstanceUtils.createIfNeeded(p));
147                        }
148                });
149        }
150
151        public static Path createIfNeeded(Instance instance, String path) {
152                assert instance.isActive();
153                Path p;
154                while (!(p = Path.to(instance, path)).isResolved(path)) {
155                        instance.create(p);
156                }
157                return p;
158        }
159
160        public static Path createIfNeeded(Path path) {
161                Instance instance = path.getInstance();
162                assert instance.isActive();
163                if (path.isResolved()) {
164                        return path;
165                }
166                return instance.create(path);
167        }
168
169        public static @Nonnull AccessInterface bindAccess(Instance instance, String path) {
170                return bindAccess(Path.to(instance, path));
171        }
172
173        public static @Nonnull AccessInterface bindAccess(Instance instance, Node node) {
174                assert instance.isActive();
175                assert node.getObject() != null;
176
177                try {
178                        AccessInterface access = instance.prepareAccess(node.getParam());
179                        if (access == null) {
180                                throw new FramsticksException().msg("failed to prepare access for param").arg("param", node.getParam());
181                        }
182                        return access.select(node.getObject());
183                } catch (FramsticksException e) {
184                        throw new FramsticksException().msg("failed to prepare access for param").arg("param", node.getParam()).cause(e);
185                        // log.error("failed to bind access for " + node.getParam() + ": " + e);
186                }
187        }
188
189        public static @Nonnull AccessInterface bindAccess(Path path) {
190                assert path.getInstance().isActive();
191                path.assureResolved();
192                return bindAccess(path.getInstance(), path.getTop());
193        }
194
195        public static void storeValue(final Path path, final ValueParam param, final Object value, final StateFunctor stateFunctor) {
196                final Instance instance = path.getInstance();
197
198                dispatchIfNotActive(instance, new RunAt<Instance>() {
199                        @Override
200                        public void run() {
201                                instance.storeValue(path, param, value, stateFunctor);
202                        }
203                });
204        }
205
206        public static void call(final Path path, final ProcedureParam param, final Object[] arguments, final Future<Object> future) {
207                final Instance instance = path.getInstance();
208
209                dispatchIfNotActive(instance, new RunAt<Instance>() {
210                        @Override
211                        public void run() {
212                                instance.call(path, param, arguments, future);
213                        }
214                });
215        }
216
217        /** This might not be correct. */
218        public static void resolve(final Instance instance, final String targetPath, final Future<Path> future) {
219                dispatchIfNotActive(instance, new RunAt<Instance>() {
220
221                        @Override
222                        public void run() {
223                                instance.resolve(Path.to(instance, targetPath), new Future<Path>(future) {
224                                        @Override
225                                        protected void result(Path result) {
226                                                assert result.getInstance().isActive();
227                                                if (result.isResolved(targetPath)) {
228                                                        future.pass(result);
229                                                        return;
230                                                }
231                                                resolve(result.getInstance(), targetPath, future);
232                                        }
233                                });
234                        }
235                });
236        }
237
238        public static FramsClass getInfoFromCache(Path path) {
239                assert path.getInstance().isActive();
240                return path.getInstance().getInfoFromCache(path.getTop().getParam().getContainedTypeName());
241        }
242}
Note: See TracBrowser for help on using the repository browser.