/interpreter/tags/at2dist091109/src/edu/vub/at/actors/natives/ELActor.java

http://ambienttalk.googlecode.com/ · Java · 627 lines · 334 code · 49 blank · 244 comment · 16 complexity · b2ceba55cbd7bea004fd849cb9c8c8a0 MD5 · raw file

  1. /**
  2. * AmbientTalk/2 Project
  3. * ELActor.java created on 27-dec-2006 at 16:17:23
  4. * (c) Programming Technology Lab, 2006 - 2007
  5. * Authors: Tom Van Cutsem & Stijn Mostinckx
  6. *
  7. * Permission is hereby granted, free of charge, to any person
  8. * obtaining a copy of this software and associated documentation
  9. * files (the "Software"), to deal in the Software without
  10. * restriction, including without limitation the rights to use,
  11. * copy, modify, merge, publish, distribute, sublicense, and/or
  12. * sell copies of the Software, and to permit persons to whom the
  13. * Software is furnished to do so, subject to the following
  14. * conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be
  17. * included in all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  21. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  23. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  24. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  26. * OTHER DEALINGS IN THE SOFTWARE.
  27. */
  28. package edu.vub.at.actors.natives;
  29. import java.lang.reflect.InvocationTargetException;
  30. import java.lang.reflect.Method;
  31. import java.util.EventListener;
  32. import edu.vub.at.actors.ATActorMirror;
  33. import edu.vub.at.actors.ATAsyncMessage;
  34. import edu.vub.at.actors.ATFarReference;
  35. import edu.vub.at.actors.eventloops.BlockingFuture;
  36. import edu.vub.at.actors.eventloops.Callable;
  37. import edu.vub.at.actors.eventloops.Event;
  38. import edu.vub.at.actors.eventloops.EventLoop;
  39. import edu.vub.at.actors.id.ATObjectID;
  40. import edu.vub.at.actors.id.ActorID;
  41. import edu.vub.at.actors.net.comm.Address;
  42. import edu.vub.at.eval.Evaluator;
  43. import edu.vub.at.exceptions.InterpreterException;
  44. import edu.vub.at.exceptions.XClassNotFound;
  45. import edu.vub.at.exceptions.XIOProblem;
  46. import edu.vub.at.exceptions.XIllegalOperation;
  47. import edu.vub.at.exceptions.XObjectOffline;
  48. import edu.vub.at.objects.ATAbstractGrammar;
  49. import edu.vub.at.objects.ATClosure;
  50. import edu.vub.at.objects.ATMethod;
  51. import edu.vub.at.objects.ATObject;
  52. import edu.vub.at.objects.ATTable;
  53. import edu.vub.at.objects.ATTypeTag;
  54. import edu.vub.at.objects.mirrors.Reflection;
  55. import edu.vub.at.objects.natives.NATContext;
  56. import edu.vub.at.objects.natives.NATObject;
  57. import edu.vub.at.objects.natives.NATTable;
  58. import edu.vub.at.objects.natives.OBJLexicalRoot;
  59. import edu.vub.at.objects.symbiosis.Symbiosis;
  60. import edu.vub.at.util.logging.Logging;
  61. /**
  62. * An instance of the class ELActor represents a programmer-defined
  63. * AmbientTalk/2 actor. The event queue of the actor event loop serves as the
  64. * actor's 'meta-level' queue.
  65. *
  66. * The events in the 'meta-level' queue are handled by the actor's mirror object.
  67. * This mirror is normally an instance of NATActorMirror, but it can be any
  68. * programmer-defined object that adheres to the ATActorMirror interface.
  69. *
  70. * @author tvcutsem
  71. */
  72. public class ELActor extends EventLoop {
  73. /**
  74. * A thread-local variable that contains the 'default actor' to use
  75. * when there is currently no ELActor event loop thread running.
  76. * This is primarily useful for performing unit tests where an actor
  77. * is automatically created when actor semantics is required.
  78. *
  79. * A warning is printed to the log because using the default actor should
  80. * only be used for testing purposes.
  81. */
  82. private static final ThreadLocal _DEFAULT_ACTOR_ = new ThreadLocal() {
  83. protected synchronized Object initialValue() {
  84. Logging.Actor_LOG.warn("Creating a default actor for thread " + Thread.currentThread());
  85. try {
  86. ELVirtualMachine host = new ELVirtualMachine(
  87. Evaluator.getNil(),
  88. new SharedActorField[] { },
  89. ELVirtualMachine._DEFAULT_GROUP_NAME_);
  90. return host.createEmptyActor().getFarHost();
  91. } catch (InterpreterException e) {
  92. throw new RuntimeException("Failed to initialize default actor: " + e.getMessage());
  93. }
  94. }
  95. };
  96. /**
  97. * Retrieves the currently running actor. If there is no running actor thread,
  98. * this returns the value stored in the thread-local default actor field.
  99. */
  100. public static final ELActor currentActor() {
  101. try {
  102. return ((ELActor) EventLoop.currentEventLoop());
  103. } catch (ClassCastException e) {
  104. // current event loop is not an actor event loop
  105. } catch (IllegalStateException e) {
  106. // current thread is not an event loop
  107. }
  108. Logging.Actor_LOG.warn("Asked for an actor in non-actor thread " + Thread.currentThread());
  109. return (ELActor) _DEFAULT_ACTOR_.get();
  110. }
  111. private ATActorMirror mirror_;
  112. private final ActorID id_;
  113. protected final ELVirtualMachine host_;
  114. protected final ReceptionistsSet receptionists_;
  115. /*
  116. * This object is created when the actor is initialized: i.e. it is the passed
  117. * version of the isolate that was passed to the actor: primitive by the creating actor.
  118. */
  119. private NATObject behaviour_;
  120. public ELActor(ATActorMirror mirror, ELVirtualMachine host) {
  121. super("actor " + mirror.toString());
  122. this.start();
  123. id_ = new ActorID();
  124. mirror_ = mirror;
  125. host_ = host;
  126. receptionists_ = new ReceptionistsSet(this);
  127. }
  128. /** constructor dedicated to initialization of discovery actor */
  129. protected ELActor(ELVirtualMachine host) {
  130. super("discovery actor");
  131. this.start();
  132. id_ = new ActorID();
  133. NATActorMirror mirror = new NATActorMirror(host);
  134. mirror.setActor(this);
  135. mirror_ = mirror;
  136. host_ = host;
  137. receptionists_ = new ReceptionistsSet(this);
  138. }
  139. /**
  140. * Actor event loops handle events by allowing the meta-level events to
  141. * process themselves.
  142. */
  143. public void handle(Event event) {
  144. event.process(mirror_);
  145. }
  146. public ATActorMirror getImplicitActorMirror() { return mirror_; }
  147. public void setActorMirror(ATActorMirror mirror) { mirror_ = mirror; }
  148. public ELVirtualMachine getHost() {
  149. return host_;
  150. }
  151. public ActorID getActorID() {
  152. return id_;
  153. }
  154. public Thread getExecutor() {
  155. return processor_;
  156. }
  157. /**
  158. * Takes offline a given local object such that it is no longer remotely accessible.
  159. * @param object a near reference to the local object to unexport
  160. * @throws XIllegalOperation if the passed object is not part of the export table - i.e. non-remotely accessible.
  161. */
  162. public void takeOffline(ATObject object) throws InterpreterException {
  163. // receptionist set will check whether ATObject is really remote to me
  164. receptionists_.takeOfflineObject(object);
  165. }
  166. /**
  167. * Disconnects a given local object such that it is no longer remotely accessible.
  168. * @param object a near reference to the local object to disconnect
  169. * @throws XIllegalOperation if the passed object is not part of the export table - i.e. non-remotely accessible.
  170. */
  171. public ATObject disconnect(final ATObject object) throws InterpreterException {
  172. // receptionist set will check whether ATObject is really remote to me
  173. return receptionists_.disconnect(object);
  174. }
  175. /**
  176. * Resolve the given object id into a local reference. There are three cases to
  177. * consider:
  178. * A) The given id designates an object local to this actor: the returned object
  179. * will be a **near** reference to the object (i.e. the object itself)
  180. * B) The given id designates a far (non-local) object that lives in the same
  181. * address space as this actor: the returned object will be a **far** reference
  182. * to the object.
  183. * C) The given id designates a far object that lives on a remote machine: the
  184. * returned object will be a **far** and **remote** reference to the object.
  185. *
  186. * @param id the identifier of the object to resolve
  187. * @return a near or far reference to the object, depending on where the designated object lives
  188. */
  189. public ATObject resolve(ATObjectID id, ATTypeTag[] types, boolean isConnected) throws XObjectOffline {
  190. return receptionists_.resolveObject(id, types, isConnected);
  191. }
  192. /* -----------------------------
  193. * -- Initialisation Protocol --
  194. * ----------------------------- */
  195. /**
  196. * Initialises the root using the contents of the init file stored by
  197. * the hosting virtual machine.
  198. * @throws InterpreterException
  199. */
  200. protected void initRootObject() throws InterpreterException {
  201. ATAbstractGrammar initialisationCode = host_.getInitialisationCode();
  202. // evaluate the initialization code in the context of the global scope
  203. NATObject globalScope = Evaluator.getGlobalLexicalScope();
  204. NATContext initCtx = new NATContext(globalScope, globalScope);
  205. initialisationCode.meta_eval(initCtx);
  206. }
  207. /**
  208. * Initialises various fields in the lexical root of the actor, which are defined in the
  209. * context of every actor. Candidates are a "system" field which allows the program to
  210. * perform IO operations or a "~" field denoting the current working directory.
  211. *
  212. * @throws InterpreterException when initialisation of a field fails
  213. */
  214. protected void initSharedFields() throws InterpreterException {
  215. SharedActorField[] fields = host_.getFieldsToInitialize();
  216. NATObject globalScope = Evaluator.getGlobalLexicalScope();
  217. for (int i = 0; i < fields.length; i++) {
  218. SharedActorField field = fields[i];
  219. ATObject value = field.initialize();
  220. if (value != null) {
  221. globalScope.meta_defineField(field.getName(), value);
  222. }
  223. }
  224. }
  225. // Events to be processed by the actor event loop
  226. /**
  227. * The initial event sent by the actor mirror to its event loop to intialize itself.
  228. * @param future the synchronization point with the creating actor, needs to be fulfilled with a far ref to the behaviour.
  229. * @param parametersPkt the serialized parameters for the initialization code
  230. * @param initcodePkt the serialized initialization code (e.g. the code in 'actor: { code }')
  231. */
  232. protected void event_init(final BlockingFuture future, final Packet parametersPkt, final Packet initcodePkt) {
  233. receive(new Event("init("+this+")") {
  234. public void process(Object byMyself) {
  235. try {
  236. behaviour_ = new NATObject();
  237. // pass far ref to behaviour to creator actor who is waiting for this
  238. future.resolve(receptionists_.exportObject(behaviour_,"behaviour of "+byMyself));
  239. // !! WARNING: the following code is also duplicated in
  240. // ELDiscoveryActor's event_init. If this code is modified, don't
  241. // forget to modify that of the discovery actor as well !!
  242. // initialize lexically visible fields
  243. initSharedFields();
  244. // go on to initialize the root and all lexically visible fields
  245. initRootObject();
  246. ATObject params = parametersPkt.unpack();
  247. ATMethod initCode = initcodePkt.unpack().asMethod();
  248. if (!params.isTable()) {
  249. // actor initialized as actor: { ... } => free vars automatically added to a private lexical scope
  250. // in this case, params refers to an object that will play the role of lexical scope of the actor's behaviour
  251. params.asAmbientTalkObject().setLexicalParent(Evaluator.getGlobalLexicalScope());
  252. behaviour_.setLexicalParent(params);
  253. params = NATTable.EMPTY;
  254. }/* else {
  255. // actor initialized as actor: { |vars| ... } => vars become publicly accessible in the actor
  256. }*/
  257. // initialize the behaviour using the parameters and the code
  258. try {
  259. initCode.base_applyInScope(params.asTable(), new NATContext(behaviour_, behaviour_));
  260. } catch (InterpreterException e) {
  261. System.out.println(">>> Exception while initializing actor " + Evaluator.trunc(initCode.base_bodyExpression().toString(),20) + ":\n"+e.getMessage());
  262. e.printAmbientTalkStackTrace(System.out);
  263. Logging.Actor_LOG.error(behaviour_ + ": could not initialize actor behaviour", e);
  264. }
  265. } catch (InterpreterException e) {
  266. System.out.println(">>> Exception while creating actor: " + e.getMessage());
  267. e.printAmbientTalkStackTrace(System.out);
  268. Logging.Actor_LOG.error(behaviour_ + ": could not initialize actor behaviour", e);
  269. }
  270. }
  271. });
  272. }
  273. /**
  274. * The main entry point for any asynchronous self-sends.
  275. * Asynchronous self-sends (i.e. intra-actor sends) do not undergo any form of parameter passing,
  276. * there is no need to serialize and deserialize the message parameter in a Packet.
  277. *
  278. * When an actor receives an asynchronous message for a given receiver, it delegates control
  279. * to the message itself by means of the message's <tt>process</tt> method.
  280. *
  281. * This method should only be invoked directly this actor's event loop thread.
  282. *
  283. * @throws InterpreterException
  284. */
  285. public void acceptSelfSend(final ATObject receiver, final ATAsyncMessage msg) throws InterpreterException {
  286. // This is the only place where messages are scheduled
  287. // The receiver is always a local object, receive has
  288. // already been invoked.
  289. mirror_.base_schedule(receiver, msg);
  290. }
  291. /**
  292. * This method makes the actor perform:
  293. * <code>closure&lt;-apply(arguments)@[]</code>
  294. * This receiver actor must be the owner of the closure.
  295. */
  296. public void event_trigger(final ATObject closure, final ATTable arguments, final String type) {
  297. final ELActor owner = this;
  298. receive(new Event("trigger("+closure+")") {
  299. public void process(Object myActorMirror) {
  300. try {
  301. owner.acceptSelfSend(closure,
  302. new NATAsyncMessage(Evaluator._APPLY_,
  303. NATTable.of(arguments),
  304. NATTable.EMPTY));
  305. } catch (InterpreterException e) {
  306. Logging.Actor_LOG.error(myActorMirror + ": error triggering "+ type + " handler with args " + arguments, e);
  307. }
  308. }
  309. });
  310. }
  311. /**
  312. * The main entry point for any asynchronous messages sent to this actor
  313. * by external sources.
  314. * @param sender address of the sending actor, used to notify when the receiver has gone offline.
  315. * @param serializedMessage the asynchronous AmbientTalk base-level message to enqueue
  316. */
  317. public void event_remoteAccept(final Address sender, final Packet serializedMessage) {
  318. receive(new Event("remoteAccept("+serializedMessage+")") {
  319. public void process(Object myActorMirror) {
  320. try {
  321. // receive a pair [receiver, message]
  322. ATObject[] pair = serializedMessage.unpack().asNativeTable().elements_;
  323. ATObject receiver = pair[0];
  324. ATAsyncMessage msg = pair[1].asAsyncMessage();
  325. performAccept(receiver, msg);
  326. } catch (XObjectOffline e) {
  327. host_.event_objectTakenOffline(e.getObjectId(), sender);
  328. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  329. } catch (InterpreterException e) {
  330. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  331. }
  332. }
  333. });
  334. }
  335. /**
  336. * The main entry point for any asynchronous messages sent to this actor
  337. * by local actors.
  338. * @param ref the local reference of the sending actor, used to notify when the receiver has gone offline.
  339. * @param serializedMessage the asynchronous AmbientTalk base-level message to enqueue
  340. */
  341. public void event_localAccept(final NATLocalFarRef ref, final Packet serializedMessage) {
  342. receive(new Event("localAccept("+serializedMessage+")") {
  343. public void process(Object myActorMirror) {
  344. try {
  345. // receive a pair [receiver, message]
  346. ATObject[] pair = serializedMessage.unpack().asNativeTable().elements_;
  347. ATObject receiver = pair[0];
  348. ATAsyncMessage msg = pair[1].asAsyncMessage();
  349. performAccept(receiver, msg);
  350. } catch (XObjectOffline e) {
  351. ref.notifyTakenOffline();
  352. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  353. } catch (InterpreterException e) {
  354. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  355. }
  356. }
  357. });
  358. }
  359. public void event_serve() {
  360. receive(new Event("serve()") {
  361. public void process(Object myActorMirror) {
  362. try {
  363. ATObject result = mirror_.base_serve();
  364. Logging.Actor_LOG.debug(mirror_ + ": serve() returned " + result);
  365. } catch (InterpreterException e) {
  366. System.out.println(">>> Exception in actor " + myActorMirror + ": "+e.getMessage());
  367. e.printAmbientTalkStackTrace(System.out);
  368. Logging.Actor_LOG.error(mirror_ + ": serve() failed ", e);
  369. }
  370. }
  371. });
  372. }
  373. private void performAccept(ATObject receiver, ATAsyncMessage msg) {
  374. try {
  375. ATObject result = mirror_.base_receive(receiver, msg);
  376. Logging.Actor_LOG.debug(mirror_ + ": scheduling "+ msg + " returned " + result);
  377. // signal a serve event for every message that is accepted
  378. // event_serve();
  379. } catch (InterpreterException e) {
  380. System.out.println(">>> Exception in actor " + getImplicitActorMirror() + ": "+e.getMessage());
  381. e.printAmbientTalkStackTrace(System.out);
  382. Logging.Actor_LOG.error(mirror_ + ": scheduling "+ msg + " failed ", e);
  383. }
  384. }
  385. /**
  386. * This method is invoked by a coercer in order to schedule a purely asynchronous symbiotic invocation
  387. * from the Java world.
  388. *
  389. * This method schedules the call for asynchronous execution. Its return value and or raised exceptions
  390. * are ignored. This method should only be used for {@link Method} objects whose return type is <tt>void</tt>
  391. * and whose declaring class is a subtype of {@link EventListener}. It represents asynchronous method
  392. * invocations from the Java world to the AmbientTalk world.
  393. *
  394. * @param principal the AmbientTalk object owned by this actor on which to invoke the method
  395. * @param method the Java method that was symbiotically invoked on the principal
  396. * @param args the arguments to the Java method call, already converted into AmbientTalk values
  397. */
  398. public void event_symbioticInvocation(final ATObject principal, final Method method, final ATObject[] args) {
  399. receive(new Event("asyncSymbioticInv of "+method.getName()) {
  400. public void process(Object actorMirror) {
  401. try {
  402. Reflection.downInvocation(principal, method, args);
  403. } catch (InterpreterException e) {
  404. System.out.println(">>> Exception in actor " + actorMirror + ": "+e.getMessage());
  405. e.printAmbientTalkStackTrace(System.out);
  406. Logging.Actor_LOG.error("asynchronous symbiotic invocation of "+method.getName()+" failed", e);
  407. }
  408. }
  409. });
  410. }
  411. /**
  412. * This method is invoked by a coercer in order to schedule a symbiotic invocation
  413. * from the Java world, which should be synchronous to the Java thread, but which
  414. * must be scheduled asynchronously to comply with the AT/2 actor model.
  415. *
  416. * The future returned by this method makes the calling (Java) thread <b>block</b> upon
  417. * accessing its value, waiting until the actor has processed the symbiotic invocation.
  418. *
  419. * @param principal the AmbientTalk object owned by this actor on which to invoke the method
  420. * @param meth the Java method that was symbiotically invoked on the principal
  421. * @param args the arguments to the Java method call, already converted into AmbientTalk values
  422. * @return a Java future that is resolved with the result of the symbiotic invocation
  423. * @throws Exception if the symbiotic invocation fails
  424. */
  425. public BlockingFuture sync_event_symbioticInvocation(final ATObject principal, final Method meth, final ATObject[] args) throws Exception {
  426. return receiveAndReturnFuture("syncSymbioticInv of " + meth.getName(), new Callable() {
  427. public Object call(Object actorMirror) throws Exception {
  428. Class targetType = meth.getReturnType();
  429. ATObject[] actualArgs = args;
  430. // if the return type is BlockingFuture, the first argument should specify the type
  431. // of the value with which BlockingFuture will be resolved
  432. if (targetType.equals(BlockingFuture.class)) {
  433. if ((meth.getParameterTypes().length > 0) && (meth.getParameterTypes()[0].equals(Class.class))) {
  434. targetType = args[0].asJavaClassUnderSymbiosis().getWrappedClass();
  435. // drop first argument, it only exists to specify the targetType
  436. ATObject[] newArgs = new ATObject[args.length-1];
  437. System.arraycopy(args, 1, newArgs, 0, newArgs.length);
  438. actualArgs = newArgs;
  439. }
  440. }
  441. ATObject result = Reflection.downInvocation(principal, meth, actualArgs);
  442. // SUPPORT FOR FUTURES
  443. if (Symbiosis.isAmbientTalkFuture(result)) {
  444. Logging.Actor_LOG.debug("Symbiotic futures: symbiotic call to " + meth.getName() + " returned an AT future");
  445. return Symbiosis.ambientTalkFutureToJavaFuture(result, targetType);
  446. } else {
  447. // return the proper value immediately
  448. return Symbiosis.ambientTalkToJava(result, targetType);
  449. }
  450. }
  451. });
  452. }
  453. /**
  454. * This method is invoked by a coercer in order to schedule a symbiotic invocation
  455. * of a method from java.lang.Object from the Java world, which should be synchronous
  456. * to the Java thread, but which
  457. * must be scheduled asynchronously to comply with the AT/2 actor model.
  458. *
  459. * The future returned by this method makes the calling (Java) thread <b>block</b> upon
  460. * accessing its value, waiting until the actor has processed the symbiotic invocation.
  461. *
  462. * Note: the parameter meth must be a method declared on the class java.lang.Object
  463. * (i.e. toString, hashCode and equals). The invocation is simply forwarded directly
  464. * to the principal with no conversion to an AmbientTalk invocation.
  465. *
  466. * @param principal the AmbientTalk object owned by this actor on which to invoke the method
  467. * @param meth the Java method that was symbiotically invoked on the principal
  468. * @param args the arguments to the Java method call, already converted into AmbientTalk values
  469. * @return a Java future that is resolved with the result of the symbiotic invocation
  470. * @throws Exception if the symbiotic invocation fails
  471. */
  472. public BlockingFuture sync_event_symbioticForwardInvocation(final ATObject principal, final Method meth, final Object[] args) throws Exception {
  473. return receiveAndReturnFuture("syncSymbioticInv of " + meth.getName(), new Callable() {
  474. public Object call(Object actorMirror) throws Exception {
  475. try {
  476. return meth.invoke(principal, args);
  477. } catch (InvocationTargetException e) {
  478. if (e instanceof Exception) {
  479. throw (Exception) e.getTargetException();
  480. } else {
  481. throw e;
  482. }
  483. }
  484. }
  485. });
  486. }
  487. /**
  488. * This method should only be used for purposes such as the IAT shell or unit testing.
  489. * It allows an external thread to make this actor evaluate an arbitrary expression.
  490. *
  491. * @param ast an abstract syntax tree to be evaluated by the receiving actor (in the
  492. * scope of its behaviour).
  493. * @return the result of the evaluation
  494. * @throws InterpreterException if the evaluation fails
  495. */
  496. public ATObject sync_event_eval(final ATAbstractGrammar ast) throws InterpreterException {
  497. try {
  498. return (ATObject) receiveAndWait("nativeEval("+ast+")", new Callable() {
  499. public Object call(Object inActor) throws Exception {
  500. return OBJLexicalRoot._INSTANCE_.base_eval_in_(ast, behaviour_);
  501. }
  502. });
  503. } catch (Exception e) {
  504. if (e instanceof InterpreterException) {
  505. throw (InterpreterException) e;
  506. } else {
  507. Logging.Actor_LOG.fatal("Unexpected Java exception: "+e.getMessage(), e);
  508. throw new RuntimeException("Unexpected exception: "+e);
  509. }
  510. }
  511. }
  512. /**
  513. * This method should only be used for purposes such as the IAT shell or unit testing.
  514. * It allows an external thread to make this actor evaluate an arbitrary expression and to
  515. * print that expression (into a String).
  516. *
  517. * @param ast an abstract syntax tree to be evaluated by the receiving actor (in the
  518. * scope of its behaviour).
  519. * @return the printed result of the evaluation as a String
  520. * @throws InterpreterException if the evaluation fails
  521. */
  522. public String sync_event_evalAndPrint(final ATAbstractGrammar ast) throws InterpreterException {
  523. try {
  524. return (String) receiveAndWait("nativeEval("+ast+")", new Callable() {
  525. public Object call(Object inActor) throws Exception {
  526. return OBJLexicalRoot._INSTANCE_.base_eval_in_(ast, behaviour_).toString();
  527. }
  528. });
  529. } catch (Exception e) {
  530. if (e instanceof InterpreterException) {
  531. throw (InterpreterException) e;
  532. } else {
  533. Logging.Actor_LOG.fatal("Unexpected Java exception: "+e.getMessage(), e);
  534. throw new RuntimeException("Unexpected exception: "+e);
  535. }
  536. }
  537. }
  538. /**
  539. * This method should only be used for purposes of unit testing. It allows
  540. * arbitary code to be scheduled by external threads such as unit testing frameworks.
  541. */
  542. public Object sync_event_performTest(Callable c) throws Exception {
  543. return (ATObject) receiveAndWait("performTest("+c+")", c);
  544. }
  545. /**
  546. * When the discovery manager receives a publication from another local actor or
  547. * another remote VM, the actor is asked to compare the incoming publication against
  548. * a subscription that it had announced previously.
  549. *
  550. * @param requiredTypePkt serialized form of the type attached to the actor's subscription
  551. * @param myHandler the closure specified as a handler for the actor's subscription
  552. * @param discoveredTypePkt serialized form of the type attached to the new publication
  553. * @param remoteServicePkt serialized form of the reference to the remote discovered service
  554. */
  555. public void event_serviceJoined(final Packet requiredTypePkt, final ATFarReference myHandler,
  556. final Packet discoveredTypePkt, final Packet remoteServicePkt) {
  557. receive(new Event("serviceJoined") {
  558. public void process(Object myActorMirror) {
  559. try {
  560. ATTypeTag requiredType = requiredTypePkt.unpack().asTypeTag();
  561. ATTypeTag discoveredType = discoveredTypePkt.unpack().asTypeTag();
  562. // is there a match?
  563. if (discoveredType.base_isSubtypeOf(requiredType).asNativeBoolean().javaValue) {
  564. ATObject remoteService = remoteServicePkt.unpack();
  565. // myhandler<-apply([remoteService])@[]
  566. Evaluator.trigger(myHandler, NATTable.of(remoteService));
  567. }
  568. } catch (XIOProblem e) {
  569. Logging.Actor_LOG.error("Error deserializing joined types or services: ", e.getCause());
  570. } catch (XClassNotFound e) {
  571. Logging.Actor_LOG.fatal("Could not find class while deserializing joined types or services: ", e.getCause());
  572. } catch (InterpreterException e) {
  573. Logging.Actor_LOG.error("Error while joining services: ", e);
  574. }
  575. }
  576. });
  577. }
  578. }