Top Description Inners Fields Constructors Methods
org.h2.util

public Class Utils

extends Object
Class Inheritance
Imports
java.io.ByteArrayOutputStream, .IOException, .InputStream, java.lang.management.GarbageCollectorMXBean, .ManagementFactory, .OperatingSystemMXBean, java.lang.reflect.Constructor, .Method, .Modifier, java.util.ArrayList, .Arrays, .Comparator, .HashMap, java.util.concurrent.BlockingQueue, .ExecutionException, .LinkedBlockingQueue, .RejectedExecutionException, .ThreadPoolExecutor, .TimeUnit, java.util.zip.ZipEntry, .ZipInputStream

This utility class contains miscellaneous functions.

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
Utils.ClassFactory

The utility methods will try to use the provided class factories to convert binary name of class to Class object.

Field Summary

Modifier and TypeField and Description
public static final byte[]
EMPTY_BYTES

An 0-size byte array.

public static final int[]
EMPTY_INT_ARRAY

An 0-size int array.

private static final HashMap<String, byte[]>

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static Object

Returns:

the return value from this call
callMethod
(Object
the instance on which the call is done
instance
,
String
a string with the method name
methodName
,
Object...
the method parameters
params
)

Calls an instance method via reflection.

private static Object
callMethod(Object instance, Class<?> clazz, String methodName, Object... params)

public static Object

Returns:

the return value from this call
callStaticMethod
(String
a string with the entire class and method name, eg. "java.lang.System.gc"
classAndMethod
,
Object...
the method parameters
params
)

Calls a static method via reflection.

public static byte[]

Returns:

a new byte array
cloneByteArray
(byte[]
the byte array (may not be null)
b
)

Create a new byte array and copy all the data.

public static synchronized void
collectGarbage()

Run Java memory garbage collection.

public static boolean

Returns:

true if both byte arrays contain the same bytes
compareSecure
(byte[]
the first array
test
,
byte[]
the second array
good
)

Compare two byte arrays.

public static byte[]

Returns:

the target array or a new one if the target array was too small
copy
(byte[]
the source array
source
,
byte[]
the target array
target
)

Copy the contents of the source array to the target array.

public static byte[]

Returns:

the byte array
copyBytes
(byte[]
source array
bytes
,
int
the number of bytes in the new array
len
)

Creates a copy of array of bytes with the new size.

public static ThreadPoolExecutor
public static ThreadPoolExecutor
public static long

Returns:

time in nanoseconds, never equal to 0
currentNanoTime
()

Returns the current value of the high-resolution time source.

public static long

Returns:

time in nanoseconds, never equal to 0
currentNanoTimePlusMillis
(int
additional offset in milliseconds
ms
)

Returns the current value of the high-resolution time source plus the specified offset.

public static void
flushExecutor(ThreadPoolExecutor
to flush
executor
)

Makes sure that all currently submitted tasks are processed before this method returns.

public static int

Returns:

the hash code
getByteArrayHash
(byte[]
the byte array
value
)

Calculate the hash code of the given byte array.

public static long
public static long
public static long

Returns:

the free memory
getMemoryFree
()

Get the free memory in KB.

public static long

Returns:

the maximum memory
getMemoryMax
()

Get the maximum memory in KB.

public static long

Returns:

the used memory
getMemoryUsed
()

Get the used memory in KB.

public static Class<?>

Returns:

the non-primitive class (for example: java.lang.Integer)
getNonPrimitiveClass
(Class<?>
the class (for example: int)
clazz
)

Convert primitive class names to java.lang.* class names.

public static String

Returns:

the value
getProperty
(String
the key
key
,
String
the default value
defaultValue
)

Get the system property.

public static int

Returns:

the value
getProperty
(String
the key
key
,
int
the default value
defaultValue
)

Get the system property.

public static boolean

Returns:

the value
getProperty
(String
the key
key
,
boolean
the default value
defaultValue
)

Get the system property.

public static byte[]

Returns:

the resource data
getResource
(String
the name of the resource
name
)

Get a resource from the resource map.

public static int

Returns:

the index
indexOf
(byte[]
the byte array
bytes
,
byte[]
the pattern
pattern
,
int
the start index from where to search
start
)

Calculate the index of the first occurrence of the pattern in the byte array, starting with the given index.

