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

The following examples show how to use org.sonar.plugins.java.api.tree.VariableTree. 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: 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 #2
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 #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: 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: 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 #7
Source File: ResourceResolverTryWithResourcesCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitTryStatement(TryStatementTree tree) {
  insideTryStatement = true;
  tree.resourceList().stream()
          // We're iterating over a resource specification in a try-with-resource block
          // so we expect variable trees
          .filter(resource -> resource instanceof VariableTree)
          .map(VariableTree.class::cast)
          .map(resource -> resource.simpleName().name())
          .forEach(resourceResolversInTryWithResources::add);

  super.visitTryStatement(tree);
  resourceResolversInTryWithResources.clear();
  insideTryStatement = false;
}
 
Example #8
Source File: ResourceResolverTryWithResourcesCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariable(VariableTree tree) {
  if (isResourceResolverUsedProperly(tree)) {
    context.reportIssue(this, tree, RULE_MESSAGE);
  }
  super.visitVariable(tree);
}
 
Example #9
Source File: FindRRDeclarationVisitor.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private boolean isAMethodInvocation(VariableTree tree) {
    boolean returnVal = false;
    if (tree.initializer() != null) {
        returnVal = tree.initializer().is(Kind.METHOD_INVOCATION);
    }
    return returnVal;
}
 
Example #10
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariable(VariableTree tree) {
    if (isResourceInitialized(tree) && isGetContentResourceUsedOnPage(tree)) {
        contentResources.put(tree.simpleName().name(), false);
    }
    super.visitVariable(tree);
}
 
Example #11
Source File: FindRRDeclarationVisitor.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariable(VariableTree tree) {
    if (isAMethodInvocation(tree) && variableIsEqualToReturnedVariableIn(tree)) {
        MethodInvocationTree methodInvocation = (MethodInvocationTree) tree.initializer();
        if (isManuallyCreatedResourceResolver(methodInvocation)) {
            this.createdManually = true;
        } else {
            CheckIfRRCreatedManually rrCreatedManually = new CheckIfRRCreatedManually();
            getMethodTree(methodInvocation).accept(rrCreatedManually);
            this.createdManually = rrCreatedManually.isCreatedManually();
        }
    }
    super.visitVariable(tree);
}
 
Example #12
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private boolean isGetContentResourceUsedOnPage(VariableTree tree) {
    return tree.initializer() instanceof MethodInvocationTree &&
        !((MethodInvocationTree) tree.initializer()).symbol().isUnknown() &&
        isPage(((MethodInvocationTree) tree.initializer()).symbol().owner().type()
            .fullyQualifiedName()) &&
        GET_CONTENT_RESOURCE_METHOD.equals(((MethodInvocationTree) tree.initializer()).symbol().name());
}
 
Example #13
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 #14
Source File: ResourceResolverShouldBeClosed.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void collectLongResourceResolverClosed(MethodTree method) {
    if (longResourceResolvers != null) {
        for (VariableTree longResourceResolver : longResourceResolvers) {
            if (!checkIfResourceResolverIsClosed(method, longResourceResolver)) {
                context.reportIssue(this, longResourceResolver, RULE_MESSAGE);
            }
        }
    }
}
 
Example #15
Source File: ResourceResolverShouldBeClosed.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(MethodTree method) {
    if (!checkIfLongResourceResolver(method)) {
        Collection<VariableTree> resolvers = findResolversInMethod(method);
        for (VariableTree injector : resolvers) {
            if (!checkIfResourceResolverIsClosed(method, injector)) {
                context.reportIssue(this, injector, RULE_MESSAGE);
            }
        }
    }
    super.visitMethod(method);
}
 
Example #16
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 #17
Source File: SessionShouldBeLoggedOut.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void collectLongSessionClosed(MethodTree method) {
    if (longSessions != null) {
        for (VariableTree longSession : longSessions) {
            if (!checkIfLoggedOut(method, longSession)) {
                context.reportIssue(this, longSession, RULE_MESSAGE);
            }
        }
    }
}
 
Example #18
Source File: SessionShouldBeLoggedOut.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(MethodTree method) {
    if (!checkIfLongSession(method)) {
        Collection<VariableTree> sessions = findSessionsInMethod(method);
        for (VariableTree session : sessions) {
            if (!checkIfLoggedOut(method, session)) {
                context.reportIssue(this, session, RULE_MESSAGE);
            }
        }
    }
    super.visitMethod(method);
}
 
