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

The following examples show how to use org.sonar.plugins.java.api.tree.IdentifierTree. 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: 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 #2
Source File: AbstractSmellCheck.java    From qualinsight-plugins-sonarqube-smell with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static final String extractMessage(final ExpressionTree expressionTree) {
    String message = "";
    switch (expressionTree.kind()) {
        case STRING_LITERAL:
            message = ((LiteralTree) expressionTree).value();
            break;
        case PLUS:
            final BinaryExpressionTree bet = (BinaryExpressionTree) expressionTree;
            message = extractMessage(bet.leftOperand()) + extractMessage(bet.rightOperand());
            break;
        case IDENTIFIER:
            final IdentifierTree it = (IdentifierTree) expressionTree;
            message = extractMessage(((VariableTree) (it.symbol()
                .declaration())).initializer());
            break;
        default:
            LOGGER.warn("Cannot extract message due to unexpected expressionTree kind: {}", expressionTree.kind());
            break;
    }
    return trimQuotes(message);
}
 
Example #3
Source File: FindRRDeclarationVisitor.java    From AEM-Rules-for-SonarQube with Apache License 2.0 6 votes vote down vote up
@Override
public void visitAssignmentExpression(AssignmentExpressionTree tree) {
    if (isExpressionAMethodInvocation(tree) && isVariableAnIdentifier(tree)) {
        final MethodInvocationTree methodInvocation = (MethodInvocationTree) tree.expression();
        final IdentifierTree identifier = (IdentifierTree) tree.variable();
        if (isManuallyCreatedResourceResolver(methodInvocation)) {
            resourceResolvers.add((VariableTree) identifier.symbol().declaration());
        } else if (isResourceResolver(methodInvocation) && methodInvocation.methodSelect().is(Kind.IDENTIFIER)) {
            MethodTree methodDeclaration = getMethodTree(methodInvocation);
            // variable 'methodDeclaration' can be null in case when method declaration isn't within the same file.
            if (methodDeclaration != null && isManuallyCreatedResourceResolver(methodDeclaration)) {
                resourceResolvers.add((VariableTree) getDeclaration(identifier));
            }
        }
    }
    super.visitAssignmentExpression(tree);
}
 
Example #4
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 #5
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 #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: 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 #8
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 #9
Source File: ResourceResolverShouldBeClosed.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
protected boolean checkIfResourceResolverIsClosed(MethodTree method, VariableTree injector) {
    Set<IdentifierTree> usagesOfRR = new HashSet<>(injector.symbol().usages());
    CheckClosedVisitor checkClosedVisitor = new CheckClosedVisitor(usagesOfRR);
    FinallyBlockVisitor finallyBlockVisitor = new FinallyBlockVisitor(checkClosedVisitor);
    method.accept(finallyBlockVisitor);
    return checkClosedVisitor.isClosed();
}
 
Example #10
Source File: FindSessionDeclarationVisitor.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitAssignmentExpression(AssignmentExpressionTree tree) {
    if (isMethodInvocation(tree) && getDeclaration((IdentifierTree) tree.variable()).equals(declarationOfReturnedVariable)) {
        MethodInvocationTree methodInvocation = (MethodInvocationTree) tree.expression();
        if (isManuallyCreatedSession(methodInvocation)) {
            this.createdManually = true;
        } else {
            CheckIfSessionCreatedManually sessionCreatedManually = new CheckIfSessionCreatedManually();
            getMethodTree(methodInvocation).accept(sessionCreatedManually);
            this.createdManually = sessionCreatedManually.isCreatedManually();
        }
    }
    super.visitAssignmentExpression(tree);
}
 
Example #11
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();
        declarationOfReturnedVariable = getDeclaration(identifier);
    }
    super.visitReturnStatement(tree);
}
 
