EMMA Coverage Report (generated Sun Mar 01 22:06:14 CET 2015)
[all classes][org.h2.util]

COVERAGE SUMMARY FOR SOURCE FILE [Utils.java]

nameclass, %method, %block, %line, %
Utils.java100% (1/1)90%  (35/39)86%  (975/1136)82%  (225.5/274)

COVERAGE BREAKDOWN BY CLASS AND METHOD

nameclass, %method, %block, %line, %
     
class Utils100% (1/1)90%  (35/39)86%  (975/1136)82%  (225.5/274)
Utils (): void 0%   (0/1)0%   (0/3)0%   (0/2)
indexOf (byte [], byte [], int): int 0%   (0/1)0%   (0/48)0%   (0/12)
newIntArray (int): int [] 0%   (0/1)0%   (0/7)0%   (0/3)
newLongArray (int): long [] 0%   (0/1)0%   (0/7)0%   (0/3)
scaleForAvailableMemory (int): int 100% (1/1)35%  (15/43)33%  (3/9)
getProperty (String, String): String 100% (1/1)57%  (4/7)33%  (1/3)
loadResource (String): byte [] 100% (1/1)66%  (56/85)62%  (15.5/25)
compareNotNullSigned (byte [], byte []): int 100% (1/1)79%  (34/43)78%  (7/9)
newInstance (String, Object []): Object 100% (1/1)89%  (40/45)90%  (9/10)
compareSecure (byte [], byte []): boolean 100% (1/1)90%  (45/50)81%  (8.9/11)
getProperty (String, boolean): boolean 100% (1/1)92%  (11/12)80%  (4/5)
callMethod (Object, Class, String, Object []): Object 100% (1/1)92%  (56/61)92%  (11/12)
getProperty (String, int): int 100% (1/1)92%  (12/13)80%  (4/5)
compareNotNullUnsigned (byte [], byte []): int 100% (1/1)94%  (44/47)87%  (7.8/9)
match (Class [], Object []): int 100% (1/1)94%  (47/50)97%  (13.6/14)
haveCommonComparableSuperclass (Class, Class): boolean 100% (1/1)95%  (36/38)97%  (8.7/9)
getNonPrimitiveClass (Class): Class 100% (1/1)96%  (50/52)95%  (20/21)
<static initializer> 100% (1/1)100% (12/12)100% (4/4)
callMethod (Object, String, Object []): Object 100% (1/1)100% (7/7)100% (1/1)
callStaticMethod (String, Object []): Object 100% (1/1)100% (22/22)100% (4/4)
cloneByteArray (byte []): byte [] 100% (1/1)100% (22/22)100% (8/8)
collectGarbage (): void 100% (1/1)100% (35/35)100% (12/12)
copy (byte [], byte []): byte [] 100% (1/1)100% (18/18)100% (5/5)
getByteArrayHash (byte []): int 100% (1/1)100% (74/74)100% (12/12)
getField (Object, String): Object 100% (1/1)100% (7/7)100% (1/1)
getMemoryFree (): int 100% (1/1)100% (11/11)100% (4/4)
getMemoryMax (): long 100% (1/1)100% (7/7)100% (2/2)
getMemoryUsed (): int 100% (1/1)100% (14/14)100% (4/4)
getResource (String): byte [] 100% (1/1)100% (19/19)100% (6/6)
getStaticField (String): Object 100% (1/1)100% (22/22)100% (4/4)
hashCode (Object): int 100% (1/1)100% (7/7)100% (1/1)
isClassPresent (String): boolean 100% (1/1)100% (8/8)100% (4/4)
partialQuickSort (Object [], int, int, Comparator, int, int): void 100% (1/1)100% (112/112)100% (25/25)
partitionTopN (Object [], int, int, Comparator): void 100% (1/1)100% (15/15)100% (2/2)
readInt (byte [], int): int 100% (1/1)100% (31/31)100% (1/1)
readLong (byte [], int): long 100% (1/1)100% (16/16)100% (1/1)
sortTopN (Object [], int, int, Comparator): void 100% (1/1)100% (20/20)100% (3/3)
writeInt (byte [], int, int): void 100% (1/1)100% (31/31)100% (5/5)
writeLong (byte [], int, long): void 100% (1/1)100% (15/15)100% (3/3)

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

[all classes][org.h2.util]
EMMA 2.0.5312 (C) Vladimir Roubtsov