org.sonar.plugins.java.api.tree.Tree Java Examples

The following examples show how to use org.sonar.plugins.java.api.tree.Tree. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ImplicitWaitCheck.java    From sonar-webdriver-plugin with MIT License 6 votes vote down vote up
@Override
public void visitMethodInvocation(MethodInvocationTree tree) {
    JavaFileScannerContext context = getContext();

    if (!tree.methodSelect().is(Tree.Kind.IDENTIFIER)) {
        MemberSelectExpressionTree memberSelectExpressionTree = ((MemberSelectExpressionTree) tree.methodSelect());

        String methodName = memberSelectExpressionTree.identifier().name();
        String fullyQualifiedNameOfExpression = memberSelectExpressionTree.expression().symbolType()
            .fullyQualifiedName();

        if (IMPLICITLY_WAIT_METHOD_NAME.equals(methodName) &&
            isPartOfWebDriverPackage(fullyQualifiedNameOfExpression)) {
            context.reportIssue(this, tree, "Avoid using implicit wait, use explicit wait instead");
        }
    }
}
 
Example #2
Source File: UnusedPrivateFieldCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(Tree tree) {
	if (!hasSemantic()) {
		return;
	}
	switch (tree.kind()) {
	case METHOD:
		checkIfNativeMethod((MethodTree) tree);
		break;
	case CLASS:
		classes.add((ClassTree) tree);
		break;
	case IMPORT:// VJ
		checkIfLombokClass((ImportTree) tree);
		break;
	case EXPRESSION_STATEMENT:
		collectAssignment(((ExpressionStatementTree) tree).expression());
		break;
	case IDENTIFIER:
		collectUnknownIdentifier((IdentifierTree) tree);
		break;
	default:
		throw new IllegalStateException("Unexpected subscribed tree.");
	}
}
 
Example #3
Source File: HardcodedIpCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitLiteral(LiteralTree tree) {
	if (tree.is(Tree.Kind.STRING_LITERAL)) {
		String value = LiteralUtils.trimQuotes(tree.value());
		IP.reset(value);
		if (IP.matches()) {
			String ip = IP.group("ip");

			// VJ:ADD 忽略127.0.0.1
			if ("127.0.0.1".equals(ip)) {
				return;
			}
			// VJ:END
			if (areAllBelow256(Splitter.on('.').split(ip))) {
				context.reportIssue(this, tree, "Make this IP \"" + ip + "\" address configurable.");
			}
		}
	}
}
 
Example #4
Source File: BadConstantNameCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(Tree tree) {
	ClassTree classTree = (ClassTree) tree;
	for (Tree member : classTree.members()) {
		if (member.is(Tree.Kind.VARIABLE) && hasSemantic()) {
			VariableTree variableTree = (VariableTree) member;
			Type symbolType = variableTree.type().symbolType();
			 if (isConstantType(symbolType) && (classTree.is(Tree.Kind.INTERFACE, Tree.Kind.ANNOTATION_TYPE) || isStaticFinal(variableTree))) {
		          checkName(variableTree);
		     }
		}
		// VJ Remove //
		// else if (member.is(Tree.Kind.ENUM_CONSTANT)) {
		// checkName((VariableTree) member);
		// }
	}
}
 
Example #5
Source File: UnusedMethodParameterCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(Tree tree) {
	if (!hasSemantic()) {
		return;
	}
	MethodTree methodTree = (MethodTree) tree;
	if (methodTree.block() == null || !isIncluded(methodTree)) {
		return;
	}
	List<IdentifierTree> unused = Lists.newArrayList();
	for (VariableTree var : methodTree.parameters()) {
		Symbol symbol = var.symbol();
		if (symbol.usages().isEmpty() && !symbol.metadata().isAnnotatedWith(AUTHORIZED_ANNOTATION)
				&& !isStrutsActionParameter(var)) {
			unused.add(var.simpleName());
		}
	}
	Set<String> unresolvedIdentifierNames = unresolvedIdentifierNames(methodTree.block());
	// kill the noise regarding unresolved identifiers, and remove the one with matching names from the list of
	// unused
	unused = unused.stream().filter(id -> !unresolvedIdentifierNames.contains(id.name()))
			.collect(Collectors.toList());
	if (!unused.isEmpty()) {
		reportUnusedParameters(unused);
	}
}
 
