Search in sources :

Example 1 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project structr by structr.

the class JavaParserModule method parseJavaFilesAndSolveTypes.

private void parseJavaFilesAndSolveTypes(final Folder folder) {
    if (ignoreTests && "test".equals(folder.getName())) {
        return;
    }
    for (final File file : folder.getFiles()) {
        if (file.getContentType().equals("text/x-java")) {
            final String javaFileName = file.getName();
            if (javaFileName.equals("package-info.java") || javaFileName.equals("testPackage-info.java")) {
            } else {
                final String javaContent = file.getFavoriteContent();
                ClassOrInterface clsOrIface = null;
                CompilationUnit cu = null;
                try {
                    cu = JavaParser.parse(javaContent);
                    for (final TypeDeclaration type : cu.findAll(TypeDeclaration.class)) {
                        SymbolReference<? extends ResolvedValueDeclaration> decl = facade.solve(type.getName());
                        if (type.isClassOrInterfaceDeclaration()) {
                            org.structr.javaparser.entity.Package pkg = null;
                            if (cu.getPackageDeclaration().isPresent()) {
                                pkg = handlePackage(cu.getPackageDeclaration().get());
                            }
                            clsOrIface = handleClassOrInterface(type, pkg);
                        }
                    }
                    for (final BodyDeclaration t : cu.findAll(BodyDeclaration.class)) {
                        if (t instanceof CallableDeclaration) {
                            final CallableDeclaration callable = t.asCallableDeclaration();
                            if (t instanceof ConstructorDeclaration) {
                            // final ConstructorDeclaration cd = t.asConstructorDeclaration();
                            // logger.info("Constructor found: " + cd.getNameAsString());
                            // 
                            // final SymbolReference<ResolvedReferenceTypeDeclaration> constructorRef = typeSolver.tryToSolveType(cd.getNameAsString());
                            // if (constructorRef.isSolved()) {
                            // 
                            // logger.info("Solved constructor: " + cd.getNameAsString());
                            // //final ResolvedReferenceTypeDeclaration decl = constructorRef.getCorrespondingDeclaration();
                            // }
                            } else if (t instanceof MethodDeclaration) {
                                final MethodDeclaration md = t.asMethodDeclaration();
                                final String methodName = md.getNameAsString();
                                logger.info("Method found: " + methodName);
                                // Create methods and link to class
                                final PropertyMap identifyingMethodProperties = new PropertyMap();
                                identifyingMethodProperties.put(Method.name, methodName);
                                final PropertyMap methodProperties = new PropertyMap();
                                methodProperties.putAll(identifyingMethodProperties);
                                methodProperties.put(Method.classOrInterface, clsOrIface);
                                methodProperties.put(Method.declaration, md.getDeclarationAsString());
                                final Optional<BlockStmt> block = md.getBody();
                                if (block.isPresent()) {
                                    methodProperties.put(Method.body, block.get().toString());
                                }
                                final String symbolName = StringUtils.substringAfterLast(clsOrIface.getName(), ".") + "." + md.getNameAsString();
                                try {
                                    final SymbolReference<? extends ResolvedValueDeclaration> methodRef = facade.solve(md.getName());
                                    if (methodRef.isSolved()) {
                                        final ResolvedValueDeclaration decl = methodRef.getCorrespondingDeclaration();
                                        if (decl.isMethod()) {
                                            final String mName = decl.asMethod().getName();
                                            final String signature = decl.asMethod().getSignature();
                                            logger.info("Solved method: " + methodRef.toString() + ", signature: " + signature);
                                            methodProperties.put(Method.resolved, true);
                                        }
                                    }
                                } catch (final UnsolvedSymbolException ignore) {
                                }
                                getOrCreate(Method.class, identifyingMethodProperties, methodProperties);
                                logger.info("Created (or found) method " + symbolName);
                            }
                        // final NodeList<Parameter> parameters = callable.getParameters();
                        // 
                        // List<JsonResult> parameterList = new ArrayList<>();
                        // 
                        // parameters.forEach((p) -> {
                        // 
                        // JsonResult param = new JsonResult();
                        // 
                        // param.addName(p);
                        // param.addType(p.getType());
                        // param.addModifiers(p);
                        // 
                        // parameterList.add(param);
                        // });
                        }
                    }
                } catch (Throwable ignore) {
                }
            }
        }
    }
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) UnsolvedSymbolException(com.github.javaparser.symbolsolver.javaparsermodel.UnsolvedSymbolException) ClassOrInterface(org.structr.javaparser.entity.ClassOrInterface) Package(org.structr.javaparser.entity.Package) Optional(java.util.Optional) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) Method(org.structr.javaparser.entity.Method) PropertyMap(org.structr.core.property.PropertyMap) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) File(org.structr.web.entity.File) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration)

Example 2 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project structr by structr.

the class JavaParserModule method toJson.

private JsonResult toJson(final CompilationUnit cu) {
    final JsonResult jsonResult = new JsonResult();
    final NodeList<TypeDeclaration<?>> types = cu.getTypes();
    if (types.isEmpty()) {
        return jsonResult;
    }
    final TypeDeclaration<?> type = types.get(0);
    jsonResult.addName(type);
    jsonResult.addModifiers(type);
    final Optional<PackageDeclaration> pkg = cu.getPackageDeclaration();
    if (pkg.isPresent()) {
        jsonResult.addPackage(pkg.get());
    }
    final List<BodyDeclaration<?>> members = type.getMembers();
    final List<JsonResult> membersList = new ArrayList<>();
    members.forEach((t) -> {
        final JsonResult member = new JsonResult();
        if (t instanceof FieldDeclaration) {
            final FieldDeclaration fd = t.asFieldDeclaration();
            member.addName(fd.getVariable(0));
            member.addType(fd.getVariable(0).getType());
            member.addModifiers(fd);
        } else if (t instanceof CallableDeclaration) {
            final CallableDeclaration callable = t.asCallableDeclaration();
            if (t instanceof ConstructorDeclaration) {
                final ConstructorDeclaration cd = t.asConstructorDeclaration();
                member.addName(cd);
                member.isConstructor();
                member.addModifiers(cd);
            } else if (t instanceof MethodDeclaration) {
                final MethodDeclaration md = t.asMethodDeclaration();
                member.addName(md);
                member.isMethod();
                member.addReturnType(md.getType());
                member.addModifiers(md);
                member.addBody(md);
            }
            final NodeList<Parameter> parameters = callable.getParameters();
            List<JsonResult> parameterList = new ArrayList<>();
            parameters.forEach((p) -> {
                JsonResult param = new JsonResult();
                param.addName(p);
                param.addType(p.getType());
                param.addModifiers(p);
                parameterList.add(param);
            });
            member.addParameters(parameterList);
        }
        membersList.add(member);
    });
    jsonResult.addMembers(membersList);
    return jsonResult;
}
Also used : JsonObject(com.google.gson.JsonObject) Package(org.structr.javaparser.entity.Package) XPathExpressionException(javax.xml.xpath.XPathExpressionException) UnsolvedSymbolException(com.github.javaparser.symbolsolver.javaparsermodel.UnsolvedSymbolException) LoggerFactory(org.slf4j.LoggerFactory) SecurityContext(org.structr.common.SecurityContext) StringUtils(org.apache.commons.lang3.StringUtils) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) Actions(org.structr.schema.action.Actions) FrameworkException(org.structr.common.error.FrameworkException) App(org.structr.core.app.App) NodeWithSimpleName(com.github.javaparser.ast.nodeTypes.NodeWithSimpleName) Type(com.github.javaparser.ast.type.Type) Document(org.w3c.dom.Document) Map(java.util.Map) CompilationUnit(com.github.javaparser.ast.CompilationUnit) JavaInterface(org.structr.javaparser.entity.JavaInterface) NodeList(com.github.javaparser.ast.NodeList) Folder(org.structr.web.entity.Folder) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) Set(java.util.Set) GraphObject(org.structr.core.GraphObject) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) Functions(org.structr.core.function.Functions) JsonArray(com.google.gson.JsonArray) List(java.util.List) StructrModule(org.structr.module.StructrModule) JarTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver) SAXException(org.xml.sax.SAXException) LicenseManager(org.structr.api.service.LicenseManager) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) QName(javax.xml.namespace.QName) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeWithOptionalBlockStmt(com.github.javaparser.ast.nodeTypes.NodeWithOptionalBlockStmt) StructrApp(org.structr.core.app.StructrApp) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) Method(org.structr.javaparser.entity.Method) PackageDeclaration(com.github.javaparser.ast.PackageDeclaration) XPath(javax.xml.xpath.XPath) XPathConstants(javax.xml.xpath.XPathConstants) Parameter(com.github.javaparser.ast.body.Parameter) HashMap(java.util.HashMap) CombinedTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver) ArrayList(java.util.ArrayList) PropertyMap(org.structr.core.property.PropertyMap) File(org.structr.web.entity.File) JavaClass(org.structr.javaparser.entity.JavaClass) JsonPrimitive(com.google.gson.JsonPrimitive) ClassOrInterface(org.structr.javaparser.entity.ClassOrInterface) LinkedHashSet(java.util.LinkedHashSet) InputSource(org.xml.sax.InputSource) Logger(org.slf4j.Logger) NodeWithModifiers(com.github.javaparser.ast.nodeTypes.NodeWithModifiers) Files(java.nio.file.Files) AbstractSchemaNode(org.structr.core.entity.AbstractSchemaNode) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) AddJarsToIndexFunction(org.structr.javaparser.entity.AddJarsToIndexFunction) AtomicLong(java.util.concurrent.atomic.AtomicLong) XPathFactory(javax.xml.xpath.XPathFactory) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) StringReader(java.io.StringReader) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) Paths(java.nio.file.Paths) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) Module(org.structr.javaparser.entity.Module) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) NodeList(com.github.javaparser.ast.NodeList) ArrayList(java.util.ArrayList) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) NodeList(com.github.javaparser.ast.NodeList) List(java.util.List) ArrayList(java.util.ArrayList) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) PackageDeclaration(com.github.javaparser.ast.PackageDeclaration)

Example 3 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project AndroidLife by CaMnter.

the class FinalRClassBuilder method brewJava.

/**
 * JavaPoet 生成 R2
 *
 * @param rFile R.java File
 * @param outputDir R2.java 输出文件夹
 * @param packageName 包名
 * @param className R2 name
 * @throws Exception
 */
public static void brewJava(File rFile, File outputDir, String packageName, String className) throws Exception {
    /*
     * JavaParser 解析 R.java File
     * 获取到 TypeDeclaration
     */
    CompilationUnit compilationUnit = JavaParser.parse(rFile);
    TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);
    /*
     * 定义 R2.java class
     */
    TypeSpec.Builder result = TypeSpec.classBuilder(className).addModifiers(PUBLIC).addModifiers(FINAL);
    /*
     * 遍历 R.java File 的每一个节点( 内部类或者接口 --> ClassOrInterfaceDeclaration )
     * 添加到 R2.java 内
     * 这里是给 TypeSpec 添加生成 内部类 的 语句
     */
    for (Node node : resourceClass.getChildNodes()) {
        if (node instanceof ClassOrInterfaceDeclaration) {
            addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node);
        }
    }
    JavaFile finalR = JavaFile.builder(packageName, result.build()).addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!").build();
    finalR.writeTo(outputDir);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Node(com.github.javaparser.ast.Node) JavaFile(com.squareup.javapoet.JavaFile) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 4 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project cloud-sea-towerman by huadahuang1983.

the class JavaFileMergerJaxp method mergerFile.

public String mergerFile(CompilationUnit newCompilationUnit, CompilationUnit existingCompilationUnit) {
    StringBuilder sb = new StringBuilder(newCompilationUnit.getPackageDeclaration().get().toString());
    newCompilationUnit.removePackageDeclaration();
    // 合并imports
    NodeList<ImportDeclaration> imports = newCompilationUnit.getImports();
    imports.addAll(existingCompilationUnit.getImports());
    Set<ImportDeclaration> importSet = new HashSet<ImportDeclaration>();
    importSet.addAll(imports);
    NodeList<ImportDeclaration> newImports = new NodeList<>();
    newImports.addAll(importSet);
    newCompilationUnit.setImports(newImports);
    for (ImportDeclaration i : newCompilationUnit.getImports()) {
        sb.append(i.toString());
    }
    newLine(sb);
    NodeList<TypeDeclaration<?>> types = newCompilationUnit.getTypes();
    NodeList<TypeDeclaration<?>> oldTypes = existingCompilationUnit.getTypes();
    for (int i = 0; i < types.size(); i++) {
        // 截取Class
        String classNameInfo = types.get(i).toString().substring(0, types.get(i).toString().indexOf("{") + 1);
        sb.append(classNameInfo);
        newLine(sb);
        newLine(sb);
        // 合并fields
        List<FieldDeclaration> fields = types.get(i).getFields();
        List<FieldDeclaration> oldFields = oldTypes.get(i).getFields();
        List<FieldDeclaration> newFields = new ArrayList<>();
        Set<FieldDeclaration> fieldDeclarations = new LinkedHashSet<>();
        fieldDeclarations.addAll(fields);
        fieldDeclarations.addAll(oldFields);
        newFields.addAll(fieldDeclarations);
        for (FieldDeclaration f : newFields) {
            sb.append("\t" + f.toString());
            newLine(sb);
            newLine(sb);
        }
        // 合并methods
        List<MethodDeclaration> methods = types.get(i).getMethods();
        List<MethodDeclaration> existingMethods = oldTypes.get(i).getMethods();
        Set<MethodDeclaration> methodDeclarations = new LinkedHashSet<>();
        methodDeclarations.addAll(methods);
        methodDeclarations.addAll(existingMethods);
        for (MethodDeclaration f : methodDeclarations) {
            String res = f.toString().replaceAll("\r\n", "\r\n\t");
            sb.append("\t" + res);
            newLine(sb);
            newLine(sb);
        }
        // 判断是否有内部类
        types.get(i).getChildNodes();
        for (Node n : types.get(i).getChildNodes()) {
            if (n.toString().contains("static class")) {
                sb.append(n.toString());
            }
        }
    }
    return sb.append(System.getProperty("line.separator") + "}").toString();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) NodeList(com.github.javaparser.ast.NodeList) Node(com.github.javaparser.ast.Node) ArrayList(java.util.ArrayList) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project meghanada-server by mopemope.

