1 /* 2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 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 * A copy of the License is located at 7 * 8 * http://aws.amazon.com/apache2.0 9 * 10 * or in the "license" file accompanying this file. This file is distributed 11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 * express or implied. See the License for the specific language governing 13 * permissions and limitations under the License. 14 */ 15 16 package software.amazon.awssdk.buildtools.checkstyle; 17 18 import com.puppycrawl.tools.checkstyle.api.DetailAST; 19 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 20 import com.puppycrawl.tools.checkstyle.checks.naming.MethodNameCheck; 21 import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil; 22 23 /** 24 * Sdk Method Name check to check only public methods in the classes with {@code @SdkPublicApi} annotation. 25 */ 26 public final class SdkPublicMethodNameCheck extends MethodNameCheck { 27 28 /** 29 * {@link Override Override} annotation name. 30 */ 31 private static final String OVERRIDE = "Override"; 32 33 private static final String SDK_PUBLIC_API = "SdkPublicApi"; 34 35 @Override getDefaultTokens()36 public int[] getDefaultTokens() { 37 return getRequiredTokens(); 38 } 39 40 @Override getAcceptableTokens()41 public int[] getAcceptableTokens() { 42 return getRequiredTokens(); 43 } 44 45 @Override getRequiredTokens()46 public int[] getRequiredTokens() { 47 return new int[] { 48 TokenTypes.METHOD_DEF 49 }; 50 } 51 52 @Override visitToken(DetailAST ast)53 public void visitToken(DetailAST ast) { 54 // Get class classDef 55 DetailAST classDef = ast.getParent().getParent(); 56 57 try { 58 if (!AnnotationUtil.containsAnnotation(ast, OVERRIDE) 59 && AnnotationUtil.containsAnnotation(classDef, SDK_PUBLIC_API)) { 60 super.visitToken(ast); 61 } 62 } catch (NullPointerException ex) { 63 //If that method is in an anonymous class, it will throw NPE, ignoring those. 64 } 65 66 } 67 68 @Override mustCheckName(DetailAST ast)69 protected boolean mustCheckName(DetailAST ast) { 70 return ast.findFirstToken(TokenTypes.MODIFIERS) 71 .findFirstToken(TokenTypes.LITERAL_PUBLIC) != null; 72 } 73 } 74