Example #6
Source File: UnusedPrivateFieldCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(Tree tree) {
	if (!hasSemantic()) {
		return;
	}
	switch (tree.kind()) {
	case METHOD:
		checkIfNativeMethod((MethodTree) tree);
		break;
	case CLASS:
		classes.add((ClassTree) tree);
		break;
	case IMPORT:// VJ
		checkIfLombokClass((ImportTree) tree);
		break;
	case EXPRESSION_STATEMENT:
		collectAssignment(((ExpressionStatementTree) tree).expression());
		break;
	case IDENTIFIER:
		collectUnknownIdentifier((IdentifierTree) tree);
		break;
	default:
		throw new IllegalStateException("Unexpected subscribed tree.");
	}
}
 
Example #7
Source File: SessionShouldBeLoggedOut.java    From AEM-Rules-for-SonarQube with Apache License 2.0 6 votes vote down vote up
protected boolean checkIfLongSession(MethodTree method) {
    List<AnnotationTree> annotations = method.modifiers().annotations();
    for (AnnotationTree annotationTree : annotations) {
        if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER)) {
            IdentifierTree idf = (IdentifierTree) annotationTree.annotationType();
            if (idf.name().equals(ACTIVATE)) {
                collectLongSessionOpened(method);
                return true;
            } else if (idf.name().equals(DEACTIVATE)) {
                collectLongSessionClosed(method);
                return true;
            }
        }
    }
    return false;
}
 
Example #8
Source File: HardcodedIpCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitLiteral(LiteralTree tree) {
	if (tree.is(Tree.Kind.STRING_LITERAL)) {
		String value = LiteralUtils.trimQuotes(tree.value());
		IP.reset(value);
		if (IP.matches()) {
			String ip = IP.group("ip");

			// VJ:ADD 忽略127.0.0.1
			if ("127.0.0.1".equals(ip)) {
				return;
			}
			// VJ:END
			if (areAllBelow256(Splitter.on('.').split(ip))) {
				context.reportIssue(this, tree, "Make this IP \"" + ip + "\" address configurable.");
			}
		}
	}
}
 
Example #9
Source File: ResourceResolverShouldBeClosed.java    From AEM-Rules-for-SonarQube with Apache License 2.0 6 votes vote down vote up
protected boolean checkIfLongResourceResolver(MethodTree method) {
    List<AnnotationTree> annotations = method.modifiers().annotations();
    for (AnnotationTree annotationTree : annotations) {
        if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER)) {
            IdentifierTree idf = (IdentifierTree) annotationTree.annotationType();
            if (idf.name().equals(ACTIVATE)) {
                collectLongResourceResolverOpened(method);
                return true;
            } else if (idf.name().equals(DEACTIVATE)) {
                collectLongResourceResolverClosed(method);
                return true;
            }
        }
    }
    return false;
}
 
Example #10
Source File: HardCodedSleepCheck.java    From sonar-webdriver-plugin with MIT License 6 votes vote down vote up
@Override
public void visitMethodInvocation(MethodInvocationTree tree) {
    JavaFileScannerContext context = getContext();

    if (!tree.methodSelect().is(Tree.Kind.IDENTIFIER)) {
        MemberSelectExpressionTree memberSelectExpressionTree = ((MemberSelectExpressionTree) tree.methodSelect());

        String methodName = memberSelectExpressionTree.identifier().name();
        String fullyQualifiedNameOfExpression = memberSelectExpressionTree.expression().symbolType()
            .fullyQualifiedName();

        if (SLEEP_METHOD_NAME.equals(methodName) &&
            fullyQualifiedNameOfExpression.equals(THREAD)) {
            context.reportIssue(this, tree, "Avoid using hard coded sleeps, use explicit wait instead");
        }
    }
}
 
