Search in sources :

Example 41 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project AutoRefactor by JnRouvignac.

the class TypeNameDecider method getImportedTypes.

private static TreeSet<String> getImportedTypes(final CompilationUnit cu) {
    TreeSet<String> results = new TreeSet<>();
    for (ImportDeclaration importDecl : (List<ImportDeclaration>) cu.imports()) {
        Name importName = importDecl.getName();
        results.add(importName.getFullyQualifiedName());
    }
    return results;
}
Also used : TreeSet(java.util.TreeSet) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) List(java.util.List) Name(org.eclipse.jdt.core.dom.Name)

Example 42 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project flow by vaadin.

the class CodeTest method gwtGenerics.

private static void gwtGenerics(File file) throws IOException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    String value = FileUtils.readFileToString(file, UTF_8);
    parser.setSource(value.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {

        Set<String> imports = new HashSet<>();

        String packageName;

        @Override
        public boolean visit(PackageDeclaration node) {
            packageName = node.getName().toString();
            return false;
        }

        @Override
        public boolean visit(ImportDeclaration node) {
            imports.add(node.getName().toString());
            return false;
        }

        @Override
        public boolean visit(VariableDeclarationStatement node) {
            for (Object frament : node.fragments()) {
                if (frament instanceof VariableDeclarationFragment) {
                    VariableDeclarationFragment variableDeclaration = (VariableDeclarationFragment) frament;
                    Expression expression = variableDeclaration.getInitializer();
                    if (expression instanceof ClassInstanceCreation) {
                        ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression;
                        Class<?> typeClass = getClass(node.getType());
                        Class<?> instanceClass = getClass(classInstanceCreation.getType());
                        if (typeClass != instanceClass && typeClass.isAssignableFrom(instanceClass)) {
                            fail("Variable type must be the specific implementation in " + node + " in " + file.getName());
                        }
                    }
                }
            }
            return false;
        }

        private Class<?> getClass(Type type) {
            if (type instanceof ArrayType) {
                type = ((ArrayType) type).getElementType();
            }
            if (type instanceof ParameterizedType) {
                type = ((ParameterizedType) type).getType();
            }
            String className = type.toString();
            if (className.indexOf('.') == -1) {
                String dotPrefix = '.' + className;
                for (String i : imports) {
                    if (i.endsWith(dotPrefix)) {
                        className = i;
                        break;
                    }
                }
            }
            Class<?> clas = getClass(className);
            if (clas != null) {
                return clas;
            }
            clas = getClass("java.lang." + className);
            if (clas != null) {
                return clas;
            }
            try {
                String fileName = file.getName();
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
                if (fileName.equals(className)) {
                    return Class.forName(packageName + '.' + fileName);
                }
                clas = getClass(packageName + '.' + className);
                if (clas != null) {
                    return clas;
                }
                return Class.forName(packageName + '.' + fileName + '$' + className);
            } catch (ClassNotFoundException e) {
                fail("Could not load class " + e);
                return null;
            }
        }

        private Class<?> getClass(String className) {
            try {
                return ClassUtils.getClass(className);
            } catch (ClassNotFoundException e) {
                return null;
            }
        }
    });
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Type(org.eclipse.jdt.core.dom.Type) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTParser(org.eclipse.jdt.core.dom.ASTParser) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) HashSet(java.util.HashSet)

Example 43 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project eap-additional-testsuite by jboss-set.

the class MethodInfo method parse.

