JavaSonarWayProfile implements BuiltInQualityProfilesDefinition { @SuppressWarnings("unchecked") @VisibleForTesting static Set<RuleKey> getSecurityRuleKeys(boolean sonarSecurityBefore78) { try { Class<?> javaRulesClass = Class.forName("com.sonar.plugins.security.api.JavaRules"); String ruleKeysMethod = sonarSecurityBefore78 ? "getRuleKeys" : "getSecurityRuleKeys"; Method getRuleKeysMethod = javaRulesClass.getMethod(ruleKeysMethod); Set<String> ruleKeys = (Set<String>) getRuleKeysMethod.invoke(null); String repositoryKey; if (sonarSecurityBefore78) { repositoryKey = CheckList.REPOSITORY_KEY; } else { Method getRepositoryKeyMethod = javaRulesClass.getMethod("getRepositoryKey"); repositoryKey = (String) getRepositoryKeyMethod.invoke(null); } return ruleKeys.stream().map(k -> RuleKey.of(repositoryKey, k)).collect(Collectors.toSet()); } catch (ClassNotFoundException e) { LOG.debug("com.sonar.plugins.security.api.JavaRules is not found, no security rules added to Sonar way java profile: " + e.getMessage()); } catch (NoSuchMethodException e) { LOG.debug("Method is not found, no security rules added to Sonar way java profile: " + e.getMessage()); } catch (IllegalAccessException e) { LOG.debug("[IllegalAccessException] no security rules added to Sonar way java profile: " + e.getMessage()); } catch (InvocationTargetException e) { LOG.debug("[InvocationTargetException] no security rules added to Sonar way java profile: " + e.getMessage()); } return new HashSet<>(); }  @Override void define(Context context);  }
@Test void should_contains_security_rules_if_present() { JavaRules.ruleKeys = new HashSet<>(); assertThat(JavaSonarWayProfile.getSecurityRuleKeys(true)).isEmpty(); JavaRules.ruleKeys = new HashSet<>(Arrays.asList("S3649")); assertThat(JavaSonarWayProfile.getSecurityRuleKeys(true)).containsOnly(RuleKey.of("java", "S3649")); assertThat(JavaSonarWayProfile.getSecurityRuleKeys(false)).containsOnly(RuleKey.of("security-repo-key", "S3649")); }