private static byte[]
private static int
match(Class<?>[] params, Object[] values)

public static long

Returns:

time in nanoseconds, never equal to 0
nanoTimePlusMillis
(long
time in nanoseconds
nanoTime
,
int
additional offset in milliseconds
ms
)

Returns the current value of the high-resolution time source plus the specified offset.

public static byte[]

Returns:

the byte array
newBytes
(int
the number of bytes requested
len
)

Create an array of bytes with the given size.

public static Object

Returns:

the newly created object
newInstance
(String
a string with the entire class, eg. "java.lang.Integer"
className
,
Object...
the constructor parameters
params
)

Creates a new instance.

public static <
the type
T
>
ArrayList<T>

Returns:

the object
newSmallArrayList
()

Create a new ArrayList with an initial capacity of 4.

public static boolean

Returns:

parsed or default value
parseBoolean
(String
string to parse
value
,
boolean
value to return if value is null or on parsing error
defaultValue
,
boolean
throw exception on parsing error or return default value instead
throwException
)

Parses the specified string to boolean value.

private static <
the type of elements
X
>
void
partialQuickSort(X[]
the array to sort
array
,
int
the lower index with data, inclusive
low
,
int
the higher index with data, inclusive, high > low
high
,
Comparator<? super X>
the comparator
comp
,
int
the start index of requested region, inclusive
start
,
int
the end index of requested region, inclusive, end >= start
end
)

Partial quick sort.

public static int

Returns:

the scaled value
scaleForAvailableMemory
(int
the value to scale
value
)

Scale the value with the available memory.

public static void
public static <
the type of elements
X
>
void
sortTopN(X[]
the array.
array
,
int
the start index, inclusive
fromInclusive
,
int
the end index, exclusive
toExclusive
,
Comparator<? super X>
the comparator.
comp
)

Find the top limit values using given comparator and place them as in a full array sort, in descending order.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

EMPTY_BYTESback to summary
public static final byte[] EMPTY_BYTES

An 0-size byte array.

EMPTY_INT_ARRAYback to summary
public static final int[] EMPTY_INT_ARRAY

An 0-size int array.

RESOURCESback to summary
private static final HashMap<String, byte[]> RESOURCES

Constructor Detail

Utilsback to summary
private Utils()

Method Detail

callMethodback to summary
public static Object callMethod(Object instance, String methodName, Object... params) throws Exception

Calls an instance method via reflection. This will try to use the method where the most parameter classes match exactly (this algorithm is simpler than the one in the Java specification, but works well for most cases).

Parameters
instance:Object

the instance on which the call is done

methodName:String

a string with the method name

params:Object[]

the method parameters

Returns:Object

the return value from this call

Exceptions
Exception:
on failure
callMethodback to summary
private static Object callMethod(Object instance, Class<?> clazz, String methodName, Object... params) throws Exception
callStaticMethodback to summary
public static Object callStaticMethod(String classAndMethod, Object... params) throws Exception

Calls a static method via reflection. This will try to use the method where the most parameter classes match exactly (this algorithm is simpler than the one in the Java specification, but works well for most cases).

Parameters
classAndMethod:String

a string with the entire class and method name, eg. "java.lang.System.gc"

params:Object[]

the method parameters

Returns:Object

the return value from this call

Exceptions
Exception:
on failure
cloneByteArrayback to summary
public static byte[] cloneByteArray(byte[] b)

Create a new byte array and copy all the data. If the size of the byte array is zero, the same array is returned.

Parameters
b:byte[]

the byte array (may not be null)

Returns:byte[]

a new byte array

collectGarbageback to summary
public static synchronized void collectGarbage()

Run Java memory garbage collection.

compareSecureback to summary
public static boolean compareSecure(byte[] test, byte[] good)

Compare two byte arrays. This method will always loop over all bytes and doesn't use conditional operations in the loop to make sure an attacker can not use a timing attack when trying out passwords.

Parameters
test:byte[]

the first array

good:byte[]

the second array

Returns:boolean

true if both byte arrays contain the same bytes

copyback to summary
public static byte[] copy(byte[] source, byte[] target)

Copy the contents of the source array to the target array. If the size if the target array is too small, a larger array is created.

Parameters
source:byte[]

the source array

target:byte[]

the target array

Returns:byte[]

the target array or a new one if the target array was too small