Example #11
Source File: UnusedMethodParameterCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(Tree tree) {
	if (!hasSemantic()) {
		return;
	}
	MethodTree methodTree = (MethodTree) tree;
	if (methodTree.block() == null || !isIncluded(methodTree)) {
		return;
	}
	List<IdentifierTree> unused = Lists.newArrayList();
	for (VariableTree var : methodTree.parameters()) {
		Symbol symbol = var.symbol();
		if (symbol.usages().isEmpty() && !symbol.metadata().isAnnotatedWith(AUTHORIZED_ANNOTATION)
				&& !isStrutsActionParameter(var)) {
			unused.add(var.simpleName());
		}
	}
	Set<String> unresolvedIdentifierNames = unresolvedIdentifierNames(methodTree.block());
	// kill the noise regarding unresolved identifiers, and remove the one with matching names from the list of
	// unused
	unused = unused.stream().filter(id -> !unresolvedIdentifierNames.contains(id.name()))
			.collect(Collectors.toList());
	if (!unused.isEmpty()) {
		reportUnusedParameters(unused);
	}
}
 
Example #12
Source File: BadConstantNameCheck.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(Tree tree) {
	ClassTree classTree = (ClassTree) tree;
	for (Tree member : classTree.members()) {
		if (member.is(Tree.Kind.VARIABLE) && hasSemantic()) {
			VariableTree variableTree = (VariableTree) member;
			Type symbolType = variableTree.type().symbolType();
			 if (isConstantType(symbolType) && (classTree.is(Tree.Kind.INTERFACE, Tree.Kind.ANNOTATION_TYPE) || isStaticFinal(variableTree))) {
		          checkName(variableTree);
		     }
		}
		// VJ Remove //
		// else if (member.is(Tree.Kind.ENUM_CONSTANT)) {
		// checkName((VariableTree) member);
		// }
	}
}
 
Example #13
Source File: AdministrativeAccessUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void checkInvocation(Tree tree, MethodMatcher invocationMatcher) {
    if (tree.is(Kind.METHOD_INVOCATION)) {
        MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
        if (invocationMatcher.matches(methodInvocationTree)) {
            this.onMethodInvocationFound(methodInvocationTree);
        }
    }
}
 
Example #14
Source File: AbstractSmellCheck.java    From qualinsight-plugins-sonarqube-smell with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void handleSmellAnnotation(final AnnotationTree annotationTree) {
    String message = "";
    Integer minutes = 0;
    SmellType type = null;
    final Arguments arguments = annotationTree.arguments();
    for (final ExpressionTree expressionTree : arguments) {
        if (expressionTree.is(Tree.Kind.ASSIGNMENT)) {
            final AssignmentExpressionTree aet = (AssignmentExpressionTree) expressionTree;
            final String variable = ((IdentifierTree) aet.variable()).name();
            switch (variable) {
                case "minutes":
                    minutes += Integer.valueOf(((LiteralTree) aet.expression()).value());
                    LOGGER.debug("{} = {}", variable, minutes);
                    break;
                case "reason":
                    message = extractMessage(aet.expression());
                    LOGGER.debug("{} = {}", variable, message);
                    break;
                case "type":
                    type = SmellType.valueOf(((MemberSelectExpressionTree) aet.expression()).identifier()
                        .name());
                    break;
                default:
                    break;
            }
        }
    }
    if (smellType().equals(type)) {
        final Matcher matcher = PATTERN.matcher(message);
        if (matcher.matches()) {
            message = matcher.group(1);
        }
        reportIssue(annotationTree, message, new ArrayList<JavaFileScannerContext.Location>(), minutes);
    }
}
 
Example #15
Source File: UnusedPrivateFieldCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private static boolean isMethodIdentifier(IdentifierTree identifier) {
	Tree parent = identifier.parent();
	while (parent != null && !parent.is(Tree.Kind.METHOD_INVOCATION, Tree.Kind.METHOD_REFERENCE)) {
		parent = parent.parent();
	}
	if (parent == null) {
		return false;
	}
	if (parent.is(Tree.Kind.METHOD_INVOCATION)) {
		return identifier.equals(methodName((MethodInvocationTree) parent));
	} else {
		return identifier.equals(((MethodReferenceTree) parent).method());
	}
}
 