public static void parse(String str) throws IOException {
    types.clear();
    fields.clear();
    methods.clear();
    classInstanceCreations.clear();
    typesNotResolved.clear();
    methodsNotResolved.clear();
    methodInvocations.clear();
    imports.clear();
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(readFileToString(str).toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    HashMap<String, String> declarations = new HashMap();
    cu.accept(new ASTVisitor() {

        Set names = new HashSet();

        int blockCount = 0;

        public boolean visit(FieldDeclaration node) {
            String name = node.fragments().get(0).toString().split("=")[0].trim();
            String type = node.getType().toString();
            declarations.put(name, type);
            if (!node.modifiers().toString().contains("private")) {
                fields.put(name, type);
            }
            ArrayList<String> types0 = new ArrayList<>();
            String type2 = null;
            do {
                if (type.contains("[")) {
                    type = type.replaceAll("\\[\\]", "");
                    if (type.contains("[")) {
                        type = type.substring(0, type.indexOf("["));
                    }
                }
                if (type.contains("<")) {
                    String type3 = type;
                    type = type.substring(0, type.indexOf("<"));
                    if (type3.substring(type3.indexOf("<") + 1).startsWith("<>") || type3.substring(type.indexOf("<") + 1).startsWith("<T>")) {
                        type2 = null;
                    } else {
                        type2 = type3.substring(type3.indexOf("<") + 1, type3.lastIndexOf(">"));
                        if (type2.contains(",")) {
                            if (type2.substring(0, type2.indexOf(",")).contains("<")) {
                                types0.add(type2);
                            } else {
                                types0.add(type2.substring(0, type2.indexOf(",")));
                                types0.add(type2.substring(type2.indexOf(",") + 1));
                            }
                        } else {
                            types0.add(type2);
                        }
                    }
                }
                types.addAll(Arrays.asList(type.split(" extends ")));
                if (types0.size() != 0) {
                    type = types0.remove(0);
                } else {
                    type = null;
                }
            } while (type != null);
            return false;
        }

        public boolean visit(EnumConstantDeclaration node) {
            String type = node.getName().toString();
            // System.out.println("ccccc : " + type);
            List<String> constants = node.arguments();
            for (String f : constants) {
                // System.out.println("ccccc : " + type + "." + f);
                declarations.put(type + "." + f, type);
                if (!node.modifiers().toString().contains("private")) {
                    fields.put(type + "." + f, type);
                }
            }
            return false;
        }

        public boolean visit(MethodDeclaration node) {
            if (node.getName().getIdentifier() != null) {
                String returnType = null;
                if (node.getReturnType2() == null) {
                    returnType = "";
                } else {
                    returnType = node.getReturnType2().toString();
                }
                HashMap<String, String> bDeclarations = new HashMap();
                bDeclarations.putAll(importedClassFields);
                bDeclarations.putAll(declarations);
                methods.put(node.getName().toString() + "_Return_Type", new String[] { returnType });
                String[] methodParams = new String[node.parameters().size()];
                List params = node.parameters();
                int i = 0;
                for (Object s : params) {
                    String type = ((SingleVariableDeclaration) s).getType().toString();
                    bDeclarations.put(((SingleVariableDeclaration) s).getName().toString(), type);
                    ArrayList<String> types0 = new ArrayList<>();
                    String type2 = null;
                    String typeF = null;
                    do {
                        if (type.contains("[")) {
                            type = type.replaceAll("\\[\\]", "");
                            if (type.contains("[")) {
                                type = type.substring(0, type.indexOf("["));
                            }
                        } else if (type.contains("<")) {
                            String type3 = type;
                            type = type.substring(0, type.indexOf("<"));
                            if (type3.substring(type3.indexOf("<") + 1).startsWith("<>") || type3.substring(type.indexOf("<") + 1).startsWith("<T>")) {
                                type2 = null;
                            } else {
                                type2 = type3.substring(type3.indexOf("<") + 1, type3.lastIndexOf(">"));
                                if (type2.contains(",")) {
                                    if (type2.substring(0, type2.indexOf(",")).contains("<")) {
                                        types0.add(type2);
                                    } else {
                                        types0.add(type2.substring(0, type2.indexOf(",")));
                                        types0.add(type2.substring(type2.indexOf(",") + 1));
                                    }
                                } else {
                                    types0.add(type2);
                                }
                            }
                        }
                        types.addAll(Arrays.asList(type.split(" extends ")));
                        if (types0.size() != 0) {
                            type = types0.remove(0);
                            typeF = type;
                        } else {
                            type = null;
                        }
                    } while (type != null);
                    methodParams[i++] = typeF;
                }
                methods.put(node.getName().toString() + "_Return_Type", methodParams);
                Block block = node.getBody();
                blockIterate(block, cu, bDeclarations);
            }
            return false;
        }

        public boolean visit(ImportDeclaration node) {
            imports.add(node.getName().toString());
            if (DependencyTreeMethods.jarClassPaths.containsKey(node.getName().toString())) {
                importedClassFields = DependencyTreeMethods.listFieldsOfJarClass(DependencyTreeMethods.jarClassPaths.get(node.getName().toString()), node.getName().toString());
                fields.putAll(importedClassFields);
            }
            return false;
        }

        public boolean visit(PackageDeclaration node) {
            packageName = node.getName().toString();
            return true;
        }
    });
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ArrayList(java.util.ArrayList) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) Block(org.eclipse.jdt.core.dom.Block) ArrayList(java.util.ArrayList) List(java.util.List) ASTParser(org.eclipse.jdt.core.dom.ASTParser) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) HashSet(java.util.HashSet)

