KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jruby > test > TestHelper


1 /***** BEGIN LICENSE BLOCK *****
2  * Version: CPL 1.0/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Common Public
5  * License Version 1.0 (the "License"); you may not use this file
6  * except in compliance with the License. You may obtain a copy of
7  * the License at http://www.eclipse.org/legal/cpl-v10.html
8  *
9  * Software distributed under the License is distributed on an "AS
10  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
11  * implied. See the License for the specific language governing
12  * rights and limitations under the License.
13  *
14  * Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
15  * Copyright (C) 2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
16  * Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
17  * Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
18  * Copyright (C) 2004 David Corbin <dcorbin@users.sourceforge.net>
19  *
20  * Alternatively, the contents of this file may be used under the terms of
21  * either of the GNU General Public License Version 2 or later (the "GPL"),
22  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
23  * in which case the provisions of the GPL or the LGPL are applicable instead
24  * of those above. If you wish to allow use of your version of this file only
25  * under the terms of either the GPL or the LGPL, and not to allow others to
26  * use your version of this file under the terms of the CPL, indicate your
27  * decision by deleting the provisions above and replace them with the notice
28  * and other provisions required by the GPL or the LGPL. If you do not delete
29  * the provisions above, a recipient may use your version of this file under
30  * the terms of any one of the CPL, the GPL or the LGPL.
31  ***** END LICENSE BLOCK *****/

32 package org.jruby.test;
33
34 import java.io.ByteArrayOutputStream JavaDoc;
35 import java.io.IOException JavaDoc;
36 import java.io.InputStream JavaDoc;
37 import java.lang.reflect.InvocationTargetException JavaDoc;
38 import java.lang.reflect.Method JavaDoc;
39
40 import org.jruby.Ruby;
41 import org.jruby.runtime.ThreadContext;
42 import org.jruby.runtime.builtin.IRubyObject;
43
44 /**
45  * Helper class, used for testing calls to java from ruby code.
46  **/

