1 /*
2 * Copyright 2012-2025 CodeLibs Project and the Others.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13 * either express or implied. See the License for the specific language
14 * governing permissions and limitations under the License.
15 */
16 package org.codelibs.fess.util;
17
18 import java.util.Arrays;
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21
22 /**
23 * Utility class for JVM-related operations.
24 * This class provides methods for handling JVM options and version detection.
25 */
26 public final class JvmUtil {
27 private static final Pattern VERSION_PREFIX_PATTERN = Pattern.compile("([0-9]+)(\\-?):(.*)");
28
29 private JvmUtil() {
30 // nothing
31 }
32
33 /**
34 * Filters JVM options based on the current Java version.
35 * Options can be prefixed with version numbers to specify compatibility.
36 * Format: "version:option" or "version-:option" (for version and above).
37 *
38 * @param values the array of JVM options to filter
39 * @return the filtered array of JVM options applicable to the current Java version
40 */
41 public static String[] filterJvmOptions(final String[] values) {
42 final int version = getJavaVersion();
43 return Arrays.stream(values).map(s -> {
44 final Matcher matcher = VERSION_PREFIX_PATTERN.matcher(s);
45 if (!matcher.matches()) {
46 return s;
47 }
48 final int v = Integer.parseInt(matcher.group(1));
49 if ("-".equals(matcher.group(2))) {
50 if (version >= v) {
51 return matcher.group(3);
52 }
53 } else if (v == version) {
54 return matcher.group(3);
55 }
56 return null;
57 }).filter(s -> s != null).toArray(n -> new String[n]);
58 }
59
60 /**
61 * Gets the major version number of the current Java runtime.
62 * For Java 8 and below, returns the minor version (e.g., 8 for Java 1.8).
63 * For Java 9 and above, returns the major version (e.g., 11 for Java 11).
64 *
65 * @return the Java version number, defaults to 8 if version cannot be determined
66 */
67 public static int getJavaVersion() {
68 final String javaVersion = System.getProperty("java.version");
69 int version = 8;
70 if (javaVersion != null) {
71 final String[] split = javaVersion.split("[\\._]");
72 if (split.length > 0) {
73 version = Integer.parseInt(split[0]);
74 if (version == 1 && split.length > 1) {
75 version = Integer.parseInt(split[1]);
76 }
77 }
78 }
79 return version;
80 }
81 }