Example #12
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 #13
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 #14
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 #15
Source File: SessionShouldBeLoggedOut.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
protected boolean checkIfLoggedOut(MethodTree method, VariableTree injector) {
    Set<IdentifierTree> usagesOfSession = new HashSet<>(injector.symbol().usages());
    CheckLoggedOutVisitor checkLoggedOutVisitor = new CheckLoggedOutVisitor(usagesOfSession);
    FinallyBlockVisitor finallyBlockVisitor = new FinallyBlockVisitor(checkLoggedOutVisitor);
    method.accept(finallyBlockVisitor);
    return checkLoggedOutVisitor.isLoggedOut();
}
 
Example #16
Source File: UnusedMethodParameterCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Override
public void visitIdentifier(IdentifierTree tree) {
	if (tree.symbol().isUnknown()) {
		unresolvedIdentifierNames.add(tree.name());
	}
	super.visitIdentifier(tree);
}
 
Example #17
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariable(VariableTree tree) {
    if (MODIFIABLE_VALUE_MAP_FULL_NAME.equals(tree.type().symbolType().fullyQualifiedName())) {
        isModified = false;
        List<IdentifierTree> usagesOfMVM = tree.symbol().usages();
        checkIfMapVariableIsModified(usagesOfMVM);
        if (!isModified) {
            context.reportIssue(this, tree, RULE_MESSAGE);
        }
        super.visitVariable(tree);
    }
}
 
Example #18
Source File: UnusedMethodParameterCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private void reportUnusedParameters(List<IdentifierTree> unused) {
	List<JavaFileScannerContext.Location> locations = new ArrayList<>();
	for (IdentifierTree identifier : unused) {
		locations.add(new JavaFileScannerContext.Location(
				"Remove this unused method parameter " + identifier.name() + "\".", identifier));
	}
	IdentifierTree firstUnused = unused.get(0);
	String msg;
	if (unused.size() > 1) {
		msg = "Remove these unused method parameters.";
	} else {
		msg = "Remove this unused method parameter \"" + firstUnused.name() + "\".";
	}
	reportIssue(firstUnused, msg, locations, null);
}
 
Example #19
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 #20
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();
        declarationOfReturnedVariable = getDeclaration(identifier);
    }
    super.visitReturnStatement(tree);
}
 
Example #21
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 #22
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 #23
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 #24
Source File: CommonUtil.java    From sonar-webdriver-plugin with MIT License 5 votes vote down vote up
private static IdentifierTree getIdentifier(MethodInvocationTree methodInvocationTree) {
    // methodSelect can only be Tree.Kind.IDENTIFIER or Tree.Kind.MEMBER_SELECT
    if (methodInvocationTree.methodSelect().is(Tree.Kind.IDENTIFIER)) {
        return (IdentifierTree) methodInvocationTree.methodSelect();
    }
    return ((MemberSelectExpressionTree) methodInvocationTree.methodSelect()).identifier();
}
 
Example #25
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()));
}
 
Example #26
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 #27
Source File: UnusedMethodParameterCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private void reportUnusedParameters(List<IdentifierTree> unused) {
	List<JavaFileScannerContext.Location> locations = new ArrayList<>();
	for (IdentifierTree identifier : unused) {
		locations.add(new JavaFileScannerContext.Location(
				"Remove this unused method parameter " + identifier.name() + "\".", identifier));
	}
	IdentifierTree firstUnused = unused.get(0);
	String msg;
	if (unused.size() > 1) {
		msg = "Remove these unused method parameters.";
	} else {
		msg = "Remove this unused method parameter \"" + firstUnused.name() + "\".";
	}
	reportIssue(firstUnused, msg, locations, null);
}
 
Example #28
Source File: UnusedMethodParameterCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Override
public void visitIdentifier(IdentifierTree tree) {
	if (tree.symbol().isUnknown()) {
		unresolvedIdentifierNames.add(tree.name());
	}
	super.visitIdentifier(tree);
}
 
Example #29
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()));
}
 
Example #30
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);
}