Debian Codegraph @

rhino/src/org/mozilla/javascript/Kit.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.Reader;
12 import java.lang.reflect.Method;
13 import java.util.Map;
14
15 /**
16 * Collection of utilities
17 */
18
19 public class Kit
20 {
21 /**
22 * Reflection of Throwable.initCause(Throwable) from JDK 1.4
23 * or nul if it is not available.
24 */
25 private static Method Throwable_initCause = null;
26
27 static {
28 // Are we running on a JDK 1.4 or later system?
29 try {
30 Class<?> ThrowableClass = Kit.classOrNull("java.lang.Throwable");
31 Class<?>[] signature = { ThrowableClass };
32 Throwable_initCause
33 = ThrowableClass.getMethod("initCause", signature);
34 } catch (Exception ex) {
35 // Assume any exceptions means the method does not exist.
36 }
37 }
38
39 public static Class<?> classOrNull(String className)
40 {
41 try {
42 return Class.forName(className);
43 } catch (ClassNotFoundException ex) {
44 } catch (SecurityException ex) {
45 } catch (LinkageError ex) {
46 } catch (IllegalArgumentException e) {
47 // Can be thrown if name has characters that a class name
48 // can not contain
49 }
50 return null;
51 }
52
53 /**
54 * Attempt to load the class of the given name. Note that the type parameter
55 * isn't checked.
56 */
57 public static Class<?> classOrNull(ClassLoader loader, String className)
58 {
59 try {
60 return loader.loadClass(className);
61 } catch (ClassNotFoundException ex) {
62 } catch (SecurityException ex) {
63 } catch (LinkageError ex) {
64 } catch (IllegalArgumentException e) {
65 // Can be thrown if name has characters that a class name
66 // can not contain
67 }
68 return null;
69 }
70
71 static Object newInstanceOrNull(Class<?> cl)
72 {
73 try {
74 return cl.newInstance();
75 } catch (SecurityException x) {
76 } catch (LinkageError ex) {
77 } catch (InstantiationException x) {
78 } catch (IllegalAccessException x) {
79 }
80 return null;
81 }
82
83 /**
84 * Check that testClass is accessible from the given loader.
85 */
86 static boolean testIfCanLoadRhinoClasses(ClassLoader loader)
87 {
88 Class<?> testClass = ScriptRuntime.ContextFactoryClass;
89 Class<?> x = Kit.classOrNull(loader, testClass.getName());
90 if (x != testClass) {
91 // The check covers the case when x == null =>
92 // loader does not know about testClass or the case
93 // when x != null && x != testClass =>
94 // loader loads a class unrelated to testClass
95 return false;
96 }
97 return true;
98 }
99
100 /**
101 * If initCause methods exists in Throwable, call
102 * <tt>ex.initCause(cause)</tt> or otherwise do nothing.
103 * @return The <tt>ex</tt> argument.
104 */
105 public static RuntimeException initCause(RuntimeException ex,
106 Throwable cause)
107 {
108 if (Throwable_initCause != null) {
109 Object[] args = { cause };
110 try {
111 Throwable_initCause.invoke(ex, args);
112 } catch (Exception e) {
113 // Ignore any exceptions
114 }
115 }
116 return ex;
117 }
118
119 /**
120 * If character <tt>c</tt> is a hexadecimal digit, return
121 * <tt>accumulator</tt> * 16 plus corresponding
122 * number. Otherise return -1.
123 */
124 public static int xDigitToInt(int c, int accumulator)
125 {
126 check: {
127 // Use 0..9 < A..Z < a..z
128 if (c <= '9') {
129 c -= '0';
130 if (0 <= c) { break check; }
131 } else if (c <= 'F') {
132 if ('A' <= c) {
133 c -= ('A' - 10);
134 break check;
135 }
136 } else if (c <= 'f') {
137 if ('a' <= c) {
138 c -= ('a' - 10);
139 break check;
140 }
141 }
142 return -1;
143 }
144 return (accumulator << 4) | c;
145 }
146
147 /**
148 * Add <i>listener</i> to <i>bag</i> of listeners.
149 * The function does not modify <i>bag</i> and return a new collection
150 * containing <i>listener</i> and all listeners from <i>bag</i>.
151 * Bag without listeners always represented as the null value.
152 * <p>
153 * Usage example:
154 * <pre>
155 * private volatile Object changeListeners;
156 *
157 * public void addMyListener(PropertyChangeListener l)
158 * {
159 * synchronized (this) {
160 * changeListeners = Kit.addListener(changeListeners, l);
161 * }
162 * }
163 *
164 * public void removeTextListener(PropertyChangeListener l)
165 * {
166 * synchronized (this) {
167 * changeListeners = Kit.removeListener(changeListeners, l);
168 * }
169 * }
170 *
171 * public void fireChangeEvent(Object oldValue, Object newValue)
172 * {
173 * // Get immune local copy
174 * Object listeners = changeListeners;
175 * if (listeners != null) {
176 * PropertyChangeEvent e = new PropertyChangeEvent(
177 * this, "someProperty" oldValue, newValue);
178 * for (int i = 0; ; ++i) {
179 * Object l = Kit.getListener(listeners, i);
180 * if (l == null)
181 * break;
182 * ((PropertyChangeListener)l).propertyChange(e);
183 * }
184 * }
185 * }
186 * </pre>
187 *
188 * @param listener Listener to add to <i>bag</i>
189 * @param bag Current collection of listeners.
190 * @return A new bag containing all listeners from <i>bag</i> and
191 * <i>listener</i>.
192 * @see #removeListener(Object bag, Object listener)
193 * @see #getListener(Object bag, int index)
194 */
195 public static Object addListener(Object bag, Object listener)
196 {
197 if (listener == null) throw new IllegalArgumentException();
198 if (listener instanceof Object[]) throw new IllegalArgumentException();
199
200 if (bag == null) {
201 bag = listener;
202 } else if (!(bag instanceof Object[])) {
203 bag = new Object[] { bag, listener };
204 } else {
205 Object[] array = (Object[])bag;
206 int L = array.length;
207 // bag has at least 2 elements if it is array
208 if (L < 2) throw new IllegalArgumentException();
209 Object[] tmp = new Object[L + 1];
210 System.arraycopy(array, 0, tmp, 0, L);
211 tmp[L] = listener;
212 bag = tmp;
213 }
214
215 return bag;
216 }
217
218 /**
219 * Remove <i>listener</i> from <i>bag</i> of listeners.
220 * The function does not modify <i>bag</i> and return a new collection
221 * containing all listeners from <i>bag</i> except <i>listener</i>.
222 * If <i>bag</i> does not contain <i>listener</i>, the function returns
223 * <i>bag</i>.
224 * <p>
225 * For usage example, see {@link #addListener(Object bag, Object listener)}.
226 *
227 * @param listener Listener to remove from <i>bag</i>
228 * @param bag Current collection of listeners.
229 * @return A new bag containing all listeners from <i>bag</i> except
230 * <i>listener</i>.
231 * @see #addListener(Object bag, Object listener)
232 * @see #getListener(Object bag, int index)
233 */
234 public static Object removeListener(Object bag, Object listener)
235 {
236 if (listener == null) throw new IllegalArgumentException();
237 if (listener instanceof Object[]) throw new IllegalArgumentException();
238
239 if (bag == listener) {
240 bag = null;
241 } else if (bag instanceof Object[]) {
242 Object[] array = (Object[])bag;
243 int L = array.length;
244 // bag has at least 2 elements if it is array
245 if (L < 2) throw new IllegalArgumentException();
246 if (L == 2) {
247 if (array[1] == listener) {
248 bag = array[0];
249 } else if (array[0] == listener) {
250 bag = array[1];
251 }
252 } else {
253 int i = L;
254 do {
255 --i;
256 if (array[i] == listener) {
257 Object[] tmp = new Object[L - 1];
258 System.arraycopy(array, 0, tmp, 0, i);
259 System.arraycopy(array, i + 1, tmp, i, L - (i + 1));
260 bag = tmp;
261 break;
262 }
263 } while (i != 0);
264 }
265 }
266
267 return bag;
268 }
269
270 /**
271 * Get listener at <i>index</i> position in <i>bag</i> or null if
272 * <i>index</i> equals to number of listeners in <i>bag</i>.
273 * <p>
274 * For usage example, see {@link #addListener(Object bag, Object listener)}.
275 *
276 * @param bag Current collection of listeners.
277 * @param index Index of the listener to access.
278 * @return Listener at the given index or null.
279 * @see #addListener(Object bag, Object listener)
280 * @see #removeListener(Object bag, Object listener)
281 */
282 public static Object getListener(Object bag, int index)
283 {
284 if (index == 0) {
285 if (bag == null)
286 return null;
287 if (!(bag instanceof Object[]))
288 return bag;
289 Object[] array = (Object[])bag;
290 // bag has at least 2 elements if it is array
291 if (array.length < 2) throw new IllegalArgumentException();
292 return array[0];
293 } else if (index == 1) {
294 if (!(bag instanceof Object[])) {
295 if (bag == null) throw new IllegalArgumentException();
296 return null;
297 }
298 Object[] array = (Object[])bag;
299 // the array access will check for index on its own
300 return array[1];
301 } else {
302 // bag has to array
303 Object[] array = (Object[])bag;
304 int L = array.length;
305 if (L < 2) throw new IllegalArgumentException();
306 if (index == L)
307 return null;
308 return array[index];
309 }
310 }
311
312 static Object initHash(Map<Object,Object> h, Object key, Object initialValue)
313 {
314 synchronized (h) {
315 Object current = h.get(key);
316 if (current == null) {
317 h.put(key, initialValue);
318 } else {
319 initialValue = current;
320 }
321 }
322 return initialValue;
323 }
324
325 private final static class ComplexKey
326 {
327 private Object key1;
328 private Object key2;
329 private int hash;
330
331 ComplexKey(Object key1, Object key2)
332 {
333 this.key1 = key1;
334 this.key2 = key2;
335 }
336
337 @Override
338 public boolean equals(Object anotherObj)
339 {
340 if (!(anotherObj instanceof ComplexKey))
341 return false;
342 ComplexKey another = (ComplexKey)anotherObj;
343 return key1.equals(another.key1) && key2.equals(another.key2);
344 }
345
346 @Override
347 public int hashCode()
348 {
349 if (hash == 0) {
350 hash = key1.hashCode() ^ key2.hashCode();
351 }
352 return hash;
353 }
354 }
355
356 public static Object makeHashKeyFromPair(Object key1, Object key2)
357 {
358 if (key1 == null) throw new IllegalArgumentException();
359 if (key2 == null) throw new IllegalArgumentException();
360 return new ComplexKey(key1, key2);
361 }
362
363 public static String readReader(Reader r)
364 throws IOException
365 {
366 char[] buffer = new char[512];
367 int cursor = 0;
368 for (;;) {
369 int n = r.read(buffer, cursor, buffer.length - cursor);
370 if (n < 0) { break; }
371 cursor += n;
372 if (cursor == buffer.length) {
373 char[] tmp = new char[buffer.length * 2];
374 System.arraycopy(buffer, 0, tmp, 0, cursor);
375 buffer = tmp;
376 }
377 }
378 return new String(buffer, 0, cursor);
379 }
380
381 public static byte[] readStream(InputStream is, int initialBufferCapacity)
382 throws IOException
383 {
384 if (initialBufferCapacity <= 0) {
385 throw new IllegalArgumentException(
386 "Bad initialBufferCapacity: "+initialBufferCapacity);
387 }
388 byte[] buffer = new byte[initialBufferCapacity];
389 int cursor = 0;
390 for (;;) {
391 int n = is.read(buffer, cursor, buffer.length - cursor);
392 if (n < 0) { break; }
393 cursor += n;
394 if (cursor == buffer.length) {
395 byte[] tmp = new byte[buffer.length * 2];
396 System.arraycopy(buffer, 0, tmp, 0, cursor);
397 buffer = tmp;
398 }
399 }
400 if (cursor != buffer.length) {
401 byte[] tmp = new byte[cursor];
402 System.arraycopy(buffer, 0, tmp, 0, cursor);
403 buffer = tmp;
404 }
405 return buffer;
406 }
407
408 /**
409 * Throws RuntimeException to indicate failed assertion.
410 * The function never returns and its return type is RuntimeException
411 * only to be able to write <tt>throw Kit.codeBug()</tt> if plain
412 * <tt>Kit.codeBug()</tt> triggers unreachable code error.
413 */
414 public static RuntimeException codeBug()
415 throws RuntimeException
416 {
417 RuntimeException ex = new IllegalStateException("FAILED ASSERTION");
418 // Print stack trace ASAP
419 ex.printStackTrace(System.err);
420 throw ex;
421 }
422
423 /**
424 * Throws RuntimeException to indicate failed assertion.
425 * The function never returns and its return type is RuntimeException
426 * only to be able to write <tt>throw Kit.codeBug()</tt> if plain
427 * <tt>Kit.codeBug()</tt> triggers unreachable code error.
428 */
429 public static RuntimeException codeBug(String msg)
430 throws RuntimeException
431 {
432 msg = "FAILED ASSERTION: " + msg;
433 RuntimeException ex = new IllegalStateException(msg);
434 // Print stack trace ASAP
435 ex.printStackTrace(System.err);
436 throw ex;
437 }
438 }