Java Code Examples for com.github.javaparser.ast.NodeList#size()

The following examples show how to use com.github.javaparser.ast.NodeList#size() . 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: RequestMappingHelper.java    From apigcc with 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 2
Source File: ExpressionHelper.java    From apigcc with MIT License 5 votes vote down vote up
public static String getStringValue(Expression expression){
    if(expression.isStringLiteralExpr()){
        return expression.asStringLiteralExpr().getValue();
    }else if(expression.isArrayInitializerExpr()){
        NodeList<Expression> values = expression.asArrayInitializerExpr().getValues();
        if(values.size()>0){
            return getStringValue(values.get(0));
        }
    }else if(expression instanceof Resolvable){
        return String.valueOf(resolve((Resolvable)expression));
    }
    return expression.toString();
}
 
Example 3
Source File: RemoveMethodParameter.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * @param methodDeclaration
 * @param parameterName
 * @return index of the parameter with the given name, or null if not found
 */
private Integer getMethodParameterIndex(MethodDeclaration methodDeclaration, String parameterName) {
	NodeList<Parameter> parameters = methodDeclaration.getParameters();
	for (int i = 0; i < parameters.size(); i++) {
		if (parameters.get(i).getName().asString().equals(parameterName)) {
			return i;
		}
	}
	return null;
}
 
Example 4
Source File: Extends.java    From butterfly with MIT License 5 votes vote down vote up
@Override
protected int getNumberOfTypes(CompilationUnit compilationUnit) {
    TypeDeclaration<?> typeDeclaration = compilationUnit.getType(0);
    if (typeDeclaration instanceof ClassOrInterfaceDeclaration) {
        ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
        NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes();
        return extendedTypes.size();
    }

    // If typeDeclaration is not ClassOrInterfaceDeclaration, then it is
    // EnumDeclaration or AnnotationDeclaration, and none of them have
    // a getExtendedTypes operation

    return 0;
}
 
Example 5
Source File: GeneralFixture.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void runAnalysis(CompilationUnit testFileCompilationUnit, CompilationUnit productionFileCompilationUnit, String testFileName, String productionFileName) throws FileNotFoundException {
    GeneralFixture.ClassVisitor classVisitor;
    classVisitor = new GeneralFixture.ClassVisitor();
    classVisitor.visit(testFileCompilationUnit, null); //This call will populate the list of test methods and identify the setup method [visit(ClassOrInterfaceDeclaration n)]

    //Proceed with general fixture analysis if setup method exists
    if (setupMethod != null) {
        //Get all fields that are initialized in the setup method
        //The following code block will identify the class level variables (i.e. fields) that are initialized in the setup method
        // TODO: There has to be a better way to do this identification/check!
        Optional<BlockStmt> blockStmt = setupMethod.getBody();
        NodeList nodeList = blockStmt.get().getStatements();
        for (int i = 0; i < nodeList.size(); i++) {
            for (int j = 0; j < fieldList.size(); j++) {
                for (int k = 0; k < fieldList.get(j).getVariables().size(); k++) {
                    if (nodeList.get(i) instanceof ExpressionStmt) {
                        ExpressionStmt expressionStmt = (ExpressionStmt) nodeList.get(i);
                        if (expressionStmt.getExpression() instanceof AssignExpr) {
                            AssignExpr assignExpr = (AssignExpr) expressionStmt.getExpression();
                            if (fieldList.get(j).getVariable(k).getNameAsString().equals(assignExpr.getTarget().toString())) {
                                setupFields.add(assignExpr.getTarget().toString());
                            }
                        }
                    }
                }
            }
        }
    }

    for (MethodDeclaration method : methodList) {
        //This call will visit each test method to identify the list of variables the method contains [visit(MethodDeclaration n)]
        classVisitor.visit(method, null);
    }
}
 