Example #19
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(MethodTree tree) {
    List<VariableTree> parameters = tree.parameters();
    if (argumentIndex >= 0 && argumentIndex <= (parameters.size() - 1)) {
        VariableTree variableTree = parameters.get(argumentIndex);
        scanner.checkIfMapVariableIsModified(variableTree.symbol().usages());
    }
    super.visitMethod(tree);
}
 
Example #20
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 #21
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 #22
Source File: FindVariableDeclarationVisitor.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariable(VariableTree variable) {
    if (isInjector(variable)) {
        variables.add(variable);
    }
    super.visitVariable(variable);
}
 
Example #23
Source File: BadConstantNameCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private void checkName(VariableTree variableTree) {
	String name = variableTree.simpleName().name();
	if (!SerializableContract.SERIAL_VERSION_UID_FIELD.equals(name)
			&& !pattern.matcher(name).matches()) {
		//VJ 报错信息加上变量名
		reportIssue(variableTree.simpleName(),
				"Rename this constant name '" + name + "' to match the regular expression '" + format + "'.");
	}
}
 
Example #24
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)) {
        MethodInvocationTree methodInvocation = (MethodInvocationTree) tree.expression();
        if (isManuallyCreatedSession(methodInvocation)) {
            IdentifierTree variable = (IdentifierTree) tree.variable();
            sessions.add((VariableTree) getDeclaration(variable));
        } else if (isSession(methodInvocation) && methodInvocation.methodSelect().is(Kind.IDENTIFIER)) {
            findSessionsCreatedInMethods(tree, methodInvocation);
        }
    }
    super.visitAssignmentExpression(tree);
}
 
Example #25
Source File: BadConstantNameCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private static boolean isStaticFinal(VariableTree variableTree) {
	boolean isStatic = false;
	boolean isFinal = false;
	for (ModifierKeywordTree modifierKeywordTree : variableTree.modifiers().modifiers()) {
		Modifier modifier = modifierKeywordTree.modifier();
		if (modifier == Modifier.STATIC) {
			isStatic = true;
		}
		if (modifier == Modifier.FINAL) {
			isFinal = true;
		}
	}
	return isStatic && isFinal;
}
 
Example #26
Source File: SlingQueryImplicitStrategyCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariable(VariableTree tree) {
    if (isSlingQuery(tree)) {
        slingQueries.put(tree.simpleName().name(), SlingQueryStates.NOT_USED);
        currentSlingQueryVariableName = tree.simpleName().name();
    }
    super.visitVariable(tree);
    // This part of code will be executed directly after initialization
    reportIssueIfStrategyNotUsed(tree, currentSlingQueryVariableName);
}
 
Example #27
Source File: BadConstantNameCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private void checkName(VariableTree variableTree) {
	String name = variableTree.simpleName().name();
	if (!SerializableContract.SERIAL_VERSION_UID_FIELD.equals(name)
			&& !pattern.matcher(name).matches()) {
		//VJ 报错信息加上变量名
		reportIssue(variableTree.simpleName(),
				"Rename this constant name '" + name + "' to match the regular expression '" + format + "'.");
	}
}
 
Example #28
Source File: UnusedPrivateFieldCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
public void checkIfUnused(VariableTree tree) {
	if (hasNoAnnotation(tree)) {
		Symbol symbol = tree.symbol();
		String name = symbol.name();
		if (symbol.isPrivate() && onlyUsedInVariableAssignment(symbol) && !"serialVersionUID".equals(name)
				&& !unknownIdentifiers.contains(name)) {
			reportIssue(tree.simpleName(), "Remove this unused \"" + name + "\" private field.");
		}
	}
}
 
Example #29
Source File: UnusedPrivateFieldCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
public void checkIfUnused(VariableTree tree) {
	if (hasNoAnnotation(tree)) {
		Symbol symbol = tree.symbol();
		String name = symbol.name();
		if (symbol.isPrivate() && onlyUsedInVariableAssignment(symbol) && !"serialVersionUID".equals(name)
				&& !unknownIdentifiers.contains(name)) {
			reportIssue(tree.simpleName(), "Remove this unused \"" + name + "\" private field.");
		}
	}
}
 
Example #30
Source File: BadConstantNameCheck.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private static boolean isStaticFinal(VariableTree variableTree) {
	boolean isStatic = false;
	boolean isFinal = false;
	for (ModifierKeywordTree modifierKeywordTree : variableTree.modifiers().modifiers()) {
		Modifier modifier = modifierKeywordTree.modifier();
		if (modifier == Modifier.STATIC) {
			isStatic = true;
		}
		if (modifier == Modifier.FINAL) {
			isFinal = true;
		}
	}
	return isStatic && isFinal;
}