47 public class TestHelper {
48     private String JavaDoc privateField = "pfValue";
49     public String JavaDoc localVariable1;
50
51     // Function not used...but it gets rid of unused warnings in Eclipse (we do call those methods
52
// from Ruby so they are not really unused).
53
public static void removeWarningsFromEclipse() {
54         TestHelper helper = new TestHelper("A");
55         helper.privateMethod();
56         TestHelper.staticPrivateMethod();
57     }
58
59     private TestHelper(String JavaDoc x) {
60         privateField = x;
61     }
62
63     public TestHelper() {
64     }
65
66     private String JavaDoc privateMethod() {
67         return privateField;
68     }
69
70     private static String JavaDoc staticPrivateMethod() {
71         return "staticPM";
72     }
73
74     public String JavaDoc identityTest() {
75         return "Original";
76     }
77
78     /**
79      * used to test Java Arrays in Ruby.
80      * while we don't yet have a way to create them this can be used to test basic
81      * array functionalities
82      */

83     public static String JavaDoc[] createArray(int i) {
84         return new String JavaDoc[i];
85     }
86
87     /**
88      * used to test native exception handling.
89      **/

90     public static void throwException() {
91         throw new RuntimeException JavaDoc("testException");
92     }
93
94     /**
95      * @return object used to test casting
96      */

97     public static SomeInterface getInterfacedInstance() {
98         return new SomeImplementation();
99     }
100
101     public static Object JavaDoc getLooslyCastedInstance() {
102         return new SomeImplementation();
103     }
104
105     public static Object JavaDoc getNull() {
106         return null;
107     }
108
109     public static interface SomeInterface {
110         String JavaDoc doStuff();
111         String JavaDoc dispatchObject(Object JavaDoc iObject);
112     }
113
114     private static class SomeImplementation implements SomeInterface {
115         public String JavaDoc doStuff() {
116             return "stuff done";
117         }
118         
119         public String JavaDoc dispatchObject(Object JavaDoc iObject) {
120             return iObject == null ? null : iObject.toString();
121         }
122     }
123
124
125     public static Class JavaDoc loadAlternateClass() throws ClassNotFoundException JavaDoc {
126         AlternateLoader loader = new AlternateLoader();
127         Class JavaDoc klass = loader.loadClass("org.jruby.test.TestHelper");
128         return klass;
129     }
130
131     /**
132      * Used by JVM bytecode compiler tests to run compiled code
133      */

134     public static IRubyObject loadAndCall(IRubyObject self, String JavaDoc name, byte[] javaClass, String JavaDoc methodName)
135             throws Throwable JavaDoc {
136         Loader loader = new Loader();
137         Class JavaDoc c = loader.loadClass(name, javaClass);
138         Method JavaDoc method = c.getMethod(methodName, new Class JavaDoc[] { Ruby.class, IRubyObject.class });
139         Ruby runtime = self.getRuntime();
140         ThreadContext tc = runtime.getCurrentContext();
141         
142         tc.pushRubyClass(self.getType());
143
144         try {
145             return (IRubyObject) method.invoke(null, new Object JavaDoc[] { runtime, self });
146         } catch (InvocationTargetException JavaDoc e) {
147             throw unrollException(e);
148         } finally {
149             tc.popRubyClass();
150         }
151     }
152
153     private static Throwable JavaDoc unrollException(InvocationTargetException JavaDoc e) {
154         while (e.getCause() instanceof InvocationTargetException JavaDoc) {
155             e = (InvocationTargetException JavaDoc) e.getCause();
156         }
157         return e.getCause();
158     }
159
160     public static String JavaDoc getClassName(Class JavaDoc klass) {
161         return klass.getName();
162     }
163
164     public static void throwTestHelperException() {
165         throw new TestHelperException();
166     }
167
168     private static class Loader extends ClassLoader JavaDoc {
169
170         public Class JavaDoc loadClass(String JavaDoc name, byte[] javaClass) {
171             Class JavaDoc cl = defineClass(name,
172                                    javaClass,
173                                    0,
174                                    javaClass.length);
175             resolveClass(cl);
176             return cl;
177         }
178
179     }
180     private static class AlternateLoader extends ClassLoader JavaDoc {
181
182         protected Class JavaDoc findModClass(String JavaDoc name) throws ClassNotFoundException JavaDoc {
183            byte[] classBytes = loadClassBytes(name);
184            replace(classBytes, "Original", "ABCDEFGH");
185            return defineClass(name, classBytes, 0, classBytes.length);
186         }
187         private void replace(byte[] classBytes, String JavaDoc find, String JavaDoc replaceWith) {
188             byte[] findBytes = find.getBytes();
189             byte[] replaceBytes = replaceWith.getBytes();
190             for (int i=0; i<classBytes.length; i++) {
191                 boolean match = true;
192                 for (int j=0; j<findBytes.length; j++) {
193                     if (classBytes[i+j] != findBytes[j]) {
194                         match = false;
195                         break;
196                     }
197                 }
198                 if (match) {
199                     for (int j=0; j<findBytes.length; j++)
200                         classBytes[i+j] = replaceBytes[j];
201                     return;
202                 }
203             }
204         }
205         public Class JavaDoc loadClass(String JavaDoc name) throws ClassNotFoundException JavaDoc {
206             if (name.equals("org.jruby.test.TestHelper"))
207                 return findModClass(name);
208             return super.loadClass(name);
209         }
210         private byte[] loadClassBytes(String JavaDoc name) throws ClassNotFoundException JavaDoc {
211             InputStream JavaDoc stream = null;
212             try {
213                 String JavaDoc fileName = name.replaceAll("\\.", "/");
214                 fileName += ".class";
215                 byte[] buf = new byte[1024];
216                 ByteArrayOutputStream JavaDoc bytes = new ByteArrayOutputStream JavaDoc();
217                 int bytesRead = 0;
218                 stream = getClass().getResourceAsStream("/" + fileName);
219                 while ((bytesRead = stream.read(buf)) != -1) {
220                     bytes.write(buf, 0, bytesRead);
221                 }
222                 return bytes.toByteArray();
223             } catch (Exception JavaDoc e) {
224                 e.printStackTrace();
225                 throw new ClassNotFoundException JavaDoc(e.getMessage(),e);
226             } finally {
227                 if (stream != null)
228                     try {
229                         stream.close();
230                     } catch (IOException JavaDoc e1) {
231                         e1.printStackTrace();
232                     }
233             }
234         }
235     }
236
237     private static class TestHelperException extends RuntimeException JavaDoc {
238         private static final long serialVersionUID = 3649034127816624007L;
239     }
240 }
241
Popular Tags