Example 6
Source File: GeneralFixture.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
    NodeList<BodyDeclaration<?>> members = n.getMembers();
    for (int i = 0; i < members.size(); i++) {
        if (members.get(i) instanceof MethodDeclaration) {
            methodDeclaration = (MethodDeclaration) members.get(i);

            //Get a list of all test methods
            if (Util.isValidTestMethod(methodDeclaration)) {
                methodList.add(methodDeclaration);
            }

            //Get the setup method
            if (Util.isValidSetupMethod(methodDeclaration)) {
                //It should have a body
                if (methodDeclaration.getBody().isPresent()) {
                    setupMethod = methodDeclaration;
                }
            }
        }

        //Get all fields in the class
        if (members.get(i) instanceof FieldDeclaration) {
            fieldList.add((FieldDeclaration) members.get(i));
        }
    }
}
 
Example 7
Source File: UnknownTest.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
@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 8
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Unwrap (possibly nested) 1 statement blocks
 * @param stmt -
 * @return unwrapped (non- block) statement
 */
private Statement getStmtFromStmt(Statement stmt) {
  while (stmt instanceof BlockStmt) {
    NodeList<Statement> stmts = ((BlockStmt) stmt).getStatements();
    if (stmts.size() == 1) {
      stmt = stmts.get(0);
      continue;
    }
    return null;
  }
  return stmt;
}
 
Example 9
Source File: ParseHelper.java    From genDoc with Apache License 2.0 4 votes vote down vote up
static List<Annotation> parseAnnotation(NodeWithAnnotations<? extends Node> nodeWithAnnotations, Member member) {
    NodeList<AnnotationExpr> annotationExprs = nodeWithAnnotations.getAnnotations();

    if (annotationExprs != null && annotationExprs.size() > 0) {
        List<Annotation> annotations = new ArrayList<Annotation>();

        for (AnnotationExpr annotationExpr : annotationExprs) {
            Annotation annotation = null;

            if (annotationExpr instanceof MarkerAnnotationExpr) {
                annotation = new MarkerAnnotation();
            } else if (annotationExpr instanceof SingleMemberAnnotationExpr) {
                SingleMemberAnnotationExpr singleMemberAnnotationExpr = (SingleMemberAnnotationExpr) annotationExpr;

                annotation = new SingleAnnotation();


                SingleAnnotation singleAnnotation = (SingleAnnotation) annotation;
                singleAnnotation.setValue(annotationValueTrim(singleMemberAnnotationExpr.getMemberValue().toString()));
            } else if (annotationExpr instanceof NormalAnnotationExpr) {
                NormalAnnotationExpr normalAnnotationExpr = (NormalAnnotationExpr) annotationExpr;

                annotation = new NormalAnnotation();

                NormalAnnotation normalAnnotation = (NormalAnnotation) annotation;

                List<NormalAnnotation.Pair> pairList = new ArrayList<NormalAnnotation.Pair>();

                for (MemberValuePair memberValuePair : normalAnnotationExpr.getPairs()) {
                    NormalAnnotation.Pair pair = new NormalAnnotation.Pair();
                    pair.setName(memberValuePair.getNameAsString());
                    pair.setValue(annotationValueTrim(memberValuePair.getValue().toString()));
                    pairList.add(pair);
                }
                normalAnnotation.setPairList(pairList);
            }

            if (annotation != null) {
                annotation.setName(annotationExpr.getNameAsString());
                annotation.setMember(member);
                annotations.add(annotation);
            }
        }

        return annotations;
    }
    return null;
}
 
Example 10
Source File: GroovydocJavaVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
private String genericTypesAsString(NodeList<TypeParameter> typeParameters) {
    if (typeParameters == null || typeParameters.size() == 0)
        return "";
    return "<" + DefaultGroovyMethods.join(typeParameters, ", ") + ">";
}
 
Example 11
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the top level class looks like a JCas class, and report if not:
 *   has 0, 1, and 2 element constructors
 *   has static final field defs for type and typeIndexID
 *   
 *   Also check if V2 style: 2 arg constructor arg types
 *   Report if looks like V3 style due to args of 2 arg constructor
 *   
 *   if class doesn't extend anything, not a JCas class.
 *   if class is enum, not a JCas class
 * @param n -
 * @param ignore -
 */
