Coverage Summary for Class: PreflightChecksUtils (co.rsk.util)

Class Class, % Method, % Line, %
PreflightChecksUtils 0% (0/1) 0% (0/7) 0% (0/21)


1 package co.rsk.util; 2  3 import co.rsk.RskContext; 4 import co.rsk.config.NodeCliFlags; 5 import com.google.common.annotations.VisibleForTesting; 6 import org.apache.commons.lang3.StringUtils; 7 import org.slf4j.Logger; 8 import org.slf4j.LoggerFactory; 9  10 import java.util.Arrays; 11  12 /** 13  * Created by Nazaret GarcĂ­a on 21/01/2021 14  * 15  * This class exposes a method to run a variety of checks. 16  * If any given check fails, then a PreflightCheckException exception is thrown. 17  * 18  * Flags, as command-line arguments, can be used to skip or configure any available check. 19  * 20  * Current Supported Checks: 21  * 22  * - Supported Java Version Check: (can be skipped by setting the --skip-java-check flag) 23  */ 24  25 public class PreflightChecksUtils { 26  private static final Logger logger = LoggerFactory.getLogger(PreflightChecksUtils.class); 27  28  private static final int[] SUPPORTED_JAVA_VERSIONS = {8, 11}; 29  30  private final RskContext rskContext; 31  32  public PreflightChecksUtils(RskContext rskContext) { 33  this.rskContext = rskContext; 34  } 35  36  /** 37  * Checks if current Java Version is supported 38  * @throws PreflightCheckException if current Java Version is not supported 39  */ 40  @VisibleForTesting 41  void checkSupportedJavaVersion() throws PreflightCheckException { 42  String javaVersion = getJavaVersion(); 43  44  int intJavaVersion = getIntJavaVersion(javaVersion); 45  46  if (Arrays.stream(SUPPORTED_JAVA_VERSIONS).noneMatch(v -> intJavaVersion == v)) { 47  String errorMessage = String.format("Invalid Java Version '%s'. Supported versions: %s", intJavaVersion, StringUtils.join(SUPPORTED_JAVA_VERSIONS, ' ')); 48  logger.error(errorMessage); 49  throw new PreflightCheckException(errorMessage); 50  } 51  } 52  53  @VisibleForTesting 54  String getJavaVersion() { 55  return System.getProperty("java.version"); 56  } 57  58  /** 59  * Returns the Java version as an int value. 60  * Formats allowed: 1.8.0_72-ea, 9-ea, 9, 9.0.1, 11, 11.0, etc. 61  * Based on @link https://stackoverflow.com/a/49512420 62  * @param version The java version as String 63  * @return the Java version as an int value (8, 9, etc.) 64  */ 65  @VisibleForTesting 66  int getIntJavaVersion(String version) { 67  if (version.startsWith("1.")) { 68  version = version.substring(2); 69  } 70  71  int dotPos = version.indexOf('.'); 72  int dashPos = version.indexOf('-'); 73  74  int endIndex; 75  76  if (dotPos > -1) { 77  endIndex = dotPos; 78  } else { 79  endIndex = dashPos > -1 ? dashPos : version.length(); 80  } 81  82  return Integer.parseInt(version.substring(0, endIndex)); 83  } 84  85  public void runChecks() throws PreflightCheckException { 86  if (!rskContext.getCliArgs().getFlags().contains(NodeCliFlags.SKIP_JAVA_CHECK)) { 87  checkSupportedJavaVersion(); 88  } 89  } 90  91 }