/interpreter/tags/at2-build060407/src/edu/vub/at/objects/coercion/Coercer.java

http://ambienttalk.googlecode.com/ · Java · 152 lines · 75 code · 14 blank · 63 comment · 25 complexity · 50e1324d1ca8f7708614f14808b91ef8 MD5 · raw file

  1. /**
  2. * AmbientTalk/2 Project
  3. * Coercer.java created on 3-okt-2006 at 16:12:05
  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.objects.coercion;
  29. import edu.vub.at.actors.eventloops.Callable;
  30. import edu.vub.at.actors.eventloops.EventLoop;
  31. import edu.vub.at.actors.eventloops.EventLoop.EventProcessor;
  32. import edu.vub.at.actors.natives.ELActor;
  33. import edu.vub.at.exceptions.XIllegalOperation;
  34. import edu.vub.at.exceptions.XTypeMismatch;
  35. import edu.vub.at.objects.ATObject;
  36. import edu.vub.at.objects.mirrors.Reflection;
  37. import edu.vub.at.objects.natives.NATObject;
  38. import edu.vub.at.objects.symbiosis.Symbiosis;
  39. import edu.vub.at.objects.symbiosis.SymbioticATObjectMarker;
  40. import java.lang.reflect.InvocationHandler;
  41. import java.lang.reflect.InvocationTargetException;
  42. import java.lang.reflect.Method;
  43. import java.lang.reflect.Proxy;
  44. /**
  45. * A coercer is a dynamic proxy which is used to 'cast' Ambienttalk base-level NATObjects to a certain ATxxx interface.
  46. * The dynamic proxy is responsible for transforming java calls to meta_invoke calls.
  47. *
  48. * For example, a method from an AT interface
  49. *
  50. * ATExpression base_getExpression() throws NATException
  51. *
  52. * receives the following implementation:
  53. *
  54. * ATExpression getExpression() throws NATException {
  55. * return principal.meta_invoke(principal, Reflection.downSelector("getExpression"), NATTable.EMPTY).asExpression();
  56. * }
  57. *
  58. * where principal is the original object 'coerced into' the given interface
  59. *
  60. * @author tvcutsem
  61. */
  62. public final class Coercer implements InvocationHandler {
  63. private final NATObject principal_;
  64. // we have to remember which thread owned the principal
  65. private final Thread wrappingThread_;
  66. private Coercer(NATObject principal) {
  67. principal_ = principal;
  68. wrappingThread_ = Thread.currentThread();
  69. }
  70. public String toString() {
  71. return "<coercer on: "+principal_+">";
  72. }
  73. public static final Object coerce(ATObject object, Class type) throws XTypeMismatch {
  74. if (type.isInstance(object)) { // object instanceof type
  75. return object; // no need to coerce
  76. } else if (object.isAmbientTalkObject() && type.isInterface()) {
  77. // note that the proxy implements both the required type
  78. // and the Symbiotic object marker interface to identify it as a wrapper
  79. return Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),
  80. new Class[] { type, SymbioticATObjectMarker.class },
  81. new Coercer(object.asAmbientTalkObject()));
  82. } else {
  83. throw new XTypeMismatch(type, object);
  84. }
  85. }
  86. public Object invoke(Object receiver, final Method method, Object[] arguments) throws Throwable {
  87. Class methodImplementor = method.getDeclaringClass();
  88. // handle toString, hashCode and equals in a dedicated fashion
  89. // similarly, handle AT conversion methods by simply forwarding them to the native AT object
  90. if (methodImplementor == Object.class || methodImplementor == ATConversions.class) {
  91. // invoke these methods on the principal rather than on the proxy
  92. try {
  93. return method.invoke(principal_, arguments);
  94. } catch (InvocationTargetException e) {
  95. throw e.getTargetException();
  96. }
  97. // intercept access to the wrapped object for Java->AT value conversion
  98. // or for serialization purposes
  99. } else if (method.getDeclaringClass() == SymbioticATObjectMarker.class) {
  100. return principal_;
  101. } else {
  102. final ATObject[] symbioticArgs;
  103. // support for variable-arity invocations from within AmbientTalk
  104. if ((arguments != null) && (arguments.length == 1) && (arguments[0] instanceof ATObject[])) {
  105. // no need to convert arguments
  106. symbioticArgs = (ATObject[]) arguments[0];
  107. } else {
  108. symbioticArgs = new ATObject[(arguments == null) ? 0 : arguments.length];
  109. for (int i = 0; i < symbioticArgs.length; i++) {
  110. symbioticArgs[i] = Symbiosis.javaToAmbientTalk(arguments[i]);
  111. }
  112. }
  113. // if the current thread is not an actor thread, treat the Java invocation
  114. // as a message send instead and enqueue it in my actor's thread
  115. if (Thread.currentThread() != wrappingThread_) {
  116. if (Thread.currentThread() instanceof EventProcessor) {
  117. // another event loop has direct access to this object, this means
  118. // an AT object has been shared between actors via Java, signal an error
  119. throw new XIllegalOperation("Detected illegal invocation: sharing via Java level of object " + principal_);
  120. }
  121. // because a message send is asynchronous and Java threads work synchronously,
  122. // we'll have to make the Java thread wait for the result
  123. ELActor owningActor = (ELActor) EventLoop.toEventLoop(wrappingThread_);
  124. return owningActor.sync_event_symbioticInvocation(new Callable() {
  125. public Object call(Object actorMirror) throws Exception {
  126. ATObject result = Reflection.downInvocation(principal_, method, symbioticArgs);
  127. return Symbiosis.ambientTalkToJava(result, method.getReturnType());
  128. }
  129. });
  130. } else {
  131. // perform a synchronous invocation
  132. ATObject result = Reflection.downInvocation(principal_, method, symbioticArgs);
  133. // properly 'cast' the returned object into the appropriate interface
  134. return Symbiosis.ambientTalkToJava(result, method.getReturnType());
  135. }
  136. }
  137. }
  138. }