@Override
public void visit(ClassOrInterfaceDeclaration n, Object ignore) {
  // do checks to see if this is a JCas class; if not report skipped
 
  Optional<Node> maybeParent = n.getParentNode();
  if (maybeParent.isPresent()) {
    Node parent = maybeParent.get();
    if (parent instanceof CompilationUnit) {
      updateClassName(n);
      if (isBuiltinJCas) {
        // is a built-in class, skip it
        super.visit(n, ignore);
        return;
      }
      NodeList<ClassOrInterfaceType> supers = n.getExtendedTypes();
      if (supers == null || supers.size() == 0) {
        reportNotJCasClass("class doesn't extend a superclass");
        super.visit(n, ignore);
        return; 
      }
      
      NodeList<BodyDeclaration<?>> members = n.getMembers();
      setHasJCasConstructors(members);
      if (hasV2Constructors && hasTypeFields(members)) {
        reportV2Class();
        super.visit(n,  ignore);
        return;
      }
      if (hasV2Constructors) {
        reportNotJCasClassMissingTypeFields();
        return;
      }
      if (hasV3Constructors) {
        reportV3Class();
        return;
      }
      reportNotJCasClass("missing v2 constructors");
      return;        
    }
  }
  
  super.visit(n,  ignore);
  return;
  
}
 
Example 12
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/** 
 * visitor for method calls
 */
@Override
public void visit(MethodCallExpr n, Object ignore) {
  Optional<Node> p1, p2, p3 = null; 
  Node updatedNode = null;
  NodeList<Expression> args;
  
  do {
    if (get_set_method == null) break;
   
    /** remove checkArraybounds statement **/
    if (n.getNameAsString().equals("checkArrayBounds") &&
        ((p1 = n.getParentNode()).isPresent() && p1.get() instanceof ExpressionStmt) &&
        ((p2 = p1.get().getParentNode()).isPresent() && p2.get() instanceof BlockStmt) &&
        ((p3 = p2.get().getParentNode()).isPresent() && p3.get() == get_set_method)) {
      NodeList<Statement> stmts = ((BlockStmt)p2.get()).getStatements();
      stmts.set(stmts.indexOf(p1.get()), new EmptyStmt());
      return;
    }
         
    // convert simpleCore expression ll_get/setRangeValue
    boolean useGetter = isGetter || isArraySetter;
    if (n.getNameAsString().startsWith("ll_" + (useGetter ? "get" : "set") + rangeNameV2Part + "Value")) {
      args = n.getArguments();
      if (args.size() != (useGetter ? 2 : 3)) break;
      String suffix = useGetter ? "Nc" : rangeNamePart.equals("Feature") ? "NcWj" : "Nfc";
      String methodName = "_" + (useGetter ? "get" : "set") + rangeNamePart + "Value" + suffix; 
      args.remove(0);    // remove the old addr arg
      // arg 0 converted when visiting args FieldAccessExpr 
      n.setScope(null);
      n.setName(methodName);
    }
    
    // convert array sets/gets
    String z = "ll_" + (isGetter ? "get" : "set");
    String nname = n.getNameAsString();
    if (nname.startsWith(z) &&
        nname.endsWith("ArrayValue")) {
      
      String s = nname.substring(z.length());
      s = s.substring(0,  s.length() - "Value".length()); // s = "ShortArray",  etc.
      if (s.equals("RefArray")) s = "FSArray";
      if (s.equals("IntArray")) s = "IntegerArray";
      EnclosedExpr ee = new EnclosedExpr(
          new CastExpr(new ClassOrInterfaceType(s), n.getArguments().get(0)));
      
      n.setScope(ee);    // the getter for the array fs
      n.setName(isGetter ? "get" : "set");
      n.getArguments().remove(0);
    }
    
    /** remove ll_getFSForRef **/
    /** remove ll_getFSRef **/
    if (n.getNameAsString().equals("ll_getFSForRef") ||
        n.getNameAsString().equals("ll_getFSRef")) {
      updatedNode = replaceInParent(n, n.getArguments().get(0));        
    }
    
    
    
  } while (false);
      
  if (updatedNode != null) {
    updatedNode.accept(this,  null);
  } else {
    super.visit(n, null);
  }
}