Search in sources :

Example 6 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project eap-additional-testsuite by jboss-set.

the class ParsedTests method readInternalClassMethods.

private static void readInternalClassMethods(String file, FileData fd) throws IOException {
    InputStream in = null;
    CompilationUnit cu = null;
    try {
        in = new FileInputStream(file);
        cu = JavaParser.parse(in);
        if (internalClassMethods.get(fd.packageName.replaceAll("/", ".") + "." + fd.fileName.replaceAll("\\.java", "")) == null) {
            internalClassMethods.put(fd.packageName.replaceAll("/", ".") + "." + fd.fileName.replaceAll("\\.java", ""), new HashMap<String, ArrayList<String[]>>());
        }
        NodeList<TypeDeclaration<?>> types = cu.getTypes();
        for (TypeDeclaration<?> type : types) {
            NodeList<BodyDeclaration<?>> members = type.getMembers();
            for (BodyDeclaration<?> member : members) {
                if (member instanceof MethodDeclaration) {
                    MethodDeclaration method = (MethodDeclaration) member;
                    HashMap<String, ArrayList<String[]>> arg = internalClassMethods.get(fd.packageName.replaceAll("/", ".") + "." + fd.fileName.replaceAll("\\.java", ""));
                    // System.out.println("yyy " + method.getParameters().size() + " " + method.getParameters());
                    String[] params = new String[method.getParameters().size()];
                    for (int i = 0; i < method.getParameters().size(); i++) {
                        params[i] = method.getParameters().get(i).getTypeAsString();
                    }
                    if (!arg.keySet().contains(method.getName().toString())) {
                        ArrayList<String[]> paramArrayList = new ArrayList<>();
                        paramArrayList.add(params);
                        arg.put(method.getName().toString(), paramArrayList);
                        ArrayList<String[]> paramRTArrayList = new ArrayList<>();
                        paramRTArrayList.add(new String[] { method.getTypeAsString() });
                        arg.put(method.getName().toString() + "_Return_Type", paramRTArrayList);
                    } else {
                        arg.get(method.getName().toString()).add(params);
                        arg.get(method.getName().toString() + "_Return_Type").add(new String[] { method.getTypeAsString() });
                    }
                }
                if (member instanceof ConstructorDeclaration) {
                    ConstructorDeclaration construct = (ConstructorDeclaration) member;
                    HashMap<String, ArrayList<String[]>> arg = internalClassMethods.get(fd.packageName.replaceAll("/", ".") + "." + fd.fileName.replaceAll("\\.java", ""));
                    String[] params = new String[construct.getParameters().size()];
                    for (int i = 0; i < construct.getParameters().size(); i++) {
                        params[i] = construct.getParameters().get(i).getTypeAsString();
                    }
                    if (!arg.keySet().contains(construct.getName().toString() + "_Constructor")) {
                        ArrayList<String[]> paramCTArrayList = new ArrayList<>();
                        paramCTArrayList.add(params);
                        arg.put(construct.getName().toString() + "_Constructor", paramCTArrayList);
                    } else {
                        arg.get(construct.getName().toString() + "_Constructor").add(params);
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        in.close();
    }
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ArrayList(java.util.ArrayList) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration)

Example 7 with TypeDeclaration

use of com.github.javaparser.ast.body.TypeDeclaration in project eap-additional-testsuite by jboss-set.

the class ParsedTests method readInternalClassFields.

private static void readInternalClassFields(String file, FileData fd) throws IOException {
    InputStream in = null;
    CompilationUnit cu = null;
    try {
        in = new FileInputStream(file);
        cu = JavaParser.parse(in);
        if (internalClassFields.get(fd.packageName.replaceAll("/", ".") + "." + fd.fileName.replaceAll("\\.java", "")) == null) {
            internalClassFields.put(fd.packageName.replaceAll("/", ".") + "." + fd.fileName.replaceAll("\\.java", ""), new HashMap<String, String>());
        }
        NodeList<TypeDeclaration<?>> types = cu.getTypes();
        for (TypeDeclaration<?> type : types) {
            NodeList<BodyDeclaration<?>> members = type.getMembers();
            for (BodyDeclaration<?> member : members) {
                if (member instanceof FieldDeclaration) {
                    FieldDeclaration field = (FieldDeclaration) member;
                    HashMap<String, String> arg = internalClassFields.get(fd.packageName.replaceAll("/", ".") + "." + fd.fileName.replaceAll("\\.java", ""));
                    if (!field.getModifiers().contains("private")) {
                        arg.put(field.getVariables().get(0).getName().toString(), field.getVariables().get(0).getType().toString());
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        in.close();
    }
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileInputStream(java.io.FileInputStream) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration)

Example 8 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 9 with TypeDeclaration

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

the class FinalRClassBuilder method brewJava.

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);
}
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 10 with TypeDeclaration

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

the class LocationSearcher method searchLocationFromFile.

@SuppressWarnings("try")
private static Location searchLocationFromFile(final SearchContext ctx, final String fqcn, final File targetFile) throws IOException {
    try (TelemetryUtils.ScopedSpan scope = TelemetryUtils.startScopedSpan("LocationSearcher.searchLocationFromFile")) {
        TelemetryUtils.ScopedSpan.addAnnotation(TelemetryUtils.annotationBuilder().put("fqcn", fqcn).put("targetFile", targetFile.getPath()).build("args"));
        CompilationUnit compilationUnit;
        try {
            compilationUnit = StaticJavaParser.parse(targetFile);
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
            return new Location(targetFile.getCanonicalPath(), 0, 0);
        }
        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) TelemetryUtils(meghanada.telemetry.TelemetryUtils) 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)44 CompilationUnit (com.github.javaparser.ast.CompilationUnit)22 Node (com.github.javaparser.ast.Node)14 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)13 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)12 BodyDeclaration (com.github.javaparser.ast.body.BodyDeclaration)10 ResolvedReferenceTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration)8 List (java.util.List)8 Optional (java.util.Optional)8 ResolvedTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration)6 SymbolReference (com.github.javaparser.symbolsolver.model.resolution.SymbolReference)6 Collectors (java.util.stream.Collectors)6 ImportDeclaration (com.github.javaparser.ast.ImportDeclaration)5 NodeList (com.github.javaparser.ast.NodeList)5 ConstructorDeclaration (com.github.javaparser.ast.body.ConstructorDeclaration)5 EnumDeclaration (com.github.javaparser.ast.body.EnumDeclaration)5 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)5 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)5 ResolvedValueDeclaration (com.github.javaparser.resolution.declarations.ResolvedValueDeclaration)5 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)5