Search in sources :

Example 16 with ImportDeclaration

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

the class JUnitCodeGenerator method createGetFieldMethod.

@SuppressWarnings({ "rawtypes", "unchecked" })
private void createGetFieldMethod(final TypeDeclaration td, final CompilationUnit cu, final AST ast) {
    // public static void setField(final String clazzName, final String fieldName, final Object receiver, final Object value) throws Exception
    // {
    // final Class<?> clazz = Class.forName(clazzName);
    // final Field    f     = clazz.getDeclaredField(fieldName);
    // f.setAccessible(true);
    // f.set(receiver, value);
    // }
    // -- add necessary import statements
    List imports = cu.imports();
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "java", "lang", "reflect", "Field" }));
    imports.add(id);
    // -- create method frame: "public static Object setProtectedField(final String clazzName, final String fieldName, final Object receiver) throws Exception"
    final MethodDeclaration md = ast.newMethodDeclaration();
    td.bodyDeclarations().add(md);
    md.setName(ast.newSimpleName("getField"));
    List modifiers = md.modifiers();
    modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
    modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
    md.thrownExceptions().add(ast.newSimpleName("Exception"));
    List parameters = md.parameters();
    SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newSimpleType(ast.newSimpleName("String")));
    svd.setName(ast.newSimpleName("clazzName"));
    parameters.add(svd);
    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newSimpleType(ast.newSimpleName("String")));
    svd.setName(ast.newSimpleName("fieldName"));
    parameters.add(svd);
    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newSimpleType(ast.newSimpleName("Object")));
    svd.setName(ast.newSimpleName("receiver"));
    parameters.add(svd);
    md.setReturnType2(ast.newSimpleType(ast.newSimpleName("Object")));
    // -- create method body
    // final Class<?> clazz = Class.forName(clazzName);
    // final Field    f     = clazz.getDeclaredField(fieldName);
    // f.setAccessible(true);
    // return f.get(receiver);
    final Block methodBlock = ast.newBlock();
    md.setBody(methodBlock);
    final List methodStmts = methodBlock.statements();
    // final Class clazz = Class.forName(clazzName);
    MethodInvocation init = ast.newMethodInvocation();
    init.setName(ast.newSimpleName("forName"));
    init.setExpression(ast.newSimpleName("Class"));
    init.arguments().add(ast.newSimpleName("clazzName"));
    VariableDeclarationFragment varDeclFrag = ast.newVariableDeclarationFragment();
    varDeclFrag.setName(ast.newSimpleName("clazz"));
    varDeclFrag.setInitializer(init);
    VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
    varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Class")));
    methodStmts.add(varDeclStmt);
    // final Field f = clazz.getDeclaredField(fieldName);
    init = ast.newMethodInvocation();
    init.setName(ast.newSimpleName("getDeclaredField"));
    init.setExpression(ast.newSimpleName("clazz"));
    init.arguments().add(ast.newSimpleName("fieldName"));
    varDeclFrag = ast.newVariableDeclarationFragment();
    varDeclFrag.setName(ast.newSimpleName("f"));
    varDeclFrag.setInitializer(init);
    varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
    varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Field")));
    methodStmts.add(varDeclStmt);
    // f.setAccessible(true);
    MethodInvocation minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("setAccessible"));
    minv.setExpression(ast.newSimpleName("f"));
    minv.arguments().add(ast.newBooleanLiteral(true));
    methodStmts.add(ast.newExpressionStatement(minv));
    // return f.get(receiver);
    minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("get"));
    minv.setExpression(ast.newSimpleName("f"));
    minv.arguments().add(ast.newSimpleName("receiver"));
    final ReturnStatement returnStmt = ast.newReturnStatement();
    returnStmt.setExpression(minv);
    methodStmts.add(returnStmt);
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) TIntArrayList(gnu.trove.list.array.TIntArrayList) List(java.util.List) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation)

Example 17 with ImportDeclaration

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

the class JUnitCodeGenerator method before.

@SuppressWarnings("unchecked")
@Override
public void before(CaptureLog log) {
    ast = AST.newAST(AST.JLS3);
    cu = ast.newCompilationUnit();
    // package declaration
    final PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newName(packageName.split("\\.")));
    cu.setPackage(p1);
    // import specifications
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "org", "junit", "Test" }));
    cu.imports().add(id);
    // class declaration
    td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName(cuName));
    td.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    cu.types().add(td);
    // test method construction
    final MethodDeclaration md = ast.newMethodDeclaration();
    md.setName(ast.newSimpleName("test"));
    md.thrownExceptions().add(ast.newSimpleName("Exception"));
    // sets @Test annotation to test method
    final NormalAnnotation annotation = ast.newNormalAnnotation();
    annotation.setTypeName(ast.newSimpleName("Test"));
    md.modifiers().add(annotation);
    // sets method to public
    md.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    td.bodyDeclarations().add(md);
    methodBlock = ast.newBlock();
    md.setBody(methodBlock);
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration)

