Java Code Examples for com.github.javaparser.ast.expr.AnnotationExpr

The following examples show how to use com.github.javaparser.ast.expr.AnnotationExpr. These examples are extracted from open source projects. 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
@Override
public void visit(final ClassOrInterfaceType n, final Void arg) {
    printJavaComment(n.getComment(), arg);

    if (n.getScope().isPresent()) {
        n.getScope().get().accept(this, arg);
        printer.print(".");
    }
    for (AnnotationExpr ae : n.getAnnotations()) {
        ae.accept(this, arg);
        printer.print(" ");
    }

    n.getName().accept(this, arg);

    if (n.isUsingDiamondOperator()) {
        printer.print("<>");
    } else {
        printTypeArgs(n, arg);
    }
}
 
Example 2
@Override
public void visit(final TypeParameter n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    for (AnnotationExpr ann : n.getAnnotations()) {
        ann.accept(this, arg);
        printer.print(" ");
    }
    n.getName().accept(this, arg);
    if (!isNullOrEmpty(n.getTypeBound())) {
        printer.print(" extends ");
        for (final Iterator<ClassOrInterfaceType> i = n.getTypeBound().iterator(); i.hasNext(); ) {
            final ClassOrInterfaceType c = i.next();
            c.accept(this, arg);
            if (i.hasNext()) {
                printer.print(" & ");
            }
        }
    }
}
 
Example 3
Source Project: apigcc   Source File: AnnotationHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 获取注解的属性
 * @param expr
 * @param keys 从前往后找,返回第一个存在的属性
 * @return
 */
public static Optional<Expression> attr(AnnotationExpr expr, String ... keys) {
    for (String key : keys) {
        if (Objects.equals("value", key) && expr.isSingleMemberAnnotationExpr()) {
            return Optional.of(expr.asSingleMemberAnnotationExpr().getMemberValue());
        }
        if (expr.isNormalAnnotationExpr()) {
            for (MemberValuePair pair : expr.asNormalAnnotationExpr().getPairs()) {
                if (Objects.equals(key, pair.getNameAsString())) {
                    return Optional.of(pair.getValue());
                }
            }
        }
    }
    return Optional.empty();
}
 
Example 4
@Override
public void visit(VariableDeclarationExpr n, Void arg) {
    super.visit(n, arg);
    //Note: the null check limits the identification of variable types declared within the method body.
    // Removing it will check for variables declared at the class level.
    //TODO: to null check or not to null check???
    if (currentMethod != null) {
        for (String variableType : mysteryTypes) {
            //check if the type variable encountered is part of the mystery type collection
            if ((n.getVariable(0).getType().asString().equals(variableType))) {
                //check if the variable has been mocked
                for (AnnotationExpr annotation : n.getAnnotations()) {
                    if (annotation.getNameAsString().equals("Mock") || annotation.getNameAsString().equals("Spy"))
                        break;
                }
                // variable is not mocked, hence it's a smell
                mysteryCount++;
            }
        }
    }
}
 
Example 5
Source Project: jql   Source File: AnnotatedWithCalculator.java    License: MIT License 6 votes vote down vote up
public void calculate(ClassOrInterfaceDeclaration classOrInterfaceDeclaration, CompilationUnit compilationUnit) {
    List<AnnotationExpr> annotations = classOrInterfaceDeclaration.getAnnotations();
    for (AnnotationExpr annotation : annotations) {
        String annotationName = annotation.getNameAsString();
        String annotationPackageName = annotation
                .findCompilationUnit()
                .flatMap(CompilationUnit::getPackageDeclaration)
                .flatMap(pkg -> Optional.of(pkg.getNameAsString())).orElse("???");

        if (typeDao.exist(annotationName, annotationPackageName)) { // JDK annotations are not indexed
            int annotationId = typeDao.getId(annotationName, annotationPackageName);
            int typeId = typeDao.getId(classOrInterfaceDeclaration.getNameAsString(), compilationUnit.getPackageDeclaration().get().getNameAsString());
            annotatedWithDao.save(new AnnotatedWith(typeId, annotationId));
        }
    }
}
 