Example 44 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project evosuite by EvoSuite.

the class TestExtensionJob method run.

@Override
protected IStatus run(IProgressMonitor monitor) {
    IStatus status = super.run(monitor);
    newTests.clear();
    IJavaElement element = JavaCore.create(target);
    if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
        ICompilationUnit compilationUnit = (ICompilationUnit) element;
        CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
        try {
            if (compilationUnit.getTypes().length == 0) {
                System.out.println("The compilation unit is empty :|");
                return status;
            }
            IType classType = compilationUnit.getTypes()[0];
            // new tests
            loadTestSuiteContent(getTestClassName());
            for (ImportDeclaration newImport : newImports) {
                if (!hasImport(compilationUnit, newImport)) {
                    int flag = newImport.isStatic() ? Flags.AccStatic : Flags.AccDefault;
                    String strImport = newImport.getName().toString();
                    // Names of onDemand import declarations do not contain the '*'
                    if (newImport.isOnDemand())
                        strImport += ".*";
                    compilationUnit.createImport(strImport, null, flag, null);
                }
            }
            for (MethodDeclaration newMethod : newMethods) {
                if (hasMethod(classType, newMethod.getName().toString())) {
                    System.out.println("Test suite already contains method called: " + newMethod.getName());
                    int num = 1;
                    newMethod.setName(newMethod.getAST().newSimpleName(newMethod.getName().toString() + "_" + num));
                    while (hasMethod(classType, newMethod.getName().toString())) {
                        num += 1;
                        String name = newMethod.getName().toString();
                        newMethod.setName(newMethod.getAST().newSimpleName(name.substring(0, name.length() - 2) + "_" + num));
                    }
                }
                String testContent = newMethod.toString();
                IMethod methodToAdd = classType.createMethod(testContent, null, false, new NullProgressMonitor());
                ISourceRange range = methodToAdd.getSourceRange();
                TextEdit indent_edit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, classType.getCompilationUnit().getSource(), range.getOffset(), range.getLength(), 0, null);
                classType.getCompilationUnit().applyTextEdit(indent_edit, null);
                newTests.add(newMethod.getName().toString());
            }
            classType.getCompilationUnit().commitWorkingCopy(false, null);
            // write markers
            writeMarkersExtendedTestSuite();
        } catch (JavaModelException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return status;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IStatus(org.eclipse.core.runtime.IStatus) JavaModelException(org.eclipse.jdt.core.JavaModelException) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IOException(java.io.IOException) IType(org.eclipse.jdt.core.IType) CodeFormatter(org.eclipse.jdt.core.formatter.CodeFormatter) TextEdit(org.eclipse.text.edits.TextEdit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) IImportDeclaration(org.eclipse.jdt.core.IImportDeclaration) IMethod(org.eclipse.jdt.core.IMethod) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 45 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project evosuite by EvoSuite.

the class ResolutionMarkerEvoIgnoreForClass method run.

@Override
public void run(IMarker marker) {
    IResource res = marker.getResource();
    try {
        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);
        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 0) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }
        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);
        Annotation annotation = ast.newNormalAnnotation();
        annotation.setTypeName(ast.newName("EvoIgnore"));
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore"));
        ListRewrite lr = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
        // lr.insertFirst(annotation, null);
        lr.insertAt(annotation, 0, null);
        lr.insertAt(id, 0, null);
        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        // (4)
        }
        System.out.println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        marker.delete();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) JavaModelException(org.eclipse.jdt.core.JavaModelException) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IOException(java.io.IOException) Annotation(org.eclipse.jdt.core.dom.Annotation) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

ImportDeclaration (org.eclipse.jdt.core.dom.ImportDeclaration)55 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)21 List (java.util.List)20 ArrayList (java.util.ArrayList)17 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)16 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)14 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)14 ASTNode (org.eclipse.jdt.core.dom.ASTNode)13 Block (org.eclipse.jdt.core.dom.Block)11 Name (org.eclipse.jdt.core.dom.Name)11 ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)10 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)10 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)10 TIntArrayList (gnu.trove.list.array.TIntArrayList)9 HashSet (java.util.HashSet)9 PackageDeclaration (org.eclipse.jdt.core.dom.PackageDeclaration)9 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)8 SimpleName (org.eclipse.jdt.core.dom.SimpleName)8 JavaModelException (org.eclipse.jdt.core.JavaModelException)7 QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)7