001: /*
002: * Copyright 2002-2007 the original author or authors.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.springframework.scripting.jruby;
018:
019: import java.lang.reflect.Array;
020: import java.lang.reflect.InvocationHandler;
021: import java.lang.reflect.Method;
022: import java.lang.reflect.Proxy;
023: import java.util.Collections;
024: import java.util.List;
025:
026: import org.jruby.Ruby;
027: import org.jruby.RubyArray;
028: import org.jruby.RubyException;
029: import org.jruby.RubyNil;
030: import org.jruby.ast.ClassNode;
031: import org.jruby.ast.Colon2Node;
032: import org.jruby.ast.NewlineNode;
033: import org.jruby.ast.Node;
034: import org.jruby.exceptions.JumpException;
035: import org.jruby.exceptions.RaiseException;
036: import org.jruby.javasupport.JavaEmbedUtils;
037: import org.jruby.runtime.DynamicScope;
038: import org.jruby.runtime.builtin.IRubyObject;
039:
040: import org.springframework.aop.support.AopUtils;
041: import org.springframework.core.NestedRuntimeException;
042: import org.springframework.util.ClassUtils;
043: import org.springframework.util.ObjectUtils;
044: import org.springframework.util.ReflectionUtils;
045: import org.springframework.util.StringUtils;
046:
047: /**
048: * Utility methods for handling JRuby-scripted objects.
049: *
050: * <p>Note: As of Spring 2.0.4, this class requires JRuby 0.9.8 or 0.9.9.
051: * As of Spring 2.0.6 / 2.1, it supports JRuby 1.0 as well.
052: *
053: * @author Rob Harrop
054: * @author Juergen Hoeller
055: * @author Rick Evans
056: * @since 2.0
057: */
058: public abstract class JRubyScriptUtils {
059:
060: // Determine whether the old JRuby 0.9 parse method is available (incompatible with 1.0)
061: private final static Method oldParseMethod = ClassUtils
062: .getMethodIfAvailable(Ruby.class, "parse", new Class[] {
063: String.class, String.class, DynamicScope.class });
064:
065: /**
066: * Create a new JRuby-scripted object from the given script source,
067: * using the default {@link ClassLoader}.
068: * @param scriptSource the script source text
069: * @param interfaces the interfaces that the scripted Java object is to implement
070: * @return the scripted Java object
071: * @throws JumpException in case of JRuby parsing failure
072: * @see ClassUtils#getDefaultClassLoader()
073: */
074: public static Object createJRubyObject(String scriptSource,
075: Class[] interfaces) throws JumpException {
076: return createJRubyObject(scriptSource, interfaces, ClassUtils
077: .getDefaultClassLoader());
078: }
079:
080: /**
081: * Create a new JRuby-scripted object from the given script source.
082: * @param scriptSource the script source text
083: * @param interfaces the interfaces that the scripted Java object is to implement
084: * @param classLoader the {@link ClassLoader} to create the script proxy with
085: * @return the scripted Java object
086: * @throws JumpException in case of JRuby parsing failure
087: */
088: public static Object createJRubyObject(String scriptSource,
089: Class[] interfaces, ClassLoader classLoader) {
090: Ruby ruby = initializeRuntime();
091:
092: Node scriptRootNode = (oldParseMethod != null ? (Node) ReflectionUtils
093: .invokeMethod(oldParseMethod, ruby, new Object[] {
094: scriptSource, "", null })
095: : ruby.parse(scriptSource, "", null, 0));
096: IRubyObject rubyObject = ruby.eval(scriptRootNode);
097:
098: if (rubyObject instanceof RubyNil) {
099: String className = findClassName(scriptRootNode);
100: rubyObject = ruby.evalScript("\n" + className + ".new");
101: }
102: // still null?
103: if (rubyObject instanceof RubyNil) {
104: throw new IllegalStateException(
105: "Compilation of JRuby script returned RubyNil: "
106: + rubyObject);
107: }
108:
109: return Proxy.newProxyInstance(classLoader, interfaces,
110: new RubyObjectInvocationHandler(rubyObject, ruby));
111: }
112:
113: /**
114: * Initializes an instance of the {@link org.jruby.Ruby} runtime.
115: */
116: private static Ruby initializeRuntime() {
117: return JavaEmbedUtils.initialize(Collections.EMPTY_LIST);
118: }
119:
120: /**
121: * Given the root {@link Node} in a JRuby AST will locate the name of the
122: * class defined by that AST.
123: * @throws IllegalArgumentException if no class is defined by the supplied AST
124: */
125: private static String findClassName(Node rootNode) {
126: ClassNode classNode = findClassNode(rootNode);
127: if (classNode == null) {
128: throw new IllegalArgumentException(
129: "Unable to determine class name for root node '"
130: + rootNode + "'");
131: }
132: Colon2Node node = (Colon2Node) classNode.getCPath();
133: return node.getName();
134: }
135:
136: /**
137: * Find the first {@link ClassNode} under the supplied {@link Node}.
138: * @return the found <code>ClassNode</code>, or <code>null</code>
139: * if no {@link ClassNode} is found
140: */
141: private static ClassNode findClassNode(Node node) {
142: if (node instanceof ClassNode) {
143: return (ClassNode) node;
144: }
145: List children = node.childNodes();
146: for (int i = 0; i < children.size(); i++) {
147: Node child = (Node) children.get(i);
148: if (child instanceof ClassNode) {
149: return (ClassNode) child;
150: } else if (child instanceof NewlineNode) {
151: NewlineNode nn = (NewlineNode) child;
152: Node found = findClassNode(nn.getNextNode());
153: if (found instanceof ClassNode) {
154: return (ClassNode) found;
155: }
156: }
157: }
158: for (int i = 0; i < children.size(); i++) {
159: Node child = (Node) children.get(i);
160: Node found = findClassNode(child);
161: if (found instanceof ClassNode) {
162: return (ClassNode) found;
163: }
164: }
165: return null;
166: }
167:
168: /**
169: * InvocationHandler that invokes a JRuby script method.
170: */
171: private static class RubyObjectInvocationHandler implements
172: InvocationHandler {
173:
174: private final IRubyObject rubyObject;
175:
176: private final Ruby ruby;
177:
178: public RubyObjectInvocationHandler(IRubyObject rubyObject,
179: Ruby ruby) {
180: this .rubyObject = rubyObject;
181: this .ruby = ruby;
182: }
183:
184: public Object invoke(Object proxy, Method method, Object[] args)
185: throws Throwable {
186: if (AopUtils.isEqualsMethod(method)) {
187: return (isProxyForSameRubyObject(args[0]) ? Boolean.TRUE
188: : Boolean.FALSE);
189: }
190: if (AopUtils.isHashCodeMethod(method)) {
191: return new Integer(this .rubyObject.hashCode());
192: }
193: if (AopUtils.isToStringMethod(method)) {
194: String toStringResult = this .rubyObject.toString();
195: if (!StringUtils.hasText(toStringResult)) {
196: toStringResult = ObjectUtils
197: .identityToString(this .rubyObject);
198: }
199: return "JRuby object [" + toStringResult + "]";
200: }
201: try {
202: IRubyObject[] rubyArgs = convertToRuby(args);
203: IRubyObject rubyResult = this .rubyObject.callMethod(
204: this .ruby.getCurrentContext(),
205: method.getName(), rubyArgs);
206: return convertFromRuby(rubyResult, method
207: .getReturnType());
208: } catch (RaiseException ex) {
209: throw new JRubyExecutionException(ex);
210: }
211: }
212:
213: private boolean isProxyForSameRubyObject(Object other) {
214: if (!Proxy.isProxyClass(other.getClass())) {
215: return false;
216: }
217: InvocationHandler ih = Proxy.getInvocationHandler(other);
218: return (ih instanceof RubyObjectInvocationHandler && this .rubyObject
219: .equals(((RubyObjectInvocationHandler) ih).rubyObject));
220: }
221:
222: private IRubyObject[] convertToRuby(Object[] javaArgs) {
223: if (javaArgs == null || javaArgs.length == 0) {
224: return new IRubyObject[0];
225: }
226: IRubyObject[] rubyArgs = new IRubyObject[javaArgs.length];
227: for (int i = 0; i < javaArgs.length; ++i) {
228: rubyArgs[i] = JavaEmbedUtils.javaToRuby(this .ruby,
229: javaArgs[i]);
230: }
231: return rubyArgs;
232: }
233:
234: private Object convertFromRuby(IRubyObject rubyResult,
235: Class returnType) {
236: Object result = JavaEmbedUtils.rubyToJava(this .ruby,
237: rubyResult, returnType);
238: if (result instanceof RubyArray && returnType.isArray()) {
239: result = convertFromRubyArray(((RubyArray) result)
240: .toJavaArray(), returnType);
241: }
242: return result;
243: }
244:
245: private Object convertFromRubyArray(IRubyObject[] rubyArray,
246: Class returnType) {
247: Class targetType = returnType.getComponentType();
248: Object javaArray = Array.newInstance(targetType,
249: rubyArray.length);
250: for (int i = 0; i < rubyArray.length; i++) {
251: IRubyObject rubyObject = rubyArray[i];
252: Array.set(javaArray, i, convertFromRuby(rubyObject,
253: targetType));
254: }
255: return javaArray;
256: }
257: }
258:
259: /**
260: * Exception thrown in response to a JRuby {@link RaiseException}
261: * being thrown from a JRuby method invocation.
262: * <p>Introduced because the <code>RaiseException</code> class does not
263: * have useful {@link Object#toString()}, {@link Throwable#getMessage()},
264: * and {@link Throwable#printStackTrace} implementations.
265: */
266: public static class JRubyExecutionException extends
267: NestedRuntimeException {
268:
269: /**
270: * Create a new <code>JRubyException</code>,
271: * wrapping the given JRuby <code>RaiseException</code>.
272: * @param ex the cause (must not be <code>null</code>)
273: */
274: public JRubyExecutionException(RaiseException ex) {
275: super (buildMessage(ex), ex);
276: }
277:
278: private static String buildMessage(RaiseException ex) {
279: RubyException rubyEx = ex.getException();
280: return (rubyEx != null && rubyEx.message != null) ? rubyEx.message
281: .toString()
282: : "Unexpected JRuby error";
283: }
284: }
285:
286: }
|