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