|
| 1 | +package fr.greencodeinitiative.java.checks; |
| 2 | + |
| 3 | +import org.sonar.check.Rule; |
| 4 | +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; |
| 5 | +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; |
| 6 | +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; |
| 7 | +import org.sonar.plugins.java.api.tree.MethodInvocationTree; |
| 8 | +import org.sonar.plugins.java.api.tree.Tree; |
| 9 | +import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; |
| 10 | + |
| 11 | +import javax.annotation.Nonnull; |
| 12 | +import java.util.Collections; |
| 13 | +import java.util.List; |
| 14 | +import java.util.Objects; |
| 15 | + |
| 16 | +@Rule(key = "XXX") |
| 17 | +@DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "XXX") |
| 18 | +public class UseOptionalOrElseGetVsOrElse extends IssuableSubscriptionVisitor { |
| 19 | + |
| 20 | + private static final String MESSAGE_RULE = "Use optional orElseGet instead of orElse."; |
| 21 | + private final UseOptionalOrElseGetVsOrElseVisitor visitorInFile = new UseOptionalOrElseGetVsOrElseVisitor(); |
| 22 | + |
| 23 | + @Override |
| 24 | + public List<Tree.Kind> nodesToVisit() { |
| 25 | + return Collections.singletonList(Tree.Kind.METHOD_INVOCATION); |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public void visitNode(@Nonnull Tree tree) { |
| 30 | + tree.accept(visitorInFile); |
| 31 | + } |
| 32 | + |
| 33 | + private class UseOptionalOrElseGetVsOrElseVisitor extends BaseTreeVisitor { |
| 34 | + @Override |
| 35 | + public void visitMethodInvocation(MethodInvocationTree tree) { |
| 36 | + if (tree.methodSelect().is(Tree.Kind.MEMBER_SELECT) && |
| 37 | + Objects.requireNonNull(tree.methodSelect().firstToken()).text().equals("Optional")) { |
| 38 | + MemberSelectExpressionTree memberSelect = (MemberSelectExpressionTree) tree.methodSelect(); |
| 39 | + if (memberSelect.identifier().name().equals("orElse")) { |
| 40 | + reportIssue(memberSelect, MESSAGE_RULE); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments