|
| 1 | +/* |
| 2 | + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs |
| 3 | + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) |
| 4 | + * |
| 5 | + * This program is free software: you can redistribute it and/or modify |
| 6 | + * it under the terms of the GNU General Public License as published by |
| 7 | + * the Free Software Foundation, either version 3 of the License, or |
| 8 | + * (at your option) any later version. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU General Public License |
| 16 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | + */ |
| 18 | +package org.greencodeinitiative.creedengo.java.checks; |
| 19 | + |
| 20 | +import org.sonar.check.Rule; |
| 21 | +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; |
| 22 | +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; |
| 23 | +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; |
| 24 | +import org.sonar.plugins.java.api.tree.MethodInvocationTree; |
| 25 | +import org.sonar.plugins.java.api.tree.Tree; |
| 26 | +import javax.annotation.Nonnull; |
| 27 | +import java.util.Collections; |
| 28 | +import java.util.List; |
| 29 | +import java.util.Objects; |
| 30 | + |
| 31 | +@Rule(key = "GCI94") |
| 32 | +public class UseOptionalOrElseGetVsOrElse extends IssuableSubscriptionVisitor { |
| 33 | + |
| 34 | + private static final String MESSAGE_RULE = "Use optional orElseGet instead of orElse."; |
| 35 | + private final UseOptionalOrElseGetVsOrElseVisitor visitorInFile = new UseOptionalOrElseGetVsOrElseVisitor(); |
| 36 | + |
| 37 | + @Override |
| 38 | + public List<Tree.Kind> nodesToVisit() { |
| 39 | + return Collections.singletonList(Tree.Kind.METHOD_INVOCATION); |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public void visitNode(@Nonnull Tree tree) { |
| 44 | + tree.accept(visitorInFile); |
| 45 | + } |
| 46 | + |
| 47 | + private class UseOptionalOrElseGetVsOrElseVisitor extends BaseTreeVisitor { |
| 48 | + @Override |
| 49 | + public void visitMethodInvocation(MethodInvocationTree tree) { |
| 50 | + if (tree.methodSelect().is(Tree.Kind.MEMBER_SELECT) && |
| 51 | + Objects.requireNonNull(tree.methodSelect().firstToken()).text().equals("Optional")) { |
| 52 | + MemberSelectExpressionTree memberSelect = (MemberSelectExpressionTree) tree.methodSelect(); |
| 53 | + if (memberSelect.identifier().name().equals("orElse")) { |
| 54 | + reportIssue(memberSelect, MESSAGE_RULE); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments