com.github.javaparser.ast.body.ClassOrInterfaceDeclaration Java Examples

The following examples show how to use com.github.javaparser.ast.body.ClassOrInterfaceDeclaration. 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 6 votes vote down vote up
/**
 * 判断是否为Rest接口
 * @param n
 * @return
 */
public static boolean isRest(MethodDeclaration n){
    if(n.isAnnotationPresent(ANNOTATION_RESPONSE_BODY)){
        return true;
    }
    Optional<Node> parentOptional = n.getParentNode();
    if(parentOptional.isPresent()){
        Node parentNode = parentOptional.get();
        if(parentNode instanceof ClassOrInterfaceDeclaration){
            if (((ClassOrInterfaceDeclaration) parentNode).isAnnotationPresent(SpringParser.ANNOTATION_REST_CONTROLLER)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #2
Source File: RefactoringHelperTest.java    From Refactoring-Bot with MIT License 6 votes vote down vote up
@Test
public void testGetClassOrInterfaceOfMethod() throws FileNotFoundException {
	// arrange
	FileInputStream in = new FileInputStream(getTestResourcesFile());
	CompilationUnit cu = StaticJavaParser.parse(in);
	int lineNumber = TestDataClassRefactoringHelper.getLineOfMethod(true);

	MethodDeclaration methodDeclaration = RefactoringHelper.getMethodDeclarationByLineNumber(lineNumber, cu);
	assertThat(methodDeclaration).isNotNull();

	// act
	ClassOrInterfaceDeclaration classOrInterface = RefactoringHelper.getClassOrInterfaceOfMethod(methodDeclaration);

	// assert
	assertThat(classOrInterface).isNotNull();
	assertThat(classOrInterface.getNameAsString()).isEqualTo(TARGET_CLASS_NAME);
}
 
Example #3
Source File: ImmutableBeanGenerator.java    From state-machine with Apache License 2.0 6 votes vote down vote up
private static void writeEquals(PrintStream s, Map<String, String> imports, String indent,
        ClassOrInterfaceDeclaration c, List<VariableDeclarator> vars) {
    s.format("\n\n%s@%s", indent, resolve(imports, Override.class));
    s.format("\n%spublic boolean equals(Object o) {", indent);
    s.format("\n%s%sif (o == null) {", indent, indent);
    s.format("\n%s%s%sreturn false;", indent, indent, indent);
    s.format("\n%s%s} else if (!(o instanceof %s)) {", indent, indent, c.getName());
    s.format("\n%s%s%sreturn false;", indent, indent, indent);
    s.format("\n%s%s} else {", indent, indent);
    if (vars.isEmpty()) {
        s.format("\n%s%s%sreturn true;", indent, indent, indent);
    } else {
        s.format("\n%s%s%s%s other = (%s) o;", indent, indent, indent, c.getName(), c.getName());
        s.format("\n%s%s%sreturn", indent, indent, indent);
        String expression = vars.stream() ///
                .map(x -> String.format("%s.deepEquals(this.%s, other.%s)", //
                        resolve(imports, Objects.class), x.getName(), x.getName())) //
                .collect(Collectors.joining(String.format("\n%s%s%s%s&& ", indent, indent, indent, indent)));
        s.format("\n%s%s%s%s%s;", indent, indent, indent, indent, expression);
    }
    s.format("\n%s%s}", indent, indent);
    s.format("\n%s}", indent);
}
 
Example #4
Source File: SpringControllerParser.java    From JApiDocs with Apache License 2.0 6 votes vote down vote up
@Override
protected void beforeHandleController(ControllerNode controllerNode, ClassOrInterfaceDeclaration clazz) {
    clazz.getAnnotationByName("RequestMapping").ifPresent(a -> {
        if (a instanceof SingleMemberAnnotationExpr) {
            String baseUrl = ((SingleMemberAnnotationExpr) a).getMemberValue().toString();
            controllerNode.setBaseUrl(Utils.removeQuotations(baseUrl));
            return;
        }
        if (a instanceof NormalAnnotationExpr) {
            ((NormalAnnotationExpr) a).getPairs().stream()
                    .filter(v -> isUrlPathKey(v.getNameAsString()))
                    .findFirst()
                    .ifPresent(p -> {
                        controllerNode.setBaseUrl(Utils.removeQuotations(p.getValue().toString()));
                    });
        }
    });
}
 
Example #5
Source File: OpenApiObjectGenerator.java    From flow with 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 #6
Source File: Extends.java    From butterfly with MIT License 6 votes vote down vote up
@Override
protected String getTypeName(CompilationUnit compilationUnit, int index) {
    ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
    NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes();
    ClassOrInterfaceType extendedType = extendedTypes.get(index);
    String typeSimpleName = extendedType.getName().getIdentifier();
    Optional<ClassOrInterfaceType> scope = extendedType.getScope();
    String typeName;
    if (scope.isPresent()) {
        String typePackageName = scope.get().toString();
        typeName = String.format("%s.%s", typePackageName, typeSimpleName);
    } else {
        typeName = typeSimpleName;
    }
    return typeName;
}
 
Example #7
Source File: IncrementalRuleCodegen.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void generateSessionUnits( List<org.kie.kogito.codegen.GeneratedFile> generatedFiles ) {
    for (KieBaseModel kBaseModel : kieModuleModel.getKieBaseModels().values()) {
        for (String sessionName : kBaseModel.getKieSessionModels().keySet()) {
            CompilationUnit cu = parse( getClass().getResourceAsStream( "/class-templates/SessionRuleUnitTemplate.java" ) );
            ClassOrInterfaceDeclaration template = cu.findFirst( ClassOrInterfaceDeclaration.class ).get();
            annotator.withNamedSingletonComponent(template, "$SessionName$");
            template.setName( "SessionRuleUnit_" + sessionName );

            template.findAll( FieldDeclaration.class).stream().filter( fd -> fd.getVariable(0).getNameAsString().equals("runtimeBuilder")).forEach( fd -> annotator.withInjection(fd));

            template.findAll( StringLiteralExpr.class ).forEach( s -> s.setString( s.getValue().replace( "$SessionName$", sessionName ) ) );
            generatedFiles.add(new org.kie.kogito.codegen.GeneratedFile(
                    org.kie.kogito.codegen.GeneratedFile.Type.RULE,
                    "org/drools/project/model/SessionRuleUnit_" + sessionName + ".java",
                    log( cu.toString() ) ));
        }
    }
}
 
Example #8
Source File: RefactoringHelper.java    From Refactoring-Bot with MIT License 6 votes vote down vote up
/**
 * @param allJavaFiles
 * @param targetClass
 * @param targetMethod
 * @return list of qualified class or interface names which are reachable via
 *         the inheritance hierarchy of the given class (ancestors, descendants,
 *         siblings, ...) and contain the given target method
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
public static Set<String> findRelatedClassesAndInterfaces(List<String> allJavaFiles,
		ClassOrInterfaceDeclaration targetClass, MethodDeclaration targetMethod)
		throws BotRefactoringException, FileNotFoundException {
	Set<ResolvedReferenceTypeDeclaration> relatedClassesAndInterfaces = new HashSet<>();
	relatedClassesAndInterfaces.add(targetClass.resolve());

	addQualifiedNamesToRelatedClassesAndInterfacesRecursively(relatedClassesAndInterfaces, allJavaFiles,
			targetClass, targetMethod);

	Set<String> result = new HashSet<>();
	for (ResolvedReferenceTypeDeclaration declaration : relatedClassesAndInterfaces) {
		result.add(declaration.getQualifiedName());
	}

	return result;
}
 
Example #9
Source File: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private String getReturnType(ClassOrInterfaceDeclaration clazz) {
    MethodDeclaration toResultMethod = clazz.getMethodsByName("toResult").get(0);
    String returnType;
    if (query.getBindings().size() == 1) {
        Map.Entry<String, Class<?>> binding = query.getBindings().entrySet().iterator().next();
        String name = binding.getKey();
        returnType = binding.getValue().getCanonicalName();

        Statement statement = toResultMethod
                .getBody()
                .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
                .getStatement(0);

        statement.findFirst(CastExpr.class).orElseThrow(() -> new NoSuchElementException("CastExpr not found in template.")).setType(returnType);
        statement.findFirst(StringLiteralExpr.class).orElseThrow(() -> new NoSuchElementException("StringLiteralExpr not found in template.")).setString(name);
    } else {
        returnType = "Result";
        generateResultClass(clazz, toResultMethod);
    }

    toResultMethod.setType(returnType);
    return returnType;
}
 
Example #10
Source File: GroovydocJavaVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
    SimpleGroovyClassDoc parent = visit(n);
    if (n.isInterface()) {
        currentClassDoc.setTokenType(SimpleGroovyDoc.INTERFACE_DEF);
    } else {
        currentClassDoc.setTokenType(SimpleGroovyDoc.CLASS_DEF);
    }
    n.getExtendedTypes().forEach(et -> {
        if (n.isInterface()) {
            currentClassDoc.addInterfaceName(fullName(et));
        } else {
            currentClassDoc.setSuperClassName(fullName(et));
        }
    });
    currentClassDoc.setNameWithTypeArgs(currentClassDoc.name() + genericTypesAsString(n.getTypeParameters()));
    n.getImplementedTypes().forEach(classOrInterfaceType ->
            currentClassDoc.addInterfaceName(fullName(classOrInterfaceType)));
    super.visit(n, arg);
    if (parent != null) {
        currentClassDoc = parent;
    }
}
 
Example #11
Source File: RenameMethod.java    From Refactoring-Bot with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	configureJavaParserForProject(issue);

	String newMethodName = issue.getRefactorString();
	String issueFilePath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	MethodDeclaration targetMethod = findAndValidateTargetMethod(issue, issueFilePath, newMethodName);
	ClassOrInterfaceDeclaration targetClass = RefactoringHelper.getClassOrInterfaceOfMethod(targetMethod);
	Set<String> qualifiedNamesOfRelatedClassesAndInterfaces = RefactoringHelper
			.findRelatedClassesAndInterfaces(issue.getAllJavaFiles(), targetClass, targetMethod);

	HashSet<String> javaFilesRelevantForRefactoring = findRelevantJavaFiles(issue, newMethodName, targetMethod,
			qualifiedNamesOfRelatedClassesAndInterfaces);
	renameRelatedMethodDeclarationsAndMethodCalls(javaFilesRelevantForRefactoring, newMethodName);

	String oldMethodName = targetMethod.getNameAsString();
	return "Renamed method '" + oldMethodName + "' to '" + newMethodName + "'";
}
 
Example #12
Source File: RemoveMethodParameter.java    From Refactoring-Bot with MIT License 6 votes vote down vote up
/**
 * Tries to find the target method in the given class or interface. Checks if
 * the found method itself could be refactored, without yet checking other code
 * locations
 * 
 * @param issue
 * @param filePath
 * @param parameterToBeRemoved
 * @return
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
private MethodDeclaration findAndValidateTargetMethod(BotIssue issue, String filePath, String parameterToBeRemoved)
		throws BotRefactoringException, FileNotFoundException {
	List<ClassOrInterfaceDeclaration> classesAndInterfaces = RefactoringHelper
			.getAllClassesAndInterfacesFromFile(filePath);

	MethodDeclaration targetMethod = null;
	for (ClassOrInterfaceDeclaration classOrInterface : classesAndInterfaces) {
		for (MethodDeclaration currentMethod : classOrInterface.getMethods()) {
			if (RefactoringHelper.isMethodDeclarationAtLine(currentMethod, issue.getLine())) {
				targetMethod = currentMethod;
				break;
			}
		}
		if (targetMethod != null) {
			break;
		}
	}

	if (targetMethod == null) {
		throw new BotRefactoringException("Could not find a method declaration at the given line!");
	}
	validateMethodHasParameter(targetMethod, parameterToBeRemoved);
	validateParameterUnused(targetMethod, parameterToBeRemoved);
	return targetMethod;
}
 
Example #13
Source File: ClassOrInterfaceDeclarationMerger.java    From dolphin with Apache License 2.0 6 votes vote down vote up
@Override
public ClassOrInterfaceDeclaration doMerge(ClassOrInterfaceDeclaration first, ClassOrInterfaceDeclaration second) {

  ClassOrInterfaceDeclaration declaration = new ClassOrInterfaceDeclaration();

  declaration.setInterface(first.isInterface());
  declaration.setName(first.getName());

  declaration.setModifiers(mergeModifiers(first.getModifiers(), second.getModifiers()));
  declaration.setJavaDoc(mergeSingle(first.getJavaDoc(), second.getJavaDoc()));
  declaration.setTypeParameters(mergeCollections(first.getTypeParameters(), second.getTypeParameters()));

  declaration.setImplements(mergeCollections(first.getImplements(), second.getImplements()));
  declaration.setExtends(mergeCollections(first.getExtends(), second.getExtends()));

  declaration.setAnnotations(mergeCollections(first.getAnnotations(), second.getAnnotations()));
  declaration.setMembers(mergeCollections(first.getMembers(), second.getMembers()));

  return declaration;
}
 
Example #14
Source File: MethodBoundaryExtractor.java    From scott with MIT License 6 votes vote down vote up
private boolean isInTheCorrectClass(MethodDeclaration methodDeclaration) {
	Node n = methodDeclaration;
	
	String containingClassName = "";
	while (n != null) {
		if (n instanceof ClassOrInterfaceDeclaration) {
			ClassOrInterfaceDeclaration c = (ClassOrInterfaceDeclaration) n;
			containingClassName = c.getName() + "$" + containingClassName;
		}
		Optional<Node> no = n.getParentNode();
		if (no.isEmpty()) {
			n = null;
		} else {
			n = no.get();
		}
	}
	
	containingClassName = containingClassName.substring(0, containingClassName.length() - 1);
	return containingClassName.equals(className);
}
 
Example #15
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 6 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(name);

  String propertyName = decapitalize(name);
  classDecl.addField(getJavaType(), propertyName).setPrivate(true).setFinal(true);

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  constructor.addParameter(getJavaType(), propertyName);
  constructor.getBody().addStatement(String.format(
      "this.%s = java.util.Objects.requireNonNull(%s, \"Missing value for %s\");",
      propertyName, propertyName, name
  ));

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(name);
  fromJson.addParameter(JsonInput.class, "input");
  fromJson.getBody().get().addStatement(String.format("return %s;", getMapper()));

  MethodDeclaration toString = classDecl.addMethod("toString").setPublic(true);
  toString.setType(String.class);
  toString.getBody().get().addStatement(String.format("return %s.toString();", propertyName));

  return classDecl;
}
 
Example #16
Source File: DecisionCodegenTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void generateAllFiles() throws Exception {

    GeneratorContext context = stronglyTypedContext();

    DecisionCodegen codeGenerator = DecisionCodegen.ofPath(Paths.get("src/test/resources/decision/models/vacationDays").toAbsolutePath());
    codeGenerator.setContext(context);

    List<GeneratedFile> generatedFiles = codeGenerator.generate();
    assertEquals(5, generatedFiles.size());

    assertIterableEquals(Arrays.asList(
            "decision/InputSet.java",
            "decision/TEmployee.java",
            "decision/TAddress.java",
            "decision/TPayroll.java",
            "decision/VacationsResource.java"
                         ),
                         fileNames(generatedFiles)
    );

    ClassOrInterfaceDeclaration classDeclaration = codeGenerator.moduleGenerator().classDeclaration();
    assertNotNull(classDeclaration);
}
 
Example #17
Source File: MarshallerGeneratorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonWithAdressesMarshallers() throws Exception {
    
    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(PersonWithAddresses.class));
    assertThat(proto).isNotNull();        
    assertThat(proto.getMessages()).hasSize(2);

    System.out.println(proto.getMessages());
    
    MarshallerGenerator marshallerGenerator = new MarshallerGenerator(this.getClass().getClassLoader());
    
    List<CompilationUnit> classes = marshallerGenerator.generate(proto.toString());
    assertThat(classes).isNotNull();       
    assertThat(classes).hasSize(2);
    
    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("AddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
    marshallerClass = classes.get(1).getClassByName("PersonWithAddressesMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #18
Source File: MarshallerGeneratorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonWithAdressMarshallers() throws Exception {
    
    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(PersonWithAddress.class));
    assertThat(proto).isNotNull();        
    assertThat(proto.getMessages()).hasSize(2);
    
    MarshallerGenerator marshallerGenerator = new MarshallerGenerator(this.getClass().getClassLoader());
    
    List<CompilationUnit> classes = marshallerGenerator.generate(proto.toString());
    assertThat(classes).isNotNull();       
    assertThat(classes).hasSize(2);
    
    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("AddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
    marshallerClass = classes.get(1).getClassByName("PersonWithAddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #19
Source File: MarshallerGeneratorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonWithListMarshallers() throws Exception {

    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(PersonWithList.class));
    assertThat(proto).isNotNull();
    assertThat(proto.getMessages()).hasSize(1);

    System.out.println(proto.getMessages());

    MarshallerGenerator marshallerGenerator = new MarshallerGenerator(this.getClass().getClassLoader());

    List<CompilationUnit> classes = marshallerGenerator.generate(proto.toString());
    assertThat(classes).isNotNull();
    assertThat(classes).hasSize(1);

    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("PersonWithListMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #20
Source File: MarshallerGeneratorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonMarshallers() throws Exception {
    
    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(Person.class));
    assertThat(proto).isNotNull();        
    assertThat(proto.getMessages()).hasSize(1);
    
    MarshallerGenerator marshallerGenerator = new MarshallerGenerator(this.getClass().getClassLoader());
    
    List<CompilationUnit> classes = marshallerGenerator.generate(proto.toString());
    assertThat(classes).isNotNull();       
    assertThat(classes).hasSize(1);
    
    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("PersonMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #21
Source File: RemoveMethodParameter.java    From Refactoring-Bot with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	configureJavaParserForProject(issue);

	String parameterName = issue.getRefactorString();
	String issueFilePath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	MethodDeclaration targetMethod = findAndValidateTargetMethod(issue, issueFilePath, parameterName);
	ClassOrInterfaceDeclaration targetClass = RefactoringHelper.getClassOrInterfaceOfMethod(targetMethod);
	Set<String> qualifiedNamesOfRelatedClassesAndInterfaces = RefactoringHelper
			.findRelatedClassesAndInterfaces(issue.getAllJavaFiles(), targetClass, targetMethod);

	HashSet<String> javaFilesRelevantForRefactoring = findRelevantJavaFiles(issue, parameterName,
			targetMethod, qualifiedNamesOfRelatedClassesAndInterfaces);
	removeParameterFromRelatedMethodDeclarationsAndMethodCalls(javaFilesRelevantForRefactoring, targetMethod,
			parameterName);

	String targetMethodSignature = RefactoringHelper.getLocalMethodSignatureAsString(targetMethod);
	return "Removed parameter '" + parameterName + "' from method '" + targetMethodSignature + "'";
}
 
Example #22
Source File: FinalRClassBuilder.java    From Briefness with Apache License 2.0 6 votes vote down vote up
public static void brewJava(File rFile, File outputDir, String packageName, String className, boolean useLegacyTypes) throws Exception {
  CompilationUnit compilationUnit = JavaParser.parse(rFile);
  TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);

  TypeSpec.Builder result = TypeSpec.classBuilder(className)
      .addModifiers(PUBLIC, FINAL);

  for (Node node : resourceClass.getChildNodes()) {
    if (node instanceof ClassOrInterfaceDeclaration) {
      addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node, useLegacyTypes);
    }
  }

  JavaFile finalR = JavaFile.builder(packageName, result.build())
      .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!")
      .build();

  finalR.writeTo(outputDir);
}
 
Example #23
Source File: JFinalRoutesParser.java    From JApiDocs with Apache License 2.0 5 votes vote down vote up
private JFinalRoutesParser(){
    List<File> result = new ArrayList<>();

    for(String javaSrcPath : DocContext.getJavaSrcPaths()){
        Utils.wideSearchFile(new File(javaSrcPath), new FilenameFilter() {
            @Override
            public boolean accept(File f, String name) {
                return ParseUtils.compilationUnit(f).getChildNodesByType(ClassOrInterfaceDeclaration.class)
                        .stream()
                        .anyMatch(cl -> cl.getMethodsByName("configRoute")
                                .stream()
                                .anyMatch(m -> {
                                    mdConfigRoute = m;
                                    return m.getParameters()
                                            .stream()
                                            .anyMatch(p -> p.getType().asString().endsWith("Routes"));
                                }));
            }
        },result, true);

        if(!result.isEmpty()){
            break;
        }
    }


    if(result.isEmpty()){
        throw new RuntimeException("cannot find JFinalConfig File");
    }

    jfinalConfigFile = result.get(0);

    LogUtils.info("Jfinal config file path : %s", jfinalConfigFile.getAbsolutePath());

    parse(mdConfigRoute, jfinalConfigFile);
}
 
Example #24
Source File: ClassHelper.java    From apigcc with MIT License 5 votes vote down vote up
/**
 * 获取并解析父类
 * @param n
 * @return
 */
public static Optional<ClassOrInterfaceDeclaration> getParent(ClassOrInterfaceDeclaration n) {
    if (n.getExtendedTypes().isEmpty()) {
        return Optional.empty();
    }
    return tryToResolve(n.getExtendedTypes().get(0));
}
 
Example #25
Source File: JFinalRoutesParser.java    From JApiDocs with Apache License 2.0 5 votes vote down vote up
private void parse(MethodDeclaration mdConfigRoute, File inJavaFile){
    mdConfigRoute.getBody()
            .ifPresent(blockStmt -> blockStmt.getStatements()
                    .stream()
                    .filter(statement -> statement instanceof ExpressionStmt)
                    .forEach(statement -> {
                       Expression expression = ((ExpressionStmt)statement).getExpression();
                       if(expression instanceof MethodCallExpr && ((MethodCallExpr)expression).getNameAsString().equals("add")){
                           NodeList<Expression> arguments = ((MethodCallExpr)expression).getArguments();
                           if(arguments.size() == 1 && arguments.get(0) instanceof ObjectCreationExpr){
                               String routeClassName = ((ObjectCreationExpr)((MethodCallExpr) expression).getArguments().get(0)).getType().getNameAsString();
                               File childRouteFile = ParseUtils.searchJavaFile(inJavaFile, routeClassName);
                               LogUtils.info("found child routes in file : %s" , childRouteFile.getName());
                               ParseUtils.compilationUnit(childRouteFile)
                                       .getChildNodesByType(ClassOrInterfaceDeclaration.class)
                                       .stream()
                                       .filter(cd -> routeClassName.endsWith(cd.getNameAsString()))
                                       .findFirst()
                                       .ifPresent(cd ->{
                                           LogUtils.info("found config() method, start to parse child routes in file : %s" , childRouteFile.getName());
                                           cd.getMethodsByName("config").stream().findFirst().ifPresent(m ->{
                                               parse(m, childRouteFile);
                                           });
                                       });
                           }else{
                               String basicUrl = Utils.removeQuotations(arguments.get(0).toString());
                               String controllerClass = arguments.get(1).toString();
                               String controllerFilePath = getControllerFilePath(inJavaFile, controllerClass);
                               routeNodeList.add(new RouteNode(basicUrl, controllerFilePath));
                           }
                       }
    }));
}
 
Example #26
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Collection<TypeDeclaration<?>> appendNestedClasses(
        ClassOrInterfaceDeclaration topLevelClass) {
    Set<TypeDeclaration<?>> nestedClasses = topLevelClass
            .getMembers().stream()
            .filter(bodyDeclaration -> bodyDeclaration.isClassOrInterfaceDeclaration()
                    || bodyDeclaration.isEnumDeclaration())
            .map(bodyDeclaration -> (TypeDeclaration<?>) bodyDeclaration.asTypeDeclaration())
            .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator
                    .comparing(NodeWithSimpleName::getNameAsString))));
    nestedClasses.add(topLevelClass);
    return nestedClasses;
}
 
Example #27
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 #28
Source File: ConfigurableEagerTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
    if (Objects.equals(fileType, PRODUCTION_FILE)) {
        productionClassName = n.getNameAsString();
    }
    super.visit(n, arg);
}
 