Example #16
Source File: UnusedPrivateFieldCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private void addAssignment(ExpressionTree tree) {
	ExpressionTree variable = ExpressionUtils.skipParentheses(tree);
	if (variable.is(Tree.Kind.IDENTIFIER)) {
		addAssignment((IdentifierTree) variable);
	} else if (variable.is(Tree.Kind.MEMBER_SELECT)) {
		addAssignment(((MemberSelectExpressionTree) variable).identifier());
	}
}
 
Example #17
Source File: AbstractSmellCheck.java    From qualinsight-plugins-sonarqube-smell with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void visitNode(final Tree tree) {
    final AnnotationTree annotationTree = (AnnotationTree) tree;
    final Type symbolType = annotationTree.annotationType()
        .symbolType();
    if (symbolType.is("com.qualinsight.plugins.sonarqube.smell.api.annotation.Smell")) {
        handleSmellAnnotation(annotationTree);
    }
}
 
Example #18
Source File: SynchronizedKeywordUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(Tree tree) {
    Kind i = tree.kind();
    if (i == Kind.METHOD) {
        SynchronizedMethodVisitor visitor = new SynchronizedMethodVisitor(this);
        tree.accept(visitor);
    } else if (i == Kind.SYNCHRONIZED_STATEMENT) {
        reportIssue(tree, MESSAGE);
    }
    super.visitNode(tree);
}
 
Example #19
Source File: SlingQueryImplicitStrategyCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void reportIssueIfStrategyNotUsed(Tree tree, String variableName) {
    if (findWithoutStrategyWasUsedOnSlingQuery()) {
        context.reportIssue(this, tree, RULE_MESSAGE);
        slingQueries.put(variableName, SlingQueryStates.ISSUE_RETURNED);
        ignoreIssues = true;
    }
}
 
Example #20
Source File: FindSessionDeclarationVisitor.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitReturnStatement(ReturnStatementTree tree) {
    if (tree.expression() != null && tree.expression().is(Kind.IDENTIFIER)) {
        IdentifierTree identifier = (IdentifierTree) tree.expression();
        Tree declaration = getDeclaration(identifier);
        if (sessions.contains(declaration)) {
            sessions.remove(declaration);
        }
    }
    super.visitReturnStatement(tree);
}
 
Example #21
Source File: MethodMatcher.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private static IdentifierTree getIdentifier(MethodInvocationTree methodInvocationTree) {
    // methodSelect can only be the Tree.Kind.IDENTIFIER or the Tree.Kind.MEMBER_SELECT
    if (methodInvocationTree.methodSelect().is(Tree.Kind.IDENTIFIER)) {
        return (IdentifierTree) methodInvocationTree.methodSelect();
    }
    return ((MemberSelectExpressionTree) methodInvocationTree.methodSelect()).identifier();
}
 
Example #22
Source File: ThreadSafeFieldCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void checkMember(Tree member) {
    boolean isVariableField = member.is(Kind.VARIABLE);
    if (isVariableField) {
        VariableTree variableField = (VariableTree) member;
        String name = variableField.type().symbolType().fullyQualifiedName();
        if (NON_THREAD_SAFE_TYPES.contains(name)) {
            context.reportIssue(this, member, String.format(RULE_MESSAGE, name));
        }
    }
}
 
Example #23
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void checkIfMapVariableIsModified(List<IdentifierTree> usagesOfMVM) {
    for (IdentifierTree modifiableValueMapUsageIdentifier : usagesOfMVM) {
        Tree usageOfMVM = modifiableValueMapUsageIdentifier.parent();
        if (usageOfMVM != null) {
            if (usageOfMVM.is(Tree.Kind.ARGUMENTS)) {
                visitMethodWithMVM(modifiableValueMapUsageIdentifier, usageOfMVM);
            } else if (usageOfMVM.is(Tree.Kind.MEMBER_SELECT) && isSomeoneCallingMutableMethodsOnMap((MemberSelectExpressionTree) usageOfMVM)) {
                isModified = true;
                break;
            }
        }
    }
}
 