Example 18 with ImportDeclaration

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

the class AbstractBuildErrorDetailsHandler method createMethodMarkerData.

/**
 * Create a marker on a Java Method
 *
 * @param javaProject
 * @param className - the fully qualified class name (e.g java.lang.String)
 * @param methodName
 * @param methodSignature - signatures are in "internal form" e.g. (Ljava.lang.Integer;[Ljava/lang/String;Z)V
 * @param markerAttributes - attributes that should be included in the marker, typically a message. The start and
 *            end points for the marker are added by this method.
 * @param hasResolutions - true if the marker will have resolutions
 * @return Marker Data that can be used to create an {@link IMarker}, or null if no location can be found
 * @throws JavaModelException
 */
public static final MarkerData createMethodMarkerData(IJavaProject javaProject, final String className, final String methodName, final String methodSignature, final Map<String, Object> markerAttributes, boolean hasResolutions) throws JavaModelException {
    final CompilationUnit ast = createAST(javaProject, className);
    if (ast == null)
        return null;
    ast.accept(new ASTVisitor() {

        @Override
        public boolean visit(MethodDeclaration methodDecl) {
            if (matches(ast, methodDecl, methodName, methodSignature)) {
                // Create the marker attribs here
                markerAttributes.put(IMarker.CHAR_START, methodDecl.getStartPosition());
                markerAttributes.put(IMarker.CHAR_END, methodDecl.getStartPosition() + methodDecl.getLength());
            }
            return false;
        }

        private boolean matches(CompilationUnit ast, MethodDeclaration methodDecl, String methodName, String signature) {
            if ("<init>".equals(methodName)) {
                if (!methodDecl.isConstructor()) {
                    return false;
                }
            } else if (!methodDecl.getName().getIdentifier().equals(methodName)) {
                return false;
            }
            return getSignature(ast, methodDecl).equals(signature);
        }

        private String getSignature(CompilationUnit ast, MethodDeclaration methodDecl) {
            StringBuilder signatureBuilder = new StringBuilder("(");
            for (@SuppressWarnings("unchecked") Iterator<SingleVariableDeclaration> it = methodDecl.parameters().iterator(); it.hasNext(); ) {
                SingleVariableDeclaration decl = it.next();
                appendType(ast, signatureBuilder, decl.getType(), decl.getExtraDimensions());
            }
            signatureBuilder.append(")");
            appendType(ast, signatureBuilder, methodDecl.getReturnType2(), 0);
            return signatureBuilder.toString();
        }

        private void appendType(CompilationUnit ast, StringBuilder signatureBuilder, Type typeToAdd, int extraDimensions) {
            for (int i = 0; i < extraDimensions; i++) {
                signatureBuilder.append('[');
            }
            Type rovingType = typeToAdd;
            if (rovingType == null) {
                // A special return type for constructors, nice one Eclipse...
                signatureBuilder.append("V");
            } else {
                if (rovingType.isArrayType()) {
                    ArrayType type = (ArrayType) rovingType;
                    int depth = type.getDimensions();
                    for (int i = 0; i < depth; i++) {
                        signatureBuilder.append('[');
                    }
                    // We still need to add the array component type, which might be primitive or a reference
                    rovingType = type.getElementType();
                }
                // Type erasure means that we should ignore parameters
                if (rovingType.isParameterizedType()) {
                    rovingType = ((ParameterizedType) rovingType).getType();
                }
                if (rovingType.isPrimitiveType()) {
                    PrimitiveType type = (PrimitiveType) rovingType;
                    signatureBuilder.append(PRIMITIVES_TO_SIGNATURES.get(type.getPrimitiveTypeCode()));
                } else if (rovingType.isSimpleType()) {
                    SimpleType type = (SimpleType) rovingType;
                    String name;
                    if (type.getName().isQualifiedName()) {
                        name = type.getName().getFullyQualifiedName();
                    } else {
                        name = getFullyQualifiedNameForSimpleName(ast, type.getName());
                    }
                    name = name.replace('.', '/');
                    signatureBuilder.append("L").append(name).append(";");
                } else if (rovingType.isQualifiedType()) {
                    QualifiedType type = (QualifiedType) rovingType;
                    String name = type.getQualifier().toString().replace('.', '/') + '/' + type.getName().getFullyQualifiedName().replace('.', '/');
                    signatureBuilder.append("L").append(name).append(";");
                } else {
                    throw new IllegalArgumentException("We hit an unknown type " + rovingType);
                }
            }
        }

        private String getFullyQualifiedNameForSimpleName(CompilationUnit ast, Name typeName) {
            String name = typeName.getFullyQualifiedName();
            @SuppressWarnings("unchecked") List<ImportDeclaration> ids = ast.imports();
            for (ImportDeclaration id : ids) {
                if (id.isStatic())
                    continue;
                if (id.isOnDemand()) {
                    String packageName = id.getName().getFullyQualifiedName();
                    try {
                        if (ast.getJavaElement().getJavaProject().findType(packageName + "." + name) != null) {
                            name = packageName + '.' + name;
                        }
                    } catch (JavaModelException e) {
                    }
                } else {
                    String importName = id.getName().getFullyQualifiedName();
                    if (importName.endsWith("." + name)) {
                        name = importName;
                        break;
                    }
                }
            }
            if (name.indexOf('.') < 0) {
                try {
                    if (ast.getJavaElement().getJavaProject().findType(name) == null) {
                        name = "java.lang." + name;
                    }
                } catch (JavaModelException e) {
                }
            }
            return name;
        }
    });
    if (!markerAttributes.containsKey(IMarker.CHAR_START))
        return null;
    return new MarkerData(ast.getJavaElement().getResource(), markerAttributes, hasResolutions);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) JavaModelException(org.eclipse.jdt.core.JavaModelException) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) IType(org.eclipse.jdt.core.IType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) Iterator(java.util.Iterator) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) List(java.util.List)