Example #29
Source File: AbsControllerParser.java    From JApiDocs with Apache License 2.0 5 votes vote down vote up
private void parseClassDoc(ClassOrInterfaceDeclaration c) {

        c.getParentNode().get().findFirst(PackageDeclaration.class).ifPresent(pd -> {
            controllerNode.setPackageName(pd.getNameAsString());
        });

        boolean generateDocs = c.getAnnotationByName("ApiDoc").isPresent();
        controllerNode.setGenerateDocs(generateDocs);

        c.getJavadoc().ifPresent(d -> {
            String description = d.getDescription().toText();
            controllerNode.setDescription(Utils.isNotEmpty(description) ? description : c.getNameAsString());
            List<JavadocBlockTag> blockTags = d.getBlockTags();
            if (blockTags != null) {
                for (JavadocBlockTag blockTag : blockTags) {
                    if ("author".equalsIgnoreCase(blockTag.getTagName())) {
                        controllerNode.setAuthor(blockTag.getContent().toText());
                    }
                    if ("description".equalsIgnoreCase(blockTag.getTagName())) {
                        controllerNode.setDescription(blockTag.getContent().toText());
                    }
                }
            }
        });

        if (controllerNode.getDescription() == null) {
            controllerNode.setDescription(c.getNameAsString());
        }
    }
 
Example #30
Source File: RefactoringHelperTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
@Test
public void testGetAllClassesAndInterfacesFromFile() throws FileNotFoundException {
	// arrange
	String filePath = getTestResourcesFile().getAbsolutePath();

	// act
	List<ClassOrInterfaceDeclaration> allClassesAndInterfacesOfFile = RefactoringHelper
			.getAllClassesAndInterfacesFromFile(filePath);

	// assert
	assertThat(allClassesAndInterfacesOfFile).hasSize(2);
}