the class LocationSearcher method searchLocationFromFile.

private static Location searchLocationFromFile(final SearchContext ctx, final String fqcn, final File targetFile) throws IOException {
    final CompilationUnit compilationUnit = JavaParser.parse(targetFile, StandardCharsets.UTF_8);
    final List<TypeDeclaration<?>> types = compilationUnit.getTypes();
    for (final TypeDeclaration<?> type : types) {
        if (ctx.kind.equals(SearchKind.CLASS)) {
            final SimpleName simpleName = type.getName();
            final String typeName = simpleName.getIdentifier();
            final String name = ClassNameUtils.getSimpleName(fqcn);
            final Optional<Position> begin = simpleName.getBegin();
            if (typeName.equals(name) && begin.isPresent()) {
                final Position position = begin.get();
                return new Location(targetFile.getCanonicalPath(), position.line, position.column);
            }
        }
        final List<BodyDeclaration<?>> members = type.getMembers();
        ConstructorDeclaration constructor = null;
        MethodDeclaration method = null;
        for (final BodyDeclaration<?> member : members) {
            if (member instanceof FieldDeclaration && ctx.name != null && ctx.kind.equals(SearchKind.FIELD)) {
                final Location variable = getFieldLocation(ctx, targetFile, (FieldDeclaration) member);
                if (variable != null) {
                    return variable;
                }
            } else if (member instanceof ConstructorDeclaration && ctx.name != null && ctx.kind.equals(SearchKind.METHOD)) {
                final ConstructorDeclaration declaration = (ConstructorDeclaration) member;
                final SimpleName simpleName = declaration.getName();
                final String name = simpleName.getIdentifier();
                final Optional<Position> begin = simpleName.getBegin();
                if (name.equals(ctx.name) && begin.isPresent()) {
                    final Position position = begin.get();
                    final List<Parameter> parameters = declaration.getParameters();
                    // TODO check FQCN types
                    if (ctx.arguments.size() == parameters.size()) {
                        return new Location(targetFile.getCanonicalPath(), position.line, position.column);
                    } else {
                        if (constructor == null) {
                            constructor = declaration;
                        }
                    }
                }
            } else if (member instanceof MethodDeclaration && ctx.name != null && ctx.kind.equals(SearchKind.METHOD)) {
                final MethodDeclaration declaration = (MethodDeclaration) member;
                final SimpleName simpleName = declaration.getName();
                final String name = simpleName.getIdentifier();
                final Optional<Position> begin = simpleName.getBegin();
                if (name.equals(ctx.name) && begin.isPresent()) {
                    final Position position = begin.get();
                    final List<Parameter> parameters = declaration.getParameters();
                    if (ctx.arguments.size() == parameters.size()) {
                        return new Location(targetFile.getCanonicalPath(), position.line, position.column);
                    } else {
                        if (method == null) {
                            method = declaration;
                        }
                    }
                }
            }
        }
        if (constructor != null) {
            final Position pos = constructor.getName().getBegin().get();
            return new Location(targetFile.getCanonicalPath(), pos.line, pos.column);
        }
        if (method != null) {
            final Position pos = method.getName().getBegin().get();
            return new Location(targetFile.getCanonicalPath(), pos.line, pos.column);
        }
    }
    return null;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Optional(java.util.Optional) Position(com.github.javaparser.Position) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) SimpleName(com.github.javaparser.ast.expr.SimpleName) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) Parameter(com.github.javaparser.ast.body.Parameter) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) List(java.util.List) ArrayList(java.util.ArrayList) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration)

Aggregations

TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)21 CompilationUnit (com.github.javaparser.ast.CompilationUnit)12 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)7 BodyDeclaration (com.github.javaparser.ast.body.BodyDeclaration)6 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)5 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)5 ArrayList (java.util.ArrayList)5 Node (com.github.javaparser.ast.Node)4 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)4 LinkedHashSet (java.util.LinkedHashSet)4 List (java.util.List)4 Optional (java.util.Optional)4 ImportDeclaration (com.github.javaparser.ast.ImportDeclaration)3 NodeList (com.github.javaparser.ast.NodeList)3 PackageDeclaration (com.github.javaparser.ast.PackageDeclaration)3 EmptyTypeDeclaration (com.github.javaparser.ast.body.EmptyTypeDeclaration)3 Type (com.github.javaparser.ast.type.Type)3 FileInputStream (java.io.FileInputStream)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3