File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\util\Utils.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.util;
8
9 import java.io.ByteArrayInputStream;
10 import java.io.ByteArrayOutputStream;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.ObjectInputStream;
14 import java.io.ObjectOutputStream;
15 import java.io.ObjectStreamClass;
16 import java.lang.reflect.Constructor;
17 import java.lang.reflect.Method;
18 import java.lang.reflect.Modifier;
19 import java.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.zip.ZipEntry;
23 import java.util.zip.ZipInputStream;
24 import org.h2.api.JavaObjectSerializer;
25 import org.h2.constant.ErrorCode;
26 import org.h2.constant.SysProperties;
27 import org.h2.message.DbException;
28
29 /**
30 * This utility class contains miscellaneous functions.
31 */
32 public class Utils {
33
34 /**
35 * The serializer to use.
36 */
37 public static JavaObjectSerializer serializer;
38
39 /**
40 * An 0-size byte array.
41 */
42 public static final byte[] EMPTY_BYTES = {};
43
44 /**
45 * An 0-size int array.
46 */
47 public static final int[] EMPTY_INT_ARRAY = {};
48
49 /**
50 * An 0-size long array.
51 */
52 private static final long[] EMPTY_LONG_ARRAY = {};
53
54 private static final int GC_DELAY = 50;
55 private static final int MAX_GC = 8;
56 private static long lastGC;
57
58 private static final HashMap<String, byte[]> RESOURCES = New.hashMap();
59
60 private static boolean allowAllClasses;
61 private static HashSet<String> allowedClassNames;
62 private static String[] allowedClassNamePrefixes;
63
64 static {
65 String clazz = SysProperties.JAVA_OBJECT_SERIALIZER;
66 if (clazz != null) {
67 try {
68 serializer = (JavaObjectSerializer) loadUserClass(clazz).newInstance();
69 } catch (Exception e) {
70 throw DbException.convert(e);
71 }
72 }
73 }
74
75 private Utils() {
76 // utility class
77 }
78
79 private static int readInt(byte[] buff, int pos) {
80 return (buff[pos++] << 24) + ((buff[pos++] & 0xff) << 16) + ((buff[pos++] & 0xff) << 8) + (buff[pos] & 0xff);
81 }
82
83 /**
84 * Write a long value to the byte array at the given position. The most
85 * significant byte is written first.
86 *
87 * @param buff the byte array
88 * @param pos the position
89 * @param x the value to write
90 */
91 public static void writeLong(byte[] buff, int pos, long x) {
92 writeInt(buff, pos, (int) (x >> 32));
93 writeInt(buff, pos + 4, (int) x);
94 }
95
96 private static void writeInt(byte[] buff, int pos, int x) {
97 buff[pos++] = (byte) (x >> 24);
98 buff[pos++] = (byte) (x >> 16);
99 buff[pos++] = (byte) (x >> 8);
100 buff[pos++] = (byte) x;
101 }
102
103 /**
104 * Read a long value from the byte array at the given position. The most
105 * significant byte is read first.
106 *
107 * @param buff the byte array
108 * @param pos the position
109 * @return the value
110 */
111 public static long readLong(byte[] buff, int pos) {
112 return (((long) readInt(buff, pos)) << 32) + (readInt(buff, pos + 4) & 0xffffffffL);
113 }
114
115 /**
116 * Calculate the index of the first occurrence of the pattern in the byte
117 * array, starting with the given index. This methods returns -1 if the
118 * pattern has not been found, and the start position if the pattern is
119 * empty.
120 *
121 * @param bytes the byte array
122 * @param pattern the pattern
123 * @param start the start index from where to search
124 * @return the index
125 */
126 public static int indexOf(byte[] bytes, byte[] pattern, int start) {
127 if (pattern.length == 0) {
128 return start;
129 }
130 if (start > bytes.length) {
131 return -1;
132 }
133 int last = bytes.length - pattern.length + 1;
134 int patternLen = pattern.length;
135 next:
136 for (; start < last; start++) {
137 for (int i = 0; i < patternLen; i++) {
138 if (bytes[start + i] != pattern[i]) {
139 continue next;
140 }
141 }
142 return start;
143 }
144 return -1;
145 }
146
147 /**
148 * Calculate the hash code of the given byte array.
149 *
150 * @param value the byte array
151 * @return the hash code
152 */
153 public static int getByteArrayHash(byte[] value) {
154 int len = value.length;
155 int h = len;
156 if (len < 50) {
157 for (int i = 0; i < len; i++) {
158 h = 31 * h + value[i];
159 }
160 } else {
161 int step = len / 16;
162 for (int i = 0; i < 4; i++) {
163 h = 31 * h + value[i];
164 h = 31 * h + value[--len];
165 }
166 for (int i = 4 + step; i < len; i += step) {
167 h = 31 * h + value[i];
168 }
169 }
170 return h;
171 }
172
173 /**
174 * Compare two byte arrays. This method will always loop over all bytes and
175 * doesn't use conditional operations in the loop to make sure an attacker
176 * can not use a timing attack when trying out passwords.
177 *
178 * @param test the first array
179 * @param good the second array
180 * @return true if both byte arrays contain the same bytes
181 */
182 public static boolean compareSecure(byte[] test, byte[] good) {
183 if ((test == null) || (good == null)) {
184 return (test == null) && (good == null);
185 }
186 int len = test.length;
187 if (len != good.length) {
188 return false;
189 }
190 if (len == 0) {
191 return true;
192 }
193 // don't use conditional operations inside the loop
194 int bits = 0;
195 for (int i = 0; i < len; i++) {
196 // this will never reset any bits
197 bits |= test[i] ^ good[i];
198 }
199 return bits == 0;
200 }
201
202 /**
203 * Compare the contents of two byte arrays. If the content or length of the
204 * first array is smaller than the second array, -1 is returned. If the
205 * content or length of the second array is smaller than the first array, 1
206 * is returned. If the contents and lengths are the same, 0 is returned.
207 *
208 * @param data1 the first byte array (must not be null)
209 * @param data2 the second byte array (must not be null)
210 * @return the result of the comparison (-1, 1 or 0)
211 */
212 public static int compareNotNull(byte[] data1, byte[] data2) {
213 if (data1 == data2) {
214 return 0;
215 }
216 int len = Math.min(data1.length, data2.length);
217 for (int i = 0; i < len; i++) {
218 byte b = data1[i];
219 byte b2 = data2[i];
220 if (b != b2) {
221 return b > b2 ? 1 : -1;
222 }
223 }
224 return Integer.signum(data1.length - data2.length);
225 }
226
227 /**
228 * Copy the contents of the source array to the target array. If the size if
229 * the target array is too small, a larger array is created.
230 *
231 * @param source the source array
232 * @param target the target array
233 * @return the target array or a new one if the target array was too small
234 */
235 public static byte[] copy(byte[] source, byte[] target) {
236 int len = source.length;
237 if (len > target.length) {
238 target = new byte[len];
239 }
240 System.arraycopy(source, 0, target, 0, len);
241 return target;
242 }
243
244 /**
245 * Create a new byte array and copy all the data. If the size of the byte
246 * array is zero, the same array is returned.
247 *
248 * @param b the byte array (may not be null)
249 * @return a new byte array
250 */
251 public static byte[] cloneByteArray(byte[] b) {
252 if (b == null) {
253 return null;
254 }
255 int len = b.length;
256 if (len == 0) {
257 return EMPTY_BYTES;
258 }
259 byte[] copy = new byte[len];
260 System.arraycopy(b, 0, copy, 0, len);
261 return copy;
262 }
263
264 /**
265 * Serialize the object to a byte array.
266 *
267 * @param obj the object to serialize
268 * @return the byte array
269 */
270 public static byte[] serialize(Object obj) {
271 try {
272 if (serializer != null) {
273 return serializer.serialize(obj);
274 }
275 ByteArrayOutputStream out = new ByteArrayOutputStream();
276 ObjectOutputStream os = new ObjectOutputStream(out);
277 os.writeObject(obj);
278 return out.toByteArray();
279 } catch (Throwable e) {
280 throw DbException.get(ErrorCode.SERIALIZATION_FAILED_1, e, e.toString());
281 }
282 }
283
284 /**
285 * De-serialize the byte array to an object.
286 *
287 * @param data the byte array
288 * @return the object
289 * @throws DbException if serialization fails
290 */
291 public static Object deserialize(byte[] data) {
292 try {
293 if (serializer != null) {
294 return serializer.deserialize(data);
295 }
296 ByteArrayInputStream in = new ByteArrayInputStream(data);
297 ObjectInputStream is;
298 if (SysProperties.USE_THREAD_CONTEXT_CLASS_LOADER) {
299 final ClassLoader loader = Thread.currentThread().getContextClassLoader();
300 is = new ObjectInputStream(in) {
301 protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
302 try {
303 return Class.forName(desc.getName(), true, loader);
304 } catch (ClassNotFoundException e) {
305 return super.resolveClass(desc);
306 }
307 }
308 };
309 } else {
310 is = new ObjectInputStream(in);
311 }
312 return is.readObject();
313 } catch (Throwable e) {
314 throw DbException.get(ErrorCode.DESERIALIZATION_FAILED_1, e, e.toString());
315 }
316 }
317
318 /**
319 * Calculate the hash code of the given object. The object may be null.
320 *
321 * @param o the object
322 * @return the hash code, or 0 if the object is null
323 */
324 public static int hashCode(Object o) {
325 return o == null ? 0 : o.hashCode();
326 }
327
328 /**
329 * Get the used memory in KB.
330 * This method possibly calls System.gc().
331 *
332 * @return the used memory
333 */
334 public static int getMemoryUsed() {
335 collectGarbage();
336 Runtime rt = Runtime.getRuntime();
337 long mem = rt.totalMemory() - rt.freeMemory();
338 return (int) (mem >> 10);
339 }
340
341 /**
342 * Get the free memory in KB.
343 * This method possibly calls System.gc().
344 *
345 * @return the free memory
346 */
347 public static int getMemoryFree() {
348 collectGarbage();
349 Runtime rt = Runtime.getRuntime();
350 long mem = rt.freeMemory();
351 return (int) (mem >> 10);
352 }
353
354 /**
355 * Get the maximum memory in KB.
356 *
357 * @return the maximum memory
358 */
359 public static long getMemoryMax() {
360 long max = Runtime.getRuntime().maxMemory();
361 return max / 1024;
362 }
363
364 private static synchronized void collectGarbage() {
365 Runtime runtime = Runtime.getRuntime();
366 long total = runtime.totalMemory();
367 long time = System.currentTimeMillis();
368 if (lastGC + GC_DELAY < time) {
369 for (int i = 0; i < MAX_GC; i++) {
370 runtime.gc();
371 long now = runtime.totalMemory();
372 if (now == total) {
373 lastGC = System.currentTimeMillis();
374 break;
375 }
376 total = now;
377 }
378 }
379 }
380
381 /**
382 * Create an array of bytes with the given size. If this is not possible
383 * because not enough memory is available, an OutOfMemoryError with the
384 * requested size in the message is thrown.
385 *
386 * @param len the number of bytes requested
387 * @return the byte array
388 * @throws OutOfMemoryError
389 */
390 public static byte[] newBytes(int len) {
391 try {
392 if (len == 0) {
393 return EMPTY_BYTES;
394 }
395 return new byte[len];
396 } catch (OutOfMemoryError e) {
397 Error e2 = new OutOfMemoryError("Requested memory: " + len);
398 e2.initCause(e);
399 throw e2;
400 }
401 }
402
403 /**
404 * Create an int array with the given size.
405 *
406 * @param len the number of bytes requested
407 * @return the int array
408 */
409 public static int[] newIntArray(int len) {
410 if (len == 0) {
411 return EMPTY_INT_ARRAY;
412 }
413 return new int[len];
414 }
415
416 /**
417 * Create a long array with the given size.
418 *
419 * @param len the number of bytes requested
420 * @return the int array
421 */
422 public static long[] newLongArray(int len) {
423 if (len == 0) {
424 return EMPTY_LONG_ARRAY;
425 }
426 return new long[len];
427 }
428
429 /**
430 * Checks if given classes have a common Comparable superclass.
431 *
432 * @param c1 the first class
433 * @param c2 the second class
434 * @return true if they have
435 */
436 public static boolean haveCommonComparableSuperclass(Class<?> c1, Class<?> c2) {
437 if (c1 == c2 || c1.isAssignableFrom(c2) || c2.isAssignableFrom(c1)) {
438 return true;
439 }
440 Class<?> top1;
441 do {
442 top1 = c1;
443 c1 = c1.getSuperclass();
444 } while (Comparable.class.isAssignableFrom(c1));
445
446 Class<?> top2;
447 do {
448 top2 = c2;
449 c2 = c2.getSuperclass();
450 } while (Comparable.class.isAssignableFrom(c2));
451
452 return top1 == top2;
453 }
454
455 /**
456 * Load a class, but check if it is allowed to load this class first. To
457 * perform access rights checking, the system property h2.allowedClasses
458 * needs to be set to a list of class file name prefixes.
459 *
460 * @param className the name of the class
461 * @return the class object
462 */
463 public static Class<?> loadUserClass(String className) {
464 if (allowedClassNames == null) {
465 // initialize the static fields
466 String s = SysProperties.ALLOWED_CLASSES;
467 ArrayList<String> prefixes = New.arrayList();
468 boolean allowAll = false;
469 HashSet<String> classNames = New.hashSet();
470 for (String p : StringUtils.arraySplit(s, ',', true)) {
471 if (p.equals("*")) {
472 allowAll = true;
473 } else if (p.endsWith("*")) {
474 prefixes.add(p.substring(0, p.length() - 1));
475 } else {
476 classNames.add(p);
477 }
478 }
479 allowedClassNamePrefixes = new String[prefixes.size()];
480 prefixes.toArray(allowedClassNamePrefixes);
481 allowAllClasses = allowAll;
482 allowedClassNames = classNames;
483 }
484 if (!allowAllClasses && !allowedClassNames.contains(className)) {
485 boolean allowed = false;
486 for (String s : allowedClassNamePrefixes) {
487 if (className.startsWith(s)) {
488 allowed = true;
489 }
490 }
491 if (!allowed) {
492 throw DbException.get(ErrorCode.ACCESS_DENIED_TO_CLASS_1, className);
493 }
494 }
495 // the following code might be better for OSGi (need to verify):
496 /*
497 try {
498 return Utils.class.getClassLoader().loadClass(className);
499 } catch (Throwable e) {
500 try {
501 return Thread.currentThread().getContextClassLoader().loadClass(className);
502 } catch (Throwable e2) {
503 DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
504 }
505 }
506 */
507 try {
508 return Class.forName(className);
509 } catch (ClassNotFoundException e) {
510 try {
511 return Class.forName(className, true, Thread.currentThread().getContextClassLoader());
512 } catch (Exception e2) {
513 throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
514 }
515 } catch (NoClassDefFoundError e) {
516 throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
517 } catch (Error e) {
518 // UnsupportedClassVersionError
519 throw DbException.get(ErrorCode.GENERAL_ERROR_1, e, className);
520 }
521 }
522
523 /**
524 * Get a resource from the resource map.
525 *
526 * @param name the name of the resource
527 * @return the resource data
528 */
529 public static byte[] getResource(String name) throws IOException {
530 byte[] data = RESOURCES.get(name);
531 if (data == null) {
532 data = loadResource(name);
533 RESOURCES.put(name, data);
534 }
535 return data == null ? EMPTY_BYTES : data;
536 }
537
538 private static byte[] loadResource(String name) throws IOException {
539 InputStream in = Utils.class.getResourceAsStream("data.zip");
540 if (in == null) {
541 in = Utils.class.getResourceAsStream(name);
542 if (in == null) {
543 return null;
544 }
545 return IOUtils.readBytesAndClose(in, 0);
546 }
547 ZipInputStream zipIn = new ZipInputStream(in);
548 try {
549 while (true) {
550 ZipEntry entry = zipIn.getNextEntry();
551 if (entry == null) {
552 break;
553 }
554 String entryName = entry.getName();
555 if (!entryName.startsWith("/")) {
556 entryName = "/" + entryName;
557 }
558 if (entryName.equals(name)) {
559 ByteArrayOutputStream out = new ByteArrayOutputStream();
560 IOUtils.copy(zipIn, out);
561 zipIn.closeEntry();
562 return out.toByteArray();
563 }
564 zipIn.closeEntry();
565 }
566 } catch (IOException e) {
567 // if this happens we have a real problem
568 e.printStackTrace();
569 } finally {
570 zipIn.close();
571 }
572 return null;
573 }
574
575 /**
576 * Calls a static method via reflection. This will try to use the method
577 * where the most parameter classes match exactly (this algorithm is simpler
578 * than the one in the Java specification, but works well for most cases).
579 *
580 * @param classAndMethod a string with the entire class and method name, eg.
581 * "java.lang.System.gc"
582 * @param params the method parameters
583 * @return the return value from this call
584 */
585 public static Object callStaticMethod(String classAndMethod, Object... params) throws Exception {
586 int lastDot = classAndMethod.lastIndexOf('.');
587 String className = classAndMethod.substring(0, lastDot);
588 String methodName = classAndMethod.substring(lastDot + 1);
589 return callMethod(null, Class.forName(className), methodName, params);
590 }
591
592 /**
593 * Calls an instance method via reflection. This will try to use the method
594 * where the most parameter classes match exactly (this algorithm is simpler
595 * than the one in the Java specification, but works well for most cases).
596 *
597 * @param instance the instance on which the call is done
598 * @param methodName a string with the method name
599 * @param params the method parameters
600 * @return the return value from this call
601 */
602 public static Object callMethod(
603 Object instance,
604 String methodName,
605 Object... params) throws Exception {
606 return callMethod(instance, instance.getClass(), methodName, params);
607 }
608
609 private static Object callMethod(
610 Object instance, Class<?> clazz,
611 String methodName,
612 Object... params) throws Exception {
613 Method best = null;
614 int bestMatch = 0;
615 boolean isStatic = instance == null;
616 for (Method m : clazz.getMethods()) {
617 if (Modifier.isStatic(m.getModifiers()) == isStatic && m.getName().equals(methodName)) {
618 int p = match(m.getParameterTypes(), params);
619 if (p > bestMatch) {
620 bestMatch = p;
621 best = m;
622 }
623 }
624 }
625 if (best == null) {
626 throw new NoSuchMethodException(methodName);
627 }
628 return best.invoke(instance, params);
629 }
630
631 /**
632 * Creates a new instance. This will try to use the constructor where the
633 * most parameter classes match exactly (this algorithm is simpler than the
634 * one in the Java specification, but works well for most cases).
635 *
636 * @param className a string with the entire class, eg. "java.lang.Integer"
637 * @param params the constructor parameters
638 * @return the newly created object
639 */
640 public static Object newInstance(String className, Object... params) throws Exception {
641 Constructor<?> best = null;
642 int bestMatch = 0;
643 for (Constructor<?> c : Class.forName(className).getConstructors()) {
644 int p = match(c.getParameterTypes(), params);
645 if (p > bestMatch) {
646 bestMatch = p;
647 best = c;
648 }
649 }
650 if (best == null) {
651 throw new NoSuchMethodException(className);
652 }
653 return best.newInstance(params);
654 }
655
656 private static int match(Class<?>[] params, Object[] values) {
657 int len = params.length;
658 if (len == values.length) {
659 int points = 1;
660 for (int i = 0; i < len; i++) {
661 Class<?> pc = getNonPrimitiveClass(params[i]);
662 Object v = values[i];
663 Class<?> vc = v == null ? null : v.getClass();
664 if (pc == vc) {
665 points++;
666 } else if (vc == null) {
667 // can't verify
668 } else if (!pc.isAssignableFrom(vc)) {
669 return 0;
670 }
671 }
672 return points;
673 }
674 return 0;
675 }
676
677 /**
678 * Returns a static field.
679 *
680 * @param classAndField a string with the entire class and field name
681 * @return the field value
682 */
683 public static Object getStaticField(String classAndField) throws Exception {
684 int lastDot = classAndField.lastIndexOf('.');
685 String className = classAndField.substring(0, lastDot);
686 String fieldName = classAndField.substring(lastDot + 1);
687 return Class.forName(className).getField(fieldName).get(null);
688 }
689
690 /**
691 * Returns a static field.
692 *
693 * @param instance the instance on which the call is done
694 * @param fieldName the field name
695 * @return the field value
696 */
697 public static Object getField(Object instance, String fieldName) throws Exception {
698 return instance.getClass().getField(fieldName).get(instance);
699 }
700
701 /**
702 * Returns true if the class is present in the current class loader.
703 *
704 * @param fullyQualifiedClassName a string with the entire class name, eg.
705 * "java.lang.System"
706 * @return true if the class is present
707 */
708 public static boolean isClassPresent(String fullyQualifiedClassName) {
709 try {
710 Class.forName(fullyQualifiedClassName);
711 return true;
712 } catch (ClassNotFoundException e) {
713 return false;
714 }
715 }
716
717 /**
718 * Convert primitive class names to java.lang.* class names.
719 *
720 * @param clazz the class (for example: int)
721 * @return the non-primitive class (for example: java.lang.Integer)
722 */
723 public static Class<?> getNonPrimitiveClass(Class<?> clazz) {
724 if (!clazz.isPrimitive()) {
725 return clazz;
726 } else if (clazz == boolean.class) {
727 return Boolean.class;
728 } else if (clazz == byte.class) {
729 return Byte.class;
730 } else if (clazz == char.class) {
731 return Character.class;
732 } else if (clazz == double.class) {
733 return Double.class;
734 } else if (clazz == float.class) {
735 return Float.class;
736 } else if (clazz == int.class) {
737 return Integer.class;
738 } else if (clazz == long.class) {
739 return Long.class;
740 } else if (clazz == short.class) {
741 return Short.class;
742 } else if (clazz == void.class) {
743 return Void.class;
744 }
745 return clazz;
746 }
747
748 /**
749 * Get the system property. If the system property is not set, or if a
750 * security exception occurs, the default value is returned.
751 *
752 * @param key the key
753 * @param defaultValue the default value
754 * @return the value
755 */
756 public static String getProperty(String key, String defaultValue) {
757 try {
758 return System.getProperty(key, defaultValue);
759 } catch (SecurityException se) {
760 return defaultValue;
761 }
762 }
763
764 /**
765 * Get the system property. If the system property is not set, or if a
766 * security exception occurs, the default value is returned.
767 *
768 * @param key the key
769 * @param defaultValue the default value
770 * @return the value
771 */
772 public static int getProperty(String key, int defaultValue) {
773 String s = getProperty(key, null);
774 if (s != null) {
775 try {
776 return Integer.decode(s).intValue();
777 } catch (NumberFormatException e) {
778 // ignore
779 }
780 }
781 return defaultValue;
782 }
783
784 /**
785 * Get the system property. If the system property is not set, or if a
786 * security exception occurs, the default value is returned.
787 *
788 * @param key the key
789 * @param defaultValue the default value
790 * @return the value
791 */
792 public static boolean getProperty(String key, boolean defaultValue) {
793 String s = getProperty(key, null);
794 if (s != null) {
795 try {
796 return Boolean.parseBoolean(s);
797 } catch (NumberFormatException e) {
798 // ignore
799 }
800 }
801 return defaultValue;
802 }
803
804 }
805