Example 6
Source Project: flow   Source File: OpenApiObjectGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void parseClass(ClassOrInterfaceDeclaration classDeclaration,
        CompilationUnit compilationUnit) {
    Optional<AnnotationExpr> endpointAnnotation = classDeclaration
            .getAnnotationByClass(Endpoint.class);
    compilationUnit.getStorage().ifPresent(storage -> {
        String className = classDeclaration.getFullyQualifiedName()
                .orElse(classDeclaration.getNameAsString());
        qualifiedNameToPath.put(className, storage.getPath().toString());
    });
    if (!endpointAnnotation.isPresent()) {
        nonEndpointMap.put(classDeclaration.resolve().getQualifiedName(),
                classDeclaration);
    } else {
        Optional<Javadoc> javadoc = classDeclaration.getJavadoc();
        if (javadoc.isPresent()) {
            endpointsJavadoc.put(classDeclaration,
                    javadoc.get().getDescription().toText());
        } else {
            endpointsJavadoc.put(classDeclaration, "");
        }
        pathItems.putAll(createPathItems(
                getEndpointName(classDeclaration, endpointAnnotation.get()),
                classDeclaration));
    }
}
 
Example 7
Source Project: jeddict   Source File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static Optional<String> getStringAttribute(AnnotationExpr annotationExpr, String attributeName) {
    Optional<Expression> expressionOpt = getAttribute(annotationExpr, attributeName);
    if (expressionOpt.isPresent()) {
        Expression expression = expressionOpt.get();
        if (expression.isStringLiteralExpr()) {
            return expression.toStringLiteralExpr()
                    .map(StringLiteralExpr::getValue);
        } else if (expression.isNameExpr()) {
            return expression.toNameExpr()
                    .map(NameExpr::getNameAsString);
        } else if (expression.isIntegerLiteralExpr()) {
            return expression.toIntegerLiteralExpr()
                    .map(IntegerLiteralExpr::asInt)
                    .map(String::valueOf);
        } else if (expression.isFieldAccessExpr() || expression.isBinaryExpr()) {
            return expressionOpt
                    .map(Expression::toString);
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return Optional.empty();
}
 
Example 8
Source Project: jeddict   Source File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static List<String> getStringAttributes(AnnotationExpr annotationExpr, String attributeName) {
    List<String> values = new ArrayList<>();
    Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName);
    if (expOptional.isPresent()) {
        Expression expression = expOptional.get();
        if (expression.isStringLiteralExpr()) {
            values.add(expression.asStringLiteralExpr().getValue());
        } else if (expression.isArrayInitializerExpr()) {
            List<Node> nodes = expression.asArrayInitializerExpr().getChildNodes();
            for (Node node : nodes) {
                if (node instanceof StringLiteralExpr) {
                    values.add(((StringLiteralExpr) node).getValue());
                } else {
                    values.add(node.toString());
                }
            }
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return values;
}
 
Example 9
Source Project: jeddict   Source File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static Optional<Long> getLongAttribute(AnnotationExpr annotationExpr, String attributeName) {
    Optional<Expression> expressionOpt = getAttribute(annotationExpr, attributeName);
    if (expressionOpt.isPresent()) {
        Expression expression = expressionOpt.get();
        if (expression.isLongLiteralExpr()) {
            return expressionOpt.flatMap(exp -> exp.toLongLiteralExpr())
                    .map(exp -> exp.asLong());
        } else if (expression.isIntegerLiteralExpr()) {
            return expressionOpt.flatMap(exp -> exp.toIntegerLiteralExpr())
                    .map(exp -> exp.asInt())
                    .map(Long::valueOf);
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return Optional.empty();
}
 
Example 10
Source Project: jeddict   Source File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static List<String> getClassNameAttributes(AnnotationExpr annotationExpr, String attributeName) {
    List<String> values = new ArrayList<>();
    Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName);
    if (expOptional.isPresent()) {
        Expression expression = expOptional.get();
        if (expression.isClassExpr()) {
            values.add(expression.asClassExpr().getTypeAsString());
        } else if (expression.isArrayInitializerExpr()) {
            for (Node node : expression.asArrayInitializerExpr().getChildNodes()) {
                if (node instanceof ClassExpr) {
                    values.add(((ClassExpr) node).getTypeAsString());
                } else {
                    throw new UnsupportedOperationException();
                }
            }
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return values;
}
 
Example 11
Source Project: gauge-java   Source File: RegistryMethodVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(MethodDeclaration methodDeclaration, Object arg) {
    List<AnnotationExpr> annotations = methodDeclaration.getAnnotations();
    if (annotations.isEmpty()) {
        return;
    }

    for (AnnotationExpr annotationExpr : annotations) {
        if (!(annotationExpr instanceof SingleMemberAnnotationExpr)) {
            continue;
        }
        SingleMemberAnnotationExpr annotation = (SingleMemberAnnotationExpr) annotationExpr;
        if (annotation.getMemberValue() instanceof ArrayInitializerExpr) {
            ArrayInitializerExpr memberValue = (ArrayInitializerExpr) annotation.getMemberValue();
            for (Expression expression : memberValue.getValues()) {
                addStepToRegistry(expression, methodDeclaration, annotation);
            }
        } else {
            addStepToRegistry(annotation.getMemberValue(), methodDeclaration, annotation);
        }
    }
}
 
Example 12
public static AnnotatedClassPostProcessor scan(Stream<Path> files) {
    List<CompilationUnit> annotatedUnits = files
            .peek(System.out::println)
            .map(p -> {
                try {
                    return StaticJavaParser.parse(p);
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }).filter(cu -> cu.findFirst(AnnotationExpr.class, ann -> ann.getNameAsString().endsWith("When")).isPresent())
            .collect(Collectors.toList());

    return new AnnotatedClassPostProcessor(annotatedUnits);
}
 
Example 13
private String formatPattern(Parameter el) {
    Optional<AnnotationExpr> w = el.getAnnotationByName("When");
    AnnotationExpr when = w.orElseThrow(() -> new IllegalArgumentException("No When annotation"));
    return String.format(
            "  %s : %s\n",
            el.getNameAsString(),
            when.asSingleMemberAnnotationExpr().getMemberValue().asStringLiteralExpr().getValue());
}
 
Example 14
private void printMemberAnnotations(final NodeList<AnnotationExpr> annotations, final Void arg) {
    if (annotations.isEmpty()) {
        return;
    }
    for (final AnnotationExpr a : annotations) {
        a.accept(this, arg);
        printer.println();
    }
}
 
Example 15
private void printAnnotations(final NodeList<AnnotationExpr> annotations, boolean prefixWithASpace,
                              final Void arg) {
    if (annotations.isEmpty()) {
        return;
    }
    if (prefixWithASpace) {
        printer.print(" ");
    }
    for (AnnotationExpr annotation : annotations) {
        annotation.accept(this, arg);
        printer.print(" ");
    }
}
 
Example 16
Source Project: apigcc   Source File: RequestMappingHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 解析HTTP Method
 * @param n
 * @return
 */
public static Method pickMethod(MethodDeclaration n){
    if(n.isAnnotationPresent(ANNOTATION_GET_MAPPING)){
        return Method.GET;
    }
    if(n.isAnnotationPresent(ANNOTATION_POST_MAPPING)){
        return Method.POST;
    }
    if(n.isAnnotationPresent(ANNOTATION_PUT_MAPPING)){
        return Method.PUT;
    }
    if(n.isAnnotationPresent(ANNOTATION_PATCH_MAPPING)){
        return Method.PATCH;
    }
    if(n.isAnnotationPresent(ANNOTATION_DELETE_MAPPING)){
        return Method.DELETE;
    }
    if(n.isAnnotationPresent(ANNOTATION_REQUEST_MAPPING)){
        AnnotationExpr annotationExpr = n.getAnnotationByName(ANNOTATION_REQUEST_MAPPING).get();
        Optional<Expression> expressionOptional = AnnotationHelper.attr(annotationExpr, "method");
        if (expressionOptional.isPresent()) {
            Expression expression = expressionOptional.get();
            if(expression.isArrayInitializerExpr()){
                NodeList<Expression> values = expression.asArrayInitializerExpr().getValues();
                if(values!=null&&values.size()>0){
                    return Method.valueOf(values.get(0).toString().replaceAll("RequestMethod.",""));
                }
            }
            return Method.of(expression.toString().replaceAll("RequestMethod.",""));
        }
    }
    return Method.GET;
}
 
Example 17
Source Project: apigcc   Source File: RequestMappingHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取uri数据,有多个时,暂时只取第一个
 * @param nodeList
 * @return
 */
public static String pickUri(NodeList<AnnotationExpr> nodeList){
    for (AnnotationExpr annotationExpr : nodeList) {
        if(ANNOTATION_REQUEST_MAPPINGS.contains(annotationExpr.getNameAsString())){
            Optional<Expression> expressionOptional = AnnotationHelper.attr(annotationExpr, "value","path");
            if (expressionOptional.isPresent()) {
                Expression expression = expressionOptional.get();
                return ExpressionHelper.getStringValue(expression);
            }
        }
    }
    return "";
}
 
Example 18
Source Project: apigcc   Source File: RequestMappingHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取headers
 * @param nodeList
 * @return
 */
public static List<String> pickHeaders(NodeList<AnnotationExpr> nodeList){
    for (AnnotationExpr annotationExpr : nodeList) {
        if(ANNOTATION_REQUEST_MAPPINGS.contains(annotationExpr.getNameAsString())){
            Optional<Expression> expressionOptional = AnnotationHelper.attr(annotationExpr, "headers");
            if (expressionOptional.isPresent()) {
                Expression expression = expressionOptional.get();
                return ExpressionHelper.getStringValues(expression);
            }
        }
    }
    return Lists.newArrayList();
}
 
Example 19
Source Project: apigcc   Source File: RequestMappingHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取headers
 * @param nodeList
 * @return
 */
public static List<String> pickConsumers(NodeList<AnnotationExpr> nodeList){
    for (AnnotationExpr annotationExpr : nodeList) {
        if(ANNOTATION_REQUEST_MAPPINGS.contains(annotationExpr.getNameAsString())){
            Optional<Expression> expressionOptional = AnnotationHelper.attr(annotationExpr, "consumes");
            if (expressionOptional.isPresent()) {
                Expression expression = expressionOptional.get();
                return ExpressionHelper.getStringValues(expression);
            }
        }
    }
    return Lists.newArrayList();
}
 
Example 20
Source Project: apigcc   Source File: RequestMappingHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取headers
 * @param nodeList
 * @return
 */
public static List<String> pickProduces(NodeList<AnnotationExpr> nodeList){
    for (AnnotationExpr annotationExpr : nodeList) {
        if(ANNOTATION_REQUEST_MAPPINGS.contains(annotationExpr.getNameAsString())){
            Optional<Expression> expressionOptional = AnnotationHelper.attr(annotationExpr, "produces");
            if (expressionOptional.isPresent()) {
                Expression expression = expressionOptional.get();
                return ExpressionHelper.getStringValues(expression);
            }
        }
    }
    return Lists.newArrayList();
}
 
Example 21
Source Project: apigcc   Source File: ValidationHelper.java    License: MIT License 5 votes vote down vote up
public static List<String> getValidations(ResolvedFieldDeclaration declaredField) {
    List<String> result = new ArrayList<>();
    if (declaredField instanceof JavaParserFieldDeclaration) {
        FieldDeclaration fieldDeclaration = ((JavaParserFieldDeclaration) declaredField).getWrappedNode();
        for (String value : values) {
            Optional<AnnotationExpr> optional = fieldDeclaration.getAnnotationByName(value);
            if (optional.isPresent()) {
                result.add(value);
            }
        }
    }
    return result;
}
 
Example 22
Source Project: apigcc   Source File: AnnotationHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取注解的属性String类型的值
 * @param node
 * @param annotation
 * @param keys
 * @return
 */
@SuppressWarnings("unchecked")
public static Optional<String> string(NodeWithAnnotations node, String annotation, String ... keys) {
    Optional<AnnotationExpr> optional = node.getAnnotationByName(annotation);
    if (optional.isPresent()) {
        Optional<Expression> expr = AnnotationHelper.attr(optional.get(), keys);
        if (expr.isPresent()) {
            return Optional.of(ExpressionHelper.getStringValue(expr.get()));
        }
    }
    return Optional.empty();
}
 
Example 23
Source Project: Refactoring-Bot   Source File: AddOverrideAnnotation.java    License: MIT License 5 votes vote down vote up
/**
 * @param declaration
 * @return true if given declaration already has an @Override annotation, false
 *         otherwise
 */
private boolean isOverrideAnnotationExisting(MethodDeclaration declaration) {
	List<AnnotationExpr> annotations = declaration.getAnnotations();
	for (AnnotationExpr annotation : annotations) {
		if (annotation.getNameAsString().equals(OVERRIDE_ANNOTATION_NAME)) {
			return true;
		}
	}

	return false;
}
 
Example 24
Source Project: Briefness   Source File: ClassParser.java    License: Apache License 2.0 5 votes vote down vote up
private static String checkBundle(NodeList<AnnotationExpr> annotationExprs) {
    for (AnnotationExpr annotationExpr : annotationExprs) {
        if (annotationExpr.toString().contains(BindField))
            return annotationExpr.toString().replace(BindField, "").replace("(", "").replace(")", "").replace("@", "");
    }
    return null;
}
 
Example 25
Source Project: Briefness   Source File: ClassParser.java    License: Apache License 2.0 5 votes vote down vote up
private static String[] checkAnnatation(NodeList<AnnotationExpr> annotationExprs) {
    for (AnnotationExpr annotationExpr : annotationExprs) {
        if (annotationExpr.toString().contains(BindLayout) || annotationExpr.toString().contains(BindView) || annotationExpr.toString().contains(BindClick))
            return subString(annotationExpr.toString().replaceAll("R2", "R")).split(",");
    }
    return null;
}
 
Example 26
Source Project: Briefness   Source File: ClassParser.java    License: Apache License 2.0 5 votes vote down vote up
private static Immersive checkImmersive(NodeList<AnnotationExpr> annotationExprs) {
    for (AnnotationExpr annotationExpr : annotationExprs) {
        if (annotationExpr.getNameAsString().equals(Immersive)) {
            String annotation = annotationExpr.toString();
            if (!annotation.contains("(")) return new Immersive();
            String content = annotation.substring(annotation.indexOf("(") + 1, annotation.indexOf(")")).replaceAll(" ", "");
            Immersive im = new Immersive();
            if (content.length() > 4) {
                String values[] = content.split(",");
                for (String value : values) {
                    String[] kv = value.split("=");
                    if (kv[0].equals(Immersive_statusColor)) {
                        im.setStatusColor(kv[1]);
                    } else if (kv[0].equals(Immersive_navigationColor)) {
                        im.setNavigationColor(kv[1]);
                    } else if (kv[0].equals(Immersive_statusEmbed)) {
                        im.setStatusEmbed(kv[1]);
                    } else if (kv[0].equals(Immersive_navigationEmbed)) {
                        im.setNavigationEmbed(kv[1]);
                    }
                }
            }
            return im;
        }
    }
    return null;
}
 
Example 27
@Override
public void visit(MethodDeclaration n, Void arg) {
    if (Util.isValidTestMethod(n)) {
        Optional<AnnotationExpr> assertAnnotation = n.getAnnotationByName("Test");
        if (assertAnnotation.isPresent()) {
            for (int i = 0; i < assertAnnotation.get().getNodeLists().size(); i++) {
                NodeList<?> c = assertAnnotation.get().getNodeLists().get(i);
                for (int j = 0; j < c.size(); j++)
                    if (c.get(j) instanceof MemberValuePair) {
                        if (((MemberValuePair) c.get(j)).getName().equals("expected") && ((MemberValuePair) c.get(j)).getValue().toString().contains("Exception"))
                            ;
                        hasExceptionAnnotation = true;
                    }
            }
        }
        currentMethod = n;
        testMethod = new TestMethod(n.getNameAsString());
        testMethod.setHasSmell(false); //default value is false (i.e. no smell)
        super.visit(n, arg);

        // if there are duplicate messages, then the smell exists
        if (!hasAssert && !hasExceptionAnnotation)
            testMethod.setHasSmell(true);

        smellyElementList.add(testMethod);

        //reset values for next method
        currentMethod = null;
        assertMessage = new ArrayList<>();
        hasAssert = false;
    }
}
 
Example 28
Source Project: jaxrs-analyzer   Source File: JavaDocParserVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private MemberParameterTag createMethodParameterTag(JavadocBlockTag tag, MethodDeclaration method) {
    Stream<AnnotationExpr> annotations = method.getParameterByName(tag.getName().orElse(null))
            .map(Parameter::getAnnotations)
            .map(NodeList::stream)
            .orElseGet(Stream::empty);

    return createMemberParamTag(tag.getContent(), annotations);
}
 
Example 29
Source Project: jaxrs-analyzer   Source File: JavaDocParserVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private MemberParameterTag createMemberParamTag(JavadocDescription javadocDescription, Stream<AnnotationExpr> annotationStream) {
    Map<String, String> annotations = annotationStream
            .filter(Expression::isSingleMemberAnnotationExpr)
            .collect(Collectors.toMap(a -> a.getName().getIdentifier(),
                    this::createMemberParamValue));
    return new MemberParameterTag(javadocDescription.toText(), annotations);
}
 
Example 30
Source Project: jaxrs-analyzer   Source File: JavaDocParserVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private String createMemberParamValue(AnnotationExpr a) {
    Expression memberValue = a.asSingleMemberAnnotationExpr().getMemberValue();
    if (memberValue.getClass().isAssignableFrom(StringLiteralExpr.class))
        return memberValue.asStringLiteralExpr().asString();

    if (memberValue.getClass().isAssignableFrom(NameExpr.class))
        return memberValue.asNameExpr().getNameAsString();

    throw new IllegalArgumentException(String.format("Javadoc param type (%s) not supported.", memberValue.toString()));
}