Example #24
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void visitMethodWithMVM(IdentifierTree modifiableValueMapUsageIdentifier, Tree usageOfMVM) {
    int argumentNumber = ((Arguments) usageOfMVM).indexOf(modifiableValueMapUsageIdentifier);
    MethodInvocationTree methodInvocationWithMVM = (MethodInvocationTree) usageOfMVM.parent();
    if (methodInvocationWithMVM != null) {
        MethodTree methodWithMVM = (MethodTree) methodInvocationWithMVM.symbol().declaration();
        if (methodWithMVM != null && methodWithMVM.is(Tree.Kind.METHOD)) {
            MethodWithMVMVisitor methodWithMVMVisitor = new MethodWithMVMVisitor(this, argumentNumber);
            methodWithMVM.accept(methodWithMVMVisitor);
        }
    }
}
 
Example #25
Source File: DefaultInjectionStrategyAnnotationCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private boolean isOptionalDefaultValue(Arguments arguments) {
    boolean optionalIsDefaultValue = false;
    for (ExpressionTree argument : arguments) {
        if (argument.is(Tree.Kind.ASSIGNMENT)) {
            AssignmentExpressionTree assignment = (AssignmentExpressionTree) argument;
            if (isDefaultInjectionStrategyAssignment(assignment)) {
                optionalIsDefaultValue = isOptionalStrategyValue(assignment);
            }
        }
    }
    return optionalIsDefaultValue;
}
 
Example #26
Source File: PreferSlingServletAnnotation.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private boolean isAssignmentToName(ExpressionTree expression) {
    boolean result = false;
    if (expression.is(Tree.Kind.ASSIGNMENT)) {
        AssignmentExpressionTree assignment = (AssignmentExpressionTree) expression;
        result = NAME.equals(((IdentifierTree) assignment.variable()).name());
    }
    return result;
}
 
Example #27
Source File: ConstantsCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(Tree stringLiteral) {
    String literalValue = removeQuotes(((LiteralTree) stringLiteral).value());
    if (ConstantsChecker.isConstant(literalValue)) {
        String message = ConstantsChecker.getMessageForConstant(literalValue);
        reportIssue(stringLiteral, String.format("Use constant %s instead of hardcoded value.", message));
    }
    super.visitNode(stringLiteral);
}
 
Example #28
Source File: FindRRDeclarationVisitor.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitReturnStatement(ReturnStatementTree tree) {
    if (tree.expression() != null && tree.expression().is(Kind.IDENTIFIER)) {
        IdentifierTree identifier = (IdentifierTree) tree.expression();
        Tree declaration = identifier.symbol().declaration();
        if (resourceResolvers.contains(declaration)) {
            resourceResolvers.remove(declaration);
        }
    }
    super.visitReturnStatement(tree);
}
 
Example #29
Source File: CommonUtil.java    From sonar-webdriver-plugin with MIT License 5 votes vote down vote up
public static List<AnnotationTree> getAnnotationTrees(ClassTree tree) {
    List<AnnotationTree> annotationTrees = new ArrayList<>();
    List<Tree> members = tree.members();

    for (Tree member : members) {
        if (METHOD_KIND.equals(member.kind().toString())) {
            annotationTrees.addAll(((MethodTree) member).modifiers().annotations());
        }
    }

    return annotationTrees;
}
 
Example #30
Source File: UnusedPrivateFieldCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private static String fullQualifiedName(Tree tree) {
	if (tree.is(Tree.Kind.IDENTIFIER)) {
		return ((IdentifierTree) tree).name();
	} else if (tree.is(Tree.Kind.MEMBER_SELECT)) {
		MemberSelectExpressionTree m = (MemberSelectExpressionTree) tree;
		return fullQualifiedName(m.expression()) + "." + m.identifier().name();
	}
	throw new UnsupportedOperationException(String.format("Kind/Class '%s' not supported", tree.getClass()));
}