Example 19 with ImportDeclaration

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

the class ImportPackageQuickFixProcessor method getPackageFromImportNotFound.

private Name getPackageFromImportNotFound(IInvocationContext context, IProblemLocation location) {
    ASTNode selectedNode = location.getCoveringNode(context.getASTRoot());
    if (selectedNode == null) {
        return null;
    }
    ImportDeclaration declaration = (ImportDeclaration) ((selectedNode instanceof ImportDeclaration) ? selectedNode : ASTNodes.getParent(selectedNode, ASTNode.IMPORT_DECLARATION));
    if (declaration == null) {
        return null;
    }
    Name name = declaration.getName();
    if (!name.isQualifiedName()) {
        if (!declaration.isOnDemand() || declaration.isStatic()) {
            return null;
        }
    } else if (declaration.isStatic()) {
        final QualifiedName qName = (QualifiedName) name;
        name = qName.getQualifier();
        if (declaration.isOnDemand()) {
        // return name;
        } else if (name.isQualifiedName()) {
            name = ((QualifiedName) name).getQualifier();
        } else {
            return null;
        }
    } else if (!declaration.isOnDemand()) {
        name = ((QualifiedName) name).getQualifier();
    }
    return skipClasses(name);
}
Also used : QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name)

Example 20 with ImportDeclaration

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

the class NewTypeWizardPage method removeUnusedImports.

private void removeUnusedImports(ICompilationUnit cu, Set<String> existingImports, boolean needsSave) throws CoreException {
    ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
    parser.setSource(cu);
    parser.setResolveBindings(true);
    CompilationUnit root = (CompilationUnit) parser.createAST(null);
    if (root.getProblems().length == 0) {
        return;
    }
    @SuppressWarnings("unchecked") List<ImportDeclaration> importsDecls = root.imports();
    if (importsDecls.isEmpty()) {
        return;
    }
    ImportsManager imports = new ImportsManager(root);
    int importsEnd = ASTNodes.getExclusiveEnd(importsDecls.get(importsDecls.size() - 1));
    IProblem[] problems = root.getProblems();
    for (int i = 0; i < problems.length; i++) {
        IProblem curr = problems[i];
        if (curr.getSourceEnd() < importsEnd) {
            int id = curr.getID();
            if (id == IProblem.UnusedImport || id == IProblem.NotVisibleType) {
                // not visible problems hide unused
                // -> remove both
                int pos = curr.getSourceStart();
                for (int k = 0; k < importsDecls.size(); k++) {
                    ImportDeclaration decl = importsDecls.get(k);
                    if (decl.getStartPosition() <= pos && pos < decl.getStartPosition() + decl.getLength()) {
                        if (existingImports.isEmpty() || !existingImports.contains(ASTNodes.asString(decl))) {
                            String name = decl.getName().getFullyQualifiedName();
                            if (decl.isOnDemand()) {
                                // $NON-NLS-1$
                                name += ".*";
                            }
                            if (decl.isStatic()) {
                                imports.removeStaticImport(name);
                            } else {
                                imports.removeImport(name);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
    imports.create(needsSave, null);
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IProblem(org.eclipse.jdt.core.compiler.IProblem)

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