copyBytesback to summary
public static byte[] copyBytes(byte[] bytes, int len)

Creates a copy of array of bytes with the new size. If this is not possible because not enough memory is available, an OutOfMemoryError with the requested size in the message is thrown.

This method should be used if the size of the array is user defined, or stored in a file, so wrong size data can be distinguished from regular out-of-memory.

Parameters
bytes:byte[]

source array

len:int

the number of bytes in the new array

Returns:byte[]

the byte array

Exceptions
OutOfMemoryError:
if the allocation was too large
See Also
Arrays#copyOf(byte[], int)
createSingleThreadExecutorback to summary
public static ThreadPoolExecutor createSingleThreadExecutor(String threadName)
createSingleThreadExecutorback to summary
public static ThreadPoolExecutor createSingleThreadExecutor(String threadName, BlockingQueue<Runnable> workQueue)
currentNanoTimeback to summary
public static long currentNanoTime()

Returns the current value of the high-resolution time source.

Returns:long

time in nanoseconds, never equal to 0

See Also
System#nanoTime()
currentNanoTimePlusMillisback to summary
public static long currentNanoTimePlusMillis(int ms)

Returns the current value of the high-resolution time source plus the specified offset.

Parameters
ms:int

additional offset in milliseconds

Returns:long

time in nanoseconds, never equal to 0

See Also
System#nanoTime()
flushExecutorback to summary
public static void flushExecutor(ThreadPoolExecutor executor)

Makes sure that all currently submitted tasks are processed before this method returns. It is assumed that there will be no new submissions to this executor, once this method has started. It is assumed that executor is single-threaded, and flush is done by submitting a dummy task and waiting for its completion.

Parameters
executor:ThreadPoolExecutor

to flush

getByteArrayHashback to summary
public static int getByteArrayHash(byte[] value)

Calculate the hash code of the given byte array.

Parameters
value:byte[]

the byte array

Returns:int

the hash code

getGarbageCollectionCountback to summary
public static long getGarbageCollectionCount()
getGarbageCollectionTimeback to summary
public static long getGarbageCollectionTime()
getMemoryFreeback to summary
public static long getMemoryFree()

Get the free memory in KB. This method possibly calls System.gc().

Returns:long

the free memory

getMemoryMaxback to summary
public static long getMemoryMax()

Get the maximum memory in KB.

Returns:long

the maximum memory

getMemoryUsedback to summary
public static long getMemoryUsed()

Get the used memory in KB. This method possibly calls System.gc().

Returns:long

the used memory

getNonPrimitiveClassback to summary
public static Class<?> getNonPrimitiveClass(Class<?> clazz)

Convert primitive class names to java.lang.* class names.

Parameters
clazz:Class<?>

the class (for example: int)

Returns:Class<?>

the non-primitive class (for example: java.lang.Integer)

getPropertyback to summary
public static String getProperty(String key, String defaultValue)

Get the system property. If the system property is not set, or if a security exception occurs, the default value is returned.

Parameters
key:String

the key

defaultValue:String

the default value

Returns:String

the value

getPropertyback to summary
public static int getProperty(String key, int defaultValue)

Get the system property. If the system property is not set, or if a security exception occurs, the default value is returned.

Parameters
key:String

the key

defaultValue:int

the default value

Returns:int

the value

getPropertyback to summary
public static boolean getProperty(String key, boolean defaultValue)

Get the system property. If the system property is not set, or if a security exception occurs, the default value is returned.

Parameters
key:String

the key

defaultValue:boolean

the default value

Returns:boolean

the value

getResourceback to summary
public static byte[] getResource(String name) throws IOException

Get a resource from the resource map.

Parameters
name:String

the name of the resource

Returns:byte[]

the resource data

Exceptions
IOException:
on failure
indexOfback to summary
public static int indexOf(byte[] bytes, byte[] pattern, int start)

Calculate the index of the first occurrence of the pattern in the byte array, starting with the given index. This methods returns -1 if the pattern has not been found, and the start position if the pattern is empty.

Parameters
bytes:byte[]

the byte array

pattern:byte[]

the pattern

start:int

the start index from where to search

Returns:int

the index

loadResourceback to summary
private static byte[] loadResource(String name) throws IOException
matchback to summary
private static int match(Class<?>[] params, Object[] values)
nanoTimePlusMillisback to summary
public static long nanoTimePlusMillis(long nanoTime, int ms)

