From 23777618c08bb8015514a63033fecfffd74b75ef Mon Sep 17 00:00:00 2001 From: Michael Gumowski Date: Tue, 21 Mar 2017 15:33:22 +0100 Subject: [PATCH] SONARJAVA-176 Skip annotations parameters (#1326) --- .../sonar/java/checks/HardcodedURICheck.java | 13 ++++++++++++- .../test/files/checks/HardcodedURICheck.java | 17 +++++++++++++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/java-checks/src/main/java/org/sonar/java/checks/HardcodedURICheck.java b/java-checks/src/main/java/org/sonar/java/checks/HardcodedURICheck.java index 77af6b22f65..6f4b953adb1 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/HardcodedURICheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/HardcodedURICheck.java @@ -96,11 +96,22 @@ private void checkVariable(VariableTree tree) { } private void checkAssignment(AssignmentExpressionTree tree) { - if (isFileNameVariable(getVariableIdentifier(tree))) { + if (isFileNameVariable(getVariableIdentifier(tree)) && !isPartOfAnnotation(tree)) { checkExpression(tree.expression()); } } + private static boolean isPartOfAnnotation(AssignmentExpressionTree tree) { + Tree parent = tree.parent(); + while (parent != null) { + if (parent.is(Tree.Kind.ANNOTATION)) { + return true; + } + parent = parent.parent(); + } + return false; + } + private static boolean isFileNameVariable(@Nullable IdentifierTree variable) { return variable != null && VARIABLE_NAME_PATTERN.matcher(variable.name()).find(); } diff --git a/java-checks/src/test/files/checks/HardcodedURICheck.java b/java-checks/src/test/files/checks/HardcodedURICheck.java index 6495a82528c..49deec46f6b 100644 --- a/java-checks/src/test/files/checks/HardcodedURICheck.java +++ b/java-checks/src/test/files/checks/HardcodedURICheck.java @@ -3,10 +3,23 @@ import java.net.URISyntaxException; class A { + + public static @interface MyAnnotation { + String stuff() default "none"; + String path() default "/"; + } + String fileName = "//my-network-drive/folder/file.txt"; // Noncompliant String[] stuffs = new String[1]; - void foo(String s) throws URISyntaxException { + @MyAnnotation(stuff = "yolo", path = "/{var}/bulu/stuff") // Compliant - annotations are ignored + void bar(String var) { } + + @MyAnnotation(stuff = "/{var}/bulu/stuff") // Compliant - not a path assignmnet + void qix(String var) { } + + @MyAnnotation(path = "/{var}/bulu/stuff") // Compliant - annotations are ignored + void foo(String s, String var) throws URISyntaxException { new Object(); new URI(s); // Compliant @@ -32,7 +45,7 @@ void foo(String s) throws URISyntaxException { fileNAME = s + "\\\\" + s; // Noncompliant {{Remove this hard-coded path-delimiter.}}t fileNAME = s + "hello" + s; // Compliant fileNAME = "c:\\blah\\blah\\blah.txt"; // Noncompliant - + int fIleNaMe = 14 - 2; String v1 = s + "//" + s; // Compliant - not a file name