Returns the current value of the high-resolution time source plus the specified offset.

Parameters
nanoTime:long

time in nanoseconds

ms:int

additional offset in milliseconds

Returns:long

time in nanoseconds, never equal to 0

See Also
System#nanoTime()
newBytesback to summary
public static byte[] newBytes(int len)

Create an array of bytes with the given size. If this is not possible because not enough memory is available, an OutOfMemoryError with the requested size in the message is thrown.

This method should be used if the size of the array is user defined, or stored in a file, so wrong size data can be distinguished from regular out-of-memory.

Parameters
len:int

the number of bytes requested

Returns:byte[]

the byte array

Exceptions
OutOfMemoryError:
if the allocation was too large
newInstanceback to summary
public static Object newInstance(String className, Object... params) throws Exception

Creates a new instance. This will try to use the constructor where the most parameter classes match exactly (this algorithm is simpler than the one in the Java specification, but works well for most cases).

Parameters
className:String

a string with the entire class, eg. "java.lang.Integer"

params:Object[]

the constructor parameters

Returns:Object

the newly created object

Exceptions
Exception:
on failure
newSmallArrayListback to summary
public static <T> ArrayList<T> newSmallArrayList()

Create a new ArrayList with an initial capacity of 4.

Parameters
<T>
the type
Returns:ArrayList<T>

the object

parseBooleanback to summary
public static boolean parseBoolean(String value, boolean defaultValue, boolean throwException)

Parses the specified string to boolean value.

Parameters
value:String

string to parse

defaultValue:boolean

value to return if value is null or on parsing error

throwException:boolean

throw exception on parsing error or return default value instead

Returns:boolean

parsed or default value

Exceptions
IllegalArgumentException:
on parsing error if throwException is true
partialQuickSortback to summary
private static <X> void partialQuickSort(X[] array, int low, int high, Comparator<? super X> comp, int start, int end)

Partial quick sort.

Works with elements from low to high indexes, inclusive.

Moves smallest elements to low..start-1 positions and largest elements to end+1..high positions. Middle elements are placed into start..end positions. All these regions aren't fully sorted.

Parameters
<X>
the type of elements
array:X[]

the array to sort

low:int

the lower index with data, inclusive

high:int

the higher index with data, inclusive, high > low

comp:Comparator<? super X>

the comparator

start:int

the start index of requested region, inclusive

end:int

the end index of requested region, inclusive, end >= start

scaleForAvailableMemoryback to summary
public static int scaleForAvailableMemory(int value)

Scale the value with the available memory. If 1 GB of RAM is available, the value is returned, if 2 GB are available, then twice the value, and so on.

Parameters
value:int

the value to scale

Returns:int

the scaled value

shutdownExecutorback to summary
public static void shutdownExecutor(ThreadPoolExecutor executor)
sortTopNback to summary
public static <X> void sortTopN(X[] array, int fromInclusive, int toExclusive, Comparator<? super X> comp)

Find the top limit values using given comparator and place them as in a full array sort, in descending order.

Parameters
<X>
the type of elements
array:X[]

the array.

fromInclusive:int

the start index, inclusive

toExclusive:int

the end index, exclusive

comp:Comparator<? super X>

the comparator.

org.h2.util back to summary

public Interface Utils.ClassFactory


The utility methods will try to use the provided class factories to convert binary name of class to Class object. Used by H2 OSGi Activator in order to provide a class from another bundle ClassLoader.

Method Summary

Modifier and TypeMethod and Description
public Class<?>

Returns:

the class object
loadClass
(String
the binary name of the class
name
)

Load the class.

public boolean

Returns:

true if this factory can return a valid class for the provided class name
match
(String
the binary name of the class
name
)

Check whether the factory can return the named class.

Method Detail

loadClassback to summary
public Class<?> loadClass(String name) throws ClassNotFoundException

Load the class.

Parameters
name:String

the binary name of the class

Returns:Class<?>

the class object

Exceptions
ClassNotFoundException:
If the class is not handle by this factory
matchback to summary
public boolean match(String name)

Check whether the factory can return the named class.

Parameters
name:String

the binary name of the class

Returns:boolean

true if this factory